Example usage for java.net URL getRef

List of usage examples for java.net URL getRef

Introduction

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

Prototype

public String getRef() 

Source Link

Document

Gets the anchor (also known as the "reference") of this URL .

Usage

From source file:org.motechproject.mmnaija.web.util.HTTPCommunicator.java

public static String doPost(String serviceUrl, String queryString) {
    URLConnection connection = null;
    try {//from   w  ww .jav a 2  s.  c  o  m

        URL url = new URL(serviceUrl);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        url = uri.toURL();
        // Open the connection
        connection = url.openConnection();
        connection.setDoInput(true);
        connection.setUseCaches(false); // Disable caching the document
        connection.setDoOutput(true); // Triggers POST.
        connection.setRequestProperty("Content-Type", "text/html");

        OutputStreamWriter writer = null;

        log.info("About to write");
        try {
            if (null != connection.getOutputStream()) {
                writer = new OutputStreamWriter(connection.getOutputStream());
                writer.write(queryString); // Write POST query

            } else {
                log.warn("connection Null");
            }
            // string.
        } catch (ConnectException ex) {
            log.warn("Exception : " + ex);
            // ex.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception lg) {
                    log.warn("Exception lg: " + lg.toString());
                    //lg.printStackTrace();
                }
            }
        }

        InputStream in = connection.getInputStream();

        //            StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "utf-8");
        String theString = writer.toString();
        return theString;
    } catch (Exception e) {
        //e.printStackTrace();
        log.warn("Error URL " + e.toString());
        return "";
    }
}

From source file:com.familygraph.android.Util.java

/**
 * Parse a URL query and fragment parameters into a key-value bundle.
 * //www  .ja va  2s.  c  om
 * @param url
 *            the URL to parse
 * @return a dictionary bundle of keys and values
 */
public static Bundle parseUrl(String url) {
    // hack to prevent MalformedURLException
    url = url.replace("fgconnect", "http");
    try {
        URL u = new URL(url);
        Bundle b = decodeUrl(u.getQuery());
        b.putAll(decodeUrl(u.getRef()));
        return b;
    } catch (MalformedURLException e) {
        return new Bundle();
    }
}

From source file:luis.clientebanco.OAuth.Utils.java

/**
 * Parse a URL query and fragment parameters into a key-value bundle.
 * //from  www  . j  av  a2 s  .c o m
 * @param url the URL to parse
 * @return a dictionary bundle of keys and values
 */
public static Bundle parseUrl(String url) {
    // hack to prevent MalformedURLException
    url = url.replace("fbconnect", "http");
    url = url.replace("moneyvault", "http");
    try {
        URL u = new URL(url);
        Bundle b = decodeUrl(u.getQuery());
        b.putAll(decodeUrl(u.getRef()));
        return b;
    } catch (MalformedURLException e) {
        return new Bundle();
    }
}

From source file:com.mobli.android.Util.java

/**
 * Parse a URL query and fragment parameters into a key-value bundle.
 * //from w w w . jav a  2 s .  c  o  m
 * @param url
 *            the URL to parse
 * @return a dictionary bundle of keys and values
 */
public static Bundle parseUrl(String url) {

    try {
        URL u = new URL(url);
        Bundle b = decodeUrl(u.getQuery());
        b.putAll(decodeUrl(u.getRef()));
        return b;
    } catch (MalformedURLException e) {
        return new Bundle();
    }
}

From source file:com.janrain.oauth2.OAuth2.java

/**
 * @param redirectUri the redirect_uri (per OAuth2) to validate; may be null, which is permitted/valid
 *
 * @throws ValidationException if the supplied redirectUri fails the OAuth2 prescribed checks
 *//*from   w  w w . jav  a 2s . c o m*/
public static void validateRedirectUri(String redirectUri, @Nullable String expected)
        throws ValidationException {
    if (StringUtils.isNotEmpty(redirectUri)) {
        try {
            URL url = new URL(redirectUri);
            if (StringUtils.isEmpty(url.getProtocol())) {
                throw new ValidationException(OAUTH2_TOKEN_INVALID_REQUEST,
                        "redirect_uri is not absolute: " + redirectUri);
            }
            if (StringUtils.isNotEmpty(url.getRef())) {
                throw new ValidationException(OAUTH2_TOKEN_INVALID_REQUEST,
                        "redirect_uri MUST not contain a fragment: " + redirectUri);
            }
            if (StringUtils.isNotEmpty(expected) && !redirectUri.equals(expected)) {
                throw new ValidationException(OAUTH2_TOKEN_INVALID_GRANT,
                        "Redirect URI mismatch, expected: " + expected);
            }
        } catch (MalformedURLException e) {
            throw new ValidationException(OAUTH2_TOKEN_INVALID_REQUEST,
                    "Invalid redirect_uri: " + e.getMessage());
        }
    }
}

From source file:com.mashape.unirest.android.http.HttpClientHelper.java

private static HttpRequestBase prepareRequest(HttpRequest request, boolean async) {

    Object defaultHeaders = Options.getOption(Option.DEFAULT_HEADERS);
    if (defaultHeaders != null) {
        @SuppressWarnings("unchecked")
        Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet();
        for (Entry<String, String> entry : entrySet) {
            request.header(entry.getKey(), entry.getValue());
        }//from  w  w w.  jav a2 s.  c  om
    }

    if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) {
        request.header(USER_AGENT_HEADER, USER_AGENT);
    }
    if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) {
        request.header(ACCEPT_ENCODING_HEADER, "gzip");
    }

    HttpRequestBase reqObj = null;

    String urlToRequest = null;
    try {
        URL url = new URL(request.getUrl());
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
                URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef());
        urlToRequest = uri.toURL().toString();
        if (url.getQuery() != null && !url.getQuery().trim().equals("")) {
            if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
                urlToRequest += "?";
            }
            urlToRequest += url.getQuery();
        } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
            urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    switch (request.getHttpMethod()) {
    case GET:
        reqObj = new HttpGet(urlToRequest);
        break;
    case POST:
        reqObj = new HttpPost(urlToRequest);
        break;
    case PUT:
        reqObj = new HttpPut(urlToRequest);
        break;
    case DELETE:
        //reqObj = new HttpDeleteWithBody(urlToRequest);
        break;
    case PATCH:
        //reqObj = new HttpPatchWithBody(urlToRequest);
        break;
    case OPTIONS:
        reqObj = new HttpOptions(urlToRequest);
        break;
    case HEAD:
        reqObj = new HttpHead(urlToRequest);
        break;
    }

    Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        List<String> values = entry.getValue();
        if (values != null) {
            for (String value : values) {
                reqObj.addHeader(entry.getKey(), value);
            }
        }
    }

    // Set body
    if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) {
        if (request.getBody() != null) {
            HttpEntity entity = request.getBody().getEntity();
            if (async) {
                if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) {
                    reqObj.setHeader(entity.getContentType());
                }
                try {
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    entity.writeTo(output);
                    NByteArrayEntity en = new NByteArrayEntity(output.toByteArray());
                    ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity);
            }
        }
    }

    return reqObj;
}

From source file:org.apache.jmeter.protocol.http.util.ConversionUtils.java

/**
 * @param url String Url to escape/*from   ww w.jav  a2  s.  com*/
 * @return String cleaned up url
 * @throws Exception when given <code>url</code> leads to a malformed URL or URI
 */
public static String escapeIllegalURLCharacters(String url) throws Exception {
    String decodeUrl = URLDecoder.decode(url, "UTF-8");
    URL urlString = new URL(decodeUrl);
    URI uri = new URI(urlString.getProtocol(), urlString.getUserInfo(), urlString.getHost(),
            urlString.getPort(), urlString.getPath(), urlString.getQuery(), urlString.getRef());
    return uri.toString();
}

From source file:org.fcrepo.localservices.saxon.SaxonServlet.java

/**
 * Return a URL string in which the port is always specified.
 *//*from   w w  w  .ja va  2s  .  c  o  m*/
private static String normalizeURL(String urlString) throws MalformedURLException {
    URL url = new URL(urlString);
    if (url.getPort() == -1) {
        return url.getProtocol() + "://" + url.getHost() + ":" + url.getDefaultPort() + url.getFile()
                + (url.getRef() != null ? "#" + url.getRef() : "");
    } else {
        return urlString;
    }
}

From source file:eu.trentorise.smartcampus.protocolcarrier.Communicator.java

private static HttpRequestBase buildRequest(MessageRequest msgRequest, String appToken, String authToken)
        throws URISyntaxException, UnsupportedEncodingException {
    String host = msgRequest.getTargetHost();
    if (host == null)
        throw new URISyntaxException(host, "null URI");
    if (!host.endsWith("/"))
        host += '/';
    String address = msgRequest.getTargetAddress();
    if (address == null)
        address = "";
    if (address.startsWith("/"))
        address = address.substring(1);/* w  w w .  j a  v a 2  s.  c o m*/
    String uriString = host + address;
    try {
        URL url = new URL(uriString);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        uriString = uri.toURL().toString();
    } catch (MalformedURLException e) {
        throw new URISyntaxException(uriString, e.getMessage());
    }
    if (msgRequest.getQuery() != null)
        uriString += "?" + msgRequest.getQuery();

    //      new URI(uriString);

    HttpRequestBase request = null;
    if (msgRequest.getMethod().equals(Method.POST)) {
        HttpPost post = new HttpPost(uriString);
        HttpEntity httpEntity = null;
        if (msgRequest.getRequestParams() != null) {
            // if body and requestparams are either not null there is an
            // exception
            if (msgRequest.getBody() != null && msgRequest != null) {
                throw new IllegalArgumentException("body and requestParams cannot be either populated");
            }
            httpEntity = new MultipartEntity();

            for (RequestParam param : msgRequest.getRequestParams()) {
                if (param.getParamName() == null || param.getParamName().trim().length() == 0) {
                    throw new IllegalArgumentException("paramName cannot be null or empty");
                }
                if (param instanceof FileRequestParam) {
                    FileRequestParam fileparam = (FileRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(), new ByteArrayBody(
                            fileparam.getContent(), fileparam.getContentType(), fileparam.getFilename()));
                }
                if (param instanceof ObjectRequestParam) {
                    ObjectRequestParam objectparam = (ObjectRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(),
                            new StringBody(convertObject(objectparam.getVars())));
                }
            }
            // mpe.addPart("file",
            // new ByteArrayBody(msgRequest.getFileContent(), ""));
            // post.setEntity(mpe);
        }
        if (msgRequest.getBody() != null) {
            httpEntity = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            ((StringEntity) httpEntity).setContentType(msgRequest.getContentType());
        }
        post.setEntity(httpEntity);
        request = post;
    } else if (msgRequest.getMethod().equals(Method.PUT)) {
        HttpPut put = new HttpPut(uriString);
        if (msgRequest.getBody() != null) {
            StringEntity se = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            se.setContentType(msgRequest.getContentType());
            put.setEntity(se);
        }
        request = put;
    } else if (msgRequest.getMethod().equals(Method.DELETE)) {
        request = new HttpDelete(uriString);
    } else {
        // default: GET
        request = new HttpGet(uriString);
    }

    Map<String, String> headers = new HashMap<String, String>();

    // default headers
    if (appToken != null) {
        headers.put(RequestHeader.APP_TOKEN.toString(), appToken);
    }
    if (authToken != null) {
        // is here for compatibility
        headers.put(RequestHeader.AUTH_TOKEN.toString(), authToken);
        headers.put(RequestHeader.AUTHORIZATION.toString(), "Bearer " + authToken);
    }
    headers.put(RequestHeader.ACCEPT.toString(), msgRequest.getContentType());

    if (msgRequest.getCustomHeaders() != null) {
        headers.putAll(msgRequest.getCustomHeaders());
    }

    for (String key : headers.keySet()) {
        request.addHeader(key, headers.get(key));
    }

    return request;
}

From source file:org.codice.ddf.catalog.content.monitor.DavEntry.java

static String getLocation(String initialLocation, DavEntry parent) {
    String location = initialLocation;
    if (parent != null && !location.startsWith(HTTP)) {
        String parentLocation = parent.getLocation();
        if (parentLocation.endsWith(FORSLASH) && location.startsWith(FORSLASH)) {
            location = location.replaceFirst(FORSLASH, "");
        }/*  ww  w .ja v a2s.c  om*/
        if (!parentLocation.endsWith(FORSLASH) && !location.startsWith(FORSLASH)) {
            location = FORSLASH + location;
        }
        location = parentLocation + location;
    }
    try {
        // URL class performs structural decomposition of location for us
        // URI class performs character encoding, but ONLY via multipart constructors
        // Finally, we have a fully qualified and escaped location for future manipulation
        URL url = new URL(location);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        location = uri.toASCIIString();
    } catch (MalformedURLException | URISyntaxException e) {
        throw new RuntimeException(e);
    }
    return location;
}