Example usage for java.net URI getFragment

List of usage examples for java.net URI getFragment

Introduction

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

Prototype

public String getFragment() 

Source Link

Document

Returns the decoded fragment component of this URI.

Usage

From source file:org.apache.any23.http.DefaultHTTPClient.java

/**
 *
 * Opens an {@link java.io.InputStream} from a given URI.
 * It follows redirects.//from  w w  w .j av a 2  s. co m
 *
 * @param uri to be opened
 * @return {@link java.io.InputStream}
 * @throws IOException
 */
public InputStream openInputStream(String uri) throws IOException {
    GetMethod method = null;
    try {
        ensureClientInitialized();
        String uriStr;
        try {
            URI uriObj = new URI(uri);
            // [scheme:][//authority][path][?query][#fragment]
            final String path = uriObj.getPath();
            final String query = uriObj.getQuery();
            final String fragment = uriObj.getFragment();
            uriStr = String
                    .format("%s://%s%s%s%s%s%s", uriObj.getScheme(), uriObj.getAuthority(),
                            path != null ? URLEncoder.encode(path, "UTF-8").replaceAll("%2F", "/") : "",
                            query == null ? "" : "?",
                            query != null ? URLEncoder.encode(query, "UTF-8").replaceAll("%3D", "=")
                                    .replaceAll("%26", "&") : "",
                            fragment == null ? "" : "#",
                            fragment != null ? URLEncoder.encode(fragment, "UTF-8") : "");
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("Invalid URI string.", e);
        }
        method = new GetMethod(uriStr);
        method.setFollowRedirects(true);
        client.executeMethod(method);
        _contentLength = method.getResponseContentLength();
        final Header contentTypeHeader = method.getResponseHeader("Content-Type");
        contentType = contentTypeHeader == null ? null : contentTypeHeader.getValue();
        if (method.getStatusCode() != 200) {
            throw new IOException(
                    "Failed to fetch " + uri + ": " + method.getStatusCode() + " " + method.getStatusText());
        }
        actualDocumentURI = method.getURI().toString();
        byte[] response = method.getResponseBody();

        return new ByteArrayInputStream(response);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:org.opendatakit.aggregate.servlet.MultimodeLoginPageServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    CallingContext cc = ContextFactory.getCallingContext(this, req);

    // Check to make sure we are using the canonical server name.
    // If not, redirect to that name.  This ensures that authentication
    // cookies will have the proper realm(s) established for them.
    String newUrl = cc.getServerURL() + BasicConsts.FORWARDSLASH + ADDR;
    String query = req.getQueryString();
    if (query != null && query.length() != 0) {
        newUrl += "?" + query;
    }/*  w w  w. j  a  va  2 s  .  co  m*/
    URL url = new URL(newUrl);
    if (!url.getHost().equalsIgnoreCase(req.getServerName())) {
        logger.info("Incoming servername: " + req.getServerName() + " expected: " + url.getHost()
                + " -- redirecting.");
        // try to get original destination URL from Spring...
        String redirectUrl = getRedirectUrl(req, ADDR);
        try {
            URI uriChangeable = new URI(redirectUrl);
            URI newUri = new URI(url.getProtocol(), null, url.getHost(), url.getPort(), uriChangeable.getPath(),
                    uriChangeable.getQuery(), uriChangeable.getFragment());
            newUrl = newUri.toString();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        // go to the proper page (we'll most likely be redirected back to here for authentication)
        resp.sendRedirect(newUrl);
        return;
    }

    // OK. We are using the canonical server name.
    String redirectParamString = getRedirectUrl(req, AggregateHtmlServlet.ADDR);
    // we need to appropriately cleanse this string for the OpenID login
    // strip off the server pathname portion
    if (redirectParamString.startsWith(cc.getSecureServerURL())) {
        redirectParamString = redirectParamString.substring(cc.getSecureServerURL().length());
    } else if (redirectParamString.startsWith(cc.getServerURL())) {
        redirectParamString = redirectParamString.substring(cc.getServerURL().length());
    }
    while (redirectParamString.startsWith("/")) {
        redirectParamString = redirectParamString.substring(1);
    }

    // check for XSS attacks. The redirect string is emitted within single and double
    // quotes. It is a URL with :, /, ? and # characters. But it should not contain 
    // quotes, parentheses or semicolons.
    String cleanString = redirectParamString.replaceAll(BAD_PARAMETER_CHARACTERS, "");
    if (!cleanString.equals(redirectParamString)) {
        logger.warn("XSS cleanup -- redirectParamString has forbidden characters: " + redirectParamString);
        redirectParamString = cleanString;
    }

    logger.info("Invalidating login session " + req.getSession().getId());
    // Invalidate session.
    HttpSession s = req.getSession();
    if (s != null) {
        s.invalidate();
    }
    // Display page.
    resp.setContentType(HtmlConsts.RESP_TYPE_HTML);
    resp.setCharacterEncoding(HtmlConsts.UTF8_ENCODE);
    resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    resp.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
    resp.setHeader("Pragma", "no-cache");
    resp.addHeader(HtmlConsts.X_FRAME_OPTIONS, HtmlConsts.X_FRAME_SAMEORIGIN);
    PrintWriter out = resp.getWriter();
    out.print(
            "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"
                    + "<html>" + "<head>"
                    + "<meta http-equiv=\"cache-control\" content=\"no-store, no-cache, must-revalidate\"/>"
                    + "<meta http-equiv=\"expires\" content=\"Mon, 26 Jul 1997 05:00:00 GMT\"/>"
                    + "<meta http-equiv=\"pragma\" content=\"no-cache\"/>"
                    + "<link rel=\"icon\" href=\"favicon.ico\"/>" + "<title>Log onto Aggregate</title>"
                    + "<link type=\"text/css\" rel=\"stylesheet\" href=\"AggregateUI.css\">"
                    + "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheets/button.css\">"
                    + "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheets/table.css\">"
                    + "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheets/navigation.css\">"
                    + "<script type=\"text/javascript\">" + "window.onbeforeunload=function() {\n"
                    + "var e=document.getElementById(\"stale\");\n" + "e.value=\"yes\";\n" + "}\n"
                    + "window.onload=function(){\n" + "var e=document.getElementById(\"stale\");\n"
                    + "if(e.value==\"yes\") {window.location.reload(true);}\n" + "}\n" + "</script>" + "</head>"
                    + "<body>" + "<input type=\"hidden\" id=\"stale\" value=\"no\">"
                    + "<table width=\"100%\" cellspacing=\"30\"><tr>"
                    + "<td align=\"LEFT\" width=\"10%\"><img src=\"odk_color.png\" id=\"odk_aggregate_logo\" /></td>"
                    + "<td align=\"LEFT\" width=\"90%\"><font size=\"7\">Log onto Aggregate</font></td></tr></table>"
                    + "<table cellspacing=\"20\">" + "<tr><td valign=\"top\">"
                    + "<form action=\"local_login.html\" method=\"get\">" + "<script type=\"text/javascript\">"
                    + "<!--\n" + "document.write('<input name=\"redirect\" type=\"hidden\" value=\""
                    + redirectParamString + "' + window.location.hash + '\"/>');" + "\n-->" + "</script>"
                    + "<input class=\"gwt-Button\" type=\"submit\" value=\"Sign in with Aggregate password\"/>"
                    + "</form></td>"
                    + "<td valign=\"top\">Click this button to log onto Aggregate using the username "
                    + "and password that have been assigned to you by the Aggregate site administrator.</td></tr>"
                    + "<tr><td valign=\"top\">" + "<script type=\"text/javascript\">" + "<!--\n"
                    + "document.write('<form action=\"" + redirectParamString
                    + "' + window.location.hash + '\" method=\"get\">');"
                    + "document.write('<input class=\"gwt-Button\" type=\"submit\" value=\"Anonymous Access\"/></form>');"
                    + "\n-->" + "</script>" + "</td>"
                    + "<td valign=\"top\">Click this button to access Aggregate without logging in.</td></tr>"
                    + "</table>" + "</body>" + "</html>");
}

From source file:org.nuxeo.ecm.restapi.server.jaxrs.resource.wro.ResourceBundleWriter.java

@Override
public void writeTo(ResourceBundleDispatcher arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4,
        MultivaluedMap<String, Object> arg5, OutputStream arg6) throws IOException, WebApplicationException {
    try {//  w ww  .  j  a va2s  .  co m
        URI uri = uriInfo.getRequestUri();
        String path = uri.getPath();
        // remove lead /nuxeo
        path = path.replaceFirst(servletContext.getContextPath(), "");
        // redirect to the wro servlet path
        path = path.replaceFirst("/site/api/", "/wapi/");
        URI dispatch = new URI(null, null, path, uri.getQuery(), uri.getFragment());
        servletContext.getRequestDispatcher(dispatch.toString()).forward(request, response);
    } catch (URISyntaxException | ServletException e) {
        log.error("Error while forwarding to Wro servlet", e);
    }
}

From source file:org.rhq.enterprise.clientapi.RhqDownloadsScriptSourceProvider.java

@Override
protected Reader doGetScriptSource(URI scriptUri) {
    if (remoteClient == null) {
        return null;
    }//ww w.j av  a  2s.  co  m

    String path = scriptUri.getPath();

    URI remoteUri = remoteClient.getRemoteURI().resolve(URL_PATH_PREFIX + path);

    String replacementScheme = SecurityUtil.isTransportSecure(remoteUri.getScheme()) ? "https" : "http";

    try {
        remoteUri = new URI(replacementScheme, remoteUri.getAuthority(), remoteUri.getPath(),
                remoteUri.getQuery(), remoteUri.getFragment());
    } catch (URISyntaxException e) {
        LOG.error("Failed to copy the RHQ server download URI: " + remoteUri + " to the " + replacementScheme
                + " scheme.");
    }

    try {
        URL downloadUrl = remoteUri.toURL();

        return new InputStreamReader(downloadUrl.openStream());
    } catch (MalformedURLException e) {
        LOG.debug("Failed to download the script from the RHQ server using URL: " + remoteUri, e);
    } catch (IOException e) {
        LOG.debug("Failed to download the script from the RHQ server using URL: " + remoteUri, e);
    }

    return null;
}

From source file:org.fcrepo.apix.jena.impl.JenaServiceRegistry.java

@Override
public void update(final URI uri) {
    if (hasInDomain(uri) && uri.getFragment() == null) {
        // TODO: This can be optimized more. Right now, it re-scans all services,
        // but at least filters out obvious redundancies (hash URIs) or inapplicable resources
        update();/*from w ww .j  a va 2 s  .c  o  m*/
    }
}

From source file:org.gatherdata.alert.notify.mail.internal.EmailNotifier.java

public boolean canSendTo(URI notificationAddress) {
    log.debug("canSendTo(" + notificationAddress + ")");
    log.debug("\t scheme:" + notificationAddress.getScheme());
    log.debug("\t scheme specific:" + notificationAddress.getSchemeSpecificPart());
    log.debug("\t fragment:" + notificationAddress.getFragment());
    log.debug("\t host:" + notificationAddress.getHost());
    log.debug("\t path:" + notificationAddress.getPath());
    try {// w ww .j av a2s  .  c om
        log.debug("\t as URL:" + notificationAddress.toURL());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return SCHEME_TYPES.contains(notificationAddress.getScheme());
}

From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java

/**
 * @param request   a RestRequest object to be encoded as a tunneled POST
 * @param requestContext a RequestContext object associated with the request
 * @param threshold the size of the query params above which the request will be encoded
 *
 * @return an encoded RestRequest/*from ww w  . j  a  v  a2s  .  c om*/
 */
public static RestRequest encode(final RestRequest request, RequestContext requestContext, int threshold)
        throws URISyntaxException, MessagingException, IOException {
    URI uri = request.getURI();

    // Check to see if we should tunnel this request by testing the length of the query
    // if the query is NULL, we won't bother to encode.
    // 0 length is a special case that could occur with a url like http://www.foo.com?
    // which we don't want to encode, because we'll lose the "?" in the process
    // Otherwise only encode queries whose length is greater than or equal to the
    // threshold value.

    String query = uri.getRawQuery();

    boolean forceQueryTunnel = requestContext.getLocalAttr(R2Constants.FORCE_QUERY_TUNNEL) != null
            && (Boolean) requestContext.getLocalAttr(R2Constants.FORCE_QUERY_TUNNEL);

    if (query == null || query.length() == 0 || (query.length() < threshold && !forceQueryTunnel)) {
        return request;
    }

    RestRequestBuilder requestBuilder = new RestRequestBuilder(request);

    // reconstruct URI without query
    uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null,
            uri.getFragment());

    // If there's no existing body, just pass the request as x-www-form-urlencoded
    ByteString entity = request.getEntity();
    if (entity == null || entity.length() == 0) {
        requestBuilder.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED);
        requestBuilder.setEntity(ByteString.copyString(query, Data.UTF_8_CHARSET));
    } else {
        // If we have a body, we must preserve it, so use multipart/mixed encoding

        MimeMultipart multi = createMultiPartEntity(entity, request.getHeader(HEADER_CONTENT_TYPE), query);
        requestBuilder.setHeader(HEADER_CONTENT_TYPE, multi.getContentType());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        multi.writeTo(os);
        requestBuilder.setEntity(ByteString.copy(os.toByteArray()));
    }

    // Set the base uri, supply the original method in the override header, and change method to POST
    requestBuilder.setURI(uri);
    requestBuilder.setHeader(HEADER_METHOD_OVERRIDE, requestBuilder.getMethod());
    requestBuilder.setMethod(RestMethod.POST);

    return requestBuilder.build();
}

From source file:com.jgoetsch.eventtrader.source.SocketIOWebSocketMsgSource.java

protected String getTokenUrl() throws IOException, URISyntaxException {
    URI base = new URI(getUrl());
    BufferedReader tokenReader = new BufferedReader(
            new InputStreamReader(new URI("http", base.getUserInfo(), base.getHost(), base.getPort(),
                    base.getPath(), base.getQuery(), base.getFragment()).toURL().openStream()));
    String token = tokenReader.readLine();
    tokenReader.close();/*from w w w.  ja va2 s.  c  o  m*/

    String r[] = token.split(":");
    String comp[] = getUrl().split("\\?");
    if (!comp[0].endsWith("/"))
        comp[0] += '/';
    return comp[0] + "websocket/" + r[0] + (comp.length > 0 ? "?" + comp[1] : "");
}

From source file:com.buaa.cfs.utils.NetUtils.java

/**
 * Resolve the uri's hostname and add the default port if not in the uri
 *
 * @param uri         to resolve//from w  w w . j a v a2  s .c  o  m
 * @param defaultPort if none is given
 *
 * @return URI
 */
public static URI getCanonicalUri(URI uri, int defaultPort) {
    // skip if there is no authority, ie. "file" scheme or relative uri
    String host = uri.getHost();
    if (host == null) {
        return uri;
    }
    String fqHost = canonicalizeHost(host);
    int port = uri.getPort();
    // short out if already canonical with a port
    if (host.equals(fqHost) && port != -1) {
        return uri;
    }
    // reconstruct the uri with the canonical host and port
    try {
        uri = new URI(uri.getScheme(), uri.getUserInfo(), fqHost, (port == -1) ? defaultPort : port,
                uri.getPath(), uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
    return uri;
}