org.eclipse.jetty.util.URIUtil Java Examples

The following examples show how to use org.eclipse.jetty.util.URIUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OWLServer.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private CharSequence getLocationInfo(HttpServletRequest request) {
	StringBuilder sb = new StringBuilder();
	String scheme = request.getScheme();
       int port = request.getServerPort();

       sb.append(scheme);
       sb.append("://");
       sb.append(request.getServerName());
       if (port>0 && 
           ((scheme.equalsIgnoreCase(URIUtil.HTTP) && port != 80) || 
            (scheme.equalsIgnoreCase(URIUtil.HTTPS) && port != 443)))
       {
       	sb.append(':');
       	sb.append(port);
       }
	return sb;
}
 
Example #2
Source File: HttpRequestFactory.java    From vespa with Apache License 2.0 5 votes vote down vote up
public static URI getUri(HttpServletRequest servletRequest) {
    try {
        StringBuffer builder = new StringBuffer(128);
        URIUtil.appendSchemeHostPort(builder, servletRequest.getScheme(), servletRequest.getServerName(), getConnectorLocalPort(servletRequest));
        builder.append(servletRequest.getRequestURI());
        String query = servletRequest.getQueryString();
        if (query != null) {
            builder.append('?').append(query);
        }
        return URI.create(builder.toString());
    } catch (IllegalArgumentException e) {
        throw createBadQueryException(e);
    }
}
 
Example #3
Source File: SecuredRedirectHandler.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(String target, Request request, HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException, ServletException {
    int localPort = getConnectorLocalPort(servletRequest);
    if (!redirectMap.containsKey(localPort)) {
        _handler.handle(target, request, servletRequest, servletResponse);
        return;
    }
    servletResponse.setContentLength(0);
    if (!servletRequest.getRequestURI().equals(HEALTH_CHECK_PATH)) {
        servletResponse.sendRedirect(
                URIUtil.newURI("https", request.getServerName(), redirectMap.get(localPort), request.getRequestURI(), request.getQueryString()));
    }
    request.setHandled(true);
}
 
Example #4
Source File: URLResource.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
/**
 * Returns the resource contained inside the current resource with the
 * given name
 */
@Override
public Resource addPath(String path)
    throws IOException,MalformedURLException
{
    if (path==null)
        return null;

    path = URIUtil.canonicalPath(path);

    return newResource(URIUtil.addPaths(_url.toExternalForm(),path));
}
 
Example #5
Source File: URLResource.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
/**
 * Returns the resource contained inside the current resource with the
 * given name
 */
@Override
public Resource addPath(String path)
    throws IOException,MalformedURLException
{
    if (path==null)
        return null;

    path = URIUtil.canonicalPath(path);

    return newResource(URIUtil.addPaths(_url.toExternalForm(),path));
}
 
Example #6
Source File: RestServlet.java    From chipster with MIT License 5 votes vote down vote up
private File locateFile(HttpServletRequest request) throws ServletException {
	String requestPath = URIUtil.addPaths(request.getServletPath(), request.getPathInfo());
	String realPath = getServletContext().getRealPath(requestPath);
	if (realPath == null) {
		throw new ServletException("Servlet context refused to convert a request path to a real path. Make sure that serving files through symlinks is enabled");
	}
	return new File(realPath);		
}
 
Example #7
Source File: FileResource.java    From IoTgo_Android_App with MIT License 4 votes vote down vote up
@Override
public Resource addPath(String path)
    throws IOException,MalformedURLException
{
    URLResource r=null;
    String url=null;

    path = org.eclipse.jetty.util.URIUtil.canonicalPath(path);
   
    if ("/".equals(path))
        return this;
    else if (!isDirectory())
    {
        r=(FileResource)super.addPath(path);
        url=r._urlString;
    }
    else
    {
        if (path==null)
            throw new MalformedURLException();   
        
        // treat all paths being added as relative
        String rel=path;
        if (path.startsWith("/"))
            rel = path.substring(1);
        
        url=URIUtil.addPaths(_urlString,URIUtil.encodePath(rel));
        r=(URLResource)Resource.newResource(url);
    }
    
    // Check for encoding aliases
    // The encoded path should be a suffix of the resource (give or take a directory / )
    String encoded=URIUtil.encodePath(path);
    int expected=r.toString().length()-encoded.length();
    int index = r._urlString.lastIndexOf(encoded, expected);
    if (expected!=index && ((expected-1)!=index || path.endsWith("/") || !r.isDirectory()))
    {
        if (r instanceof FileResource)
        {
            ((FileResource)r)._alias=((FileResource)r)._file.getCanonicalFile().toURI().toURL();
            ((FileResource)r)._aliasChecked=true;
        }
    }                             
    return r;
}
 
Example #8
Source File: Resource.java    From IoTgo_Android_App with MIT License 4 votes vote down vote up
/** Get the resource list as a HTML directory listing.
    * @param base The base URL
    * @param parent True if the parent directory should be included
    * @return String of HTML
    */
   public String getListHTML(String base,boolean parent)
       throws IOException
   {
       base=URIUtil.canonicalPath(base);
       if (base==null || !isDirectory())
           return null;
       
       String[] ls = list();
       if (ls==null)
           return null;
       Arrays.sort(ls);
       
       String decodedBase = URIUtil.decodePath(base);
       String title = "Directory: "+deTag(decodedBase);

       StringBuilder buf=new StringBuilder(4096);
       buf.append("<HTML><HEAD>");
       buf.append("<LINK HREF=\"").append("jetty-dir.css").append("\" REL=\"stylesheet\" TYPE=\"text/css\"/><TITLE>");
       buf.append(title);
       buf.append("</TITLE></HEAD><BODY>\n<H1>");
       buf.append(title);
       buf.append("</H1>\n<TABLE BORDER=0>\n");
       
       if (parent)
       {
           buf.append("<TR><TD><A HREF=\"");
           buf.append(URIUtil.addPaths(base,"../"));
           buf.append("\">Parent Directory</A></TD><TD></TD><TD></TD></TR>\n");
       }
       
       String encodedBase = hrefEncodeURI(base);
       
       DateFormat dfmt=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
                                                      DateFormat.MEDIUM);
       for (int i=0 ; i< ls.length ; i++)
       {
           Resource item = addPath(ls[i]);
           
           buf.append("\n<TR><TD><A HREF=\"");
           String path=URIUtil.addPaths(encodedBase,URIUtil.encodePath(ls[i]));
           
           buf.append(path);
           
           if (item.isDirectory() && !path.endsWith("/"))
               buf.append(URIUtil.SLASH);
           
           // URIUtil.encodePath(buf,path);
           buf.append("\">");
           buf.append(deTag(ls[i]));
           buf.append("&nbsp;");
           buf.append("</A></TD><TD ALIGN=right>");
           buf.append(item.length());
           buf.append(" bytes&nbsp;</TD><TD>");
           buf.append(dfmt.format(new Date(item.lastModified())));
           buf.append("</TD></TR>");
       }
       buf.append("</TABLE>\n");
buf.append("</BODY></HTML>\n");
       
       return buf.toString();
   }
 
Example #9
Source File: FileResource.java    From IoTgo_Android_App with MIT License 4 votes vote down vote up
@Override
public Resource addPath(String path)
    throws IOException,MalformedURLException
{
    URLResource r=null;
    String url=null;

    path = org.eclipse.jetty.util.URIUtil.canonicalPath(path);
   
    if ("/".equals(path))
        return this;
    else if (!isDirectory())
    {
        r=(FileResource)super.addPath(path);
        url=r._urlString;
    }
    else
    {
        if (path==null)
            throw new MalformedURLException();   
        
        // treat all paths being added as relative
        String rel=path;
        if (path.startsWith("/"))
            rel = path.substring(1);
        
        url=URIUtil.addPaths(_urlString,URIUtil.encodePath(rel));
        r=(URLResource)Resource.newResource(url);
    }
    
    // Check for encoding aliases
    // The encoded path should be a suffix of the resource (give or take a directory / )
    String encoded=URIUtil.encodePath(path);
    int expected=r.toString().length()-encoded.length();
    int index = r._urlString.lastIndexOf(encoded, expected);
    if (expected!=index && ((expected-1)!=index || path.endsWith("/") || !r.isDirectory()))
    {
        if (r instanceof FileResource)
        {
            ((FileResource)r)._alias=((FileResource)r)._file.getCanonicalFile().toURI().toURL();
            ((FileResource)r)._aliasChecked=true;
        }
    }                             
    return r;
}
 
Example #10
Source File: Resource.java    From IoTgo_Android_App with MIT License 4 votes vote down vote up
/** Get the resource list as a HTML directory listing.
    * @param base The base URL
    * @param parent True if the parent directory should be included
    * @return String of HTML
    */
   public String getListHTML(String base,boolean parent)
       throws IOException
   {
       base=URIUtil.canonicalPath(base);
       if (base==null || !isDirectory())
           return null;
       
       String[] ls = list();
       if (ls==null)
           return null;
       Arrays.sort(ls);
       
       String decodedBase = URIUtil.decodePath(base);
       String title = "Directory: "+deTag(decodedBase);

       StringBuilder buf=new StringBuilder(4096);
       buf.append("<HTML><HEAD>");
       buf.append("<LINK HREF=\"").append("jetty-dir.css").append("\" REL=\"stylesheet\" TYPE=\"text/css\"/><TITLE>");
       buf.append(title);
       buf.append("</TITLE></HEAD><BODY>\n<H1>");
       buf.append(title);
       buf.append("</H1>\n<TABLE BORDER=0>\n");
       
       if (parent)
       {
           buf.append("<TR><TD><A HREF=\"");
           buf.append(URIUtil.addPaths(base,"../"));
           buf.append("\">Parent Directory</A></TD><TD></TD><TD></TD></TR>\n");
       }
       
       String encodedBase = hrefEncodeURI(base);
       
       DateFormat dfmt=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
                                                      DateFormat.MEDIUM);
       for (int i=0 ; i< ls.length ; i++)
       {
           Resource item = addPath(ls[i]);
           
           buf.append("\n<TR><TD><A HREF=\"");
           String path=URIUtil.addPaths(encodedBase,URIUtil.encodePath(ls[i]));
           
           buf.append(path);
           
           if (item.isDirectory() && !path.endsWith("/"))
               buf.append(URIUtil.SLASH);
           
           // URIUtil.encodePath(buf,path);
           buf.append("\">");
           buf.append(deTag(ls[i]));
           buf.append("&nbsp;");
           buf.append("</A></TD><TD ALIGN=right>");
           buf.append(item.length());
           buf.append(" bytes&nbsp;</TD><TD>");
           buf.append(dfmt.format(new Date(item.lastModified())));
           buf.append("</TD></TR>");
       }
       buf.append("</TABLE>\n");
buf.append("</BODY></HTML>\n");
       
       return buf.toString();
   }
 
Example #11
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private Authentication handleSignInRequest(HttpServletRequest request, HttpServletResponse response,
                                           HttpSession session, FedizContext fedConfig) throws IOException {
    FedizResponse wfRes = null;
    if (LOG.isDebugEnabled()) {
        LOG.debug("SignIn request found");
    }

    String action = request.getParameter(FederationConstants.PARAM_ACTION);
    String responseToken = getResponseToken(request, fedConfig);
    if (responseToken == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("SignIn request must contain a response token from the IdP");
        }
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return Authentication.SEND_FAILURE;
    } else {

        FedizRequest wfReq = new FedizRequest();
        wfReq.setAction(action);
        wfReq.setResponseToken(responseToken);
        wfReq.setState(getState(request));
        wfReq.setRequest(request);
        wfReq.setRequestState((RequestState) session.getAttribute(J_CONTEXT));

        X509Certificate[] certs =
            (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");
        wfReq.setCerts(certs);

        FederationLoginService fedLoginService = (FederationLoginService)this._loginService;
        UserIdentity user = fedLoginService.login(null, wfReq, fedConfig);
        if (user != null) {
            session = renewSession(request, response);

            // Redirect to original request
            String nuri;
            synchronized (session) {
                // Check the context
                RequestState savedRequestState = (RequestState) session.getAttribute(J_CONTEXT);
                String receivedContext = getState(request);
                if (savedRequestState == null || !savedRequestState.getState().equals(receivedContext)) {
                    LOG.warn("The received wctx/RelayState parameter does not match the saved value");
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return Authentication.UNAUTHENTICATED;
                }

                nuri = (String) session.getAttribute(J_URI);

                if (nuri == null || nuri.length() == 0) {
                    nuri = request.getContextPath();
                    if (nuri.length() == 0) {
                        nuri = URIUtil.SLASH;
                    }
                }
                Authentication cached = new SessionAuthentication(getAuthMethod(), user, wfRes);
                session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, cached);
            }

            FederationUserIdentity fui = (FederationUserIdentity)user;
            session.setAttribute(SECURITY_TOKEN_ATTR, fui.getToken());

            response.setContentLength(0);
            response.sendRedirect(response.encodeRedirectURL(nuri));

            return new FederationAuthentication(getAuthMethod(), user);
        }

        // not authenticated
        if (LOG.isDebugEnabled()) {
            LOG.debug("WSFED authentication FAILED");
        }
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return Authentication.UNAUTHENTICATED;
    }
}
 
Example #12
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private Authentication handleCachedAuthentication(HttpServletRequest request, HttpServletResponse response,
                                                  HttpSession session, FedizContext fedConfig) throws IOException {
    Authentication authentication =
        (Authentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
    if (authentication != null) {
        // Has authentication been revoked?
        if (authentication instanceof Authentication.User
            && isTokenExpired(fedConfig, ((Authentication.User)authentication).getUserIdentity())) {
            session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
        } else {
            //logout
            String action = request.getParameter(FederationConstants.PARAM_ACTION);
            boolean logout = FederationConstants.ACTION_SIGNOUT.equals(action);
            String logoutUrl = fedConfig.getLogoutURL();

            String uri = request.getRequestURI();
            if (uri == null) {
                uri = URIUtil.SLASH;
            }

            String contextName = request.getSession().getServletContext().getContextPath();
            if (contextName == null || contextName.isEmpty()) {
                contextName = "/";
            }

            if (logout || logoutUrl != null && !logoutUrl.isEmpty() && uri.equals(contextName + logoutUrl)) {
                session.invalidate();

                FedizProcessor wfProc =
                    FedizProcessorFactory.newFedizProcessor(fedConfig.getProtocol());
                signOutRedirectToIssuer(request, response, wfProc);

                return Authentication.SEND_CONTINUE;
            }

            String jUri = (String)session.getAttribute(J_URI);
            @SuppressWarnings("unchecked")
            MultiMap<String> jPost = (MultiMap<String>)session.getAttribute(J_POST);
            if (jUri != null && jPost != null) {
                StringBuffer buf = request.getRequestURL();
                if (request.getQueryString() != null) {
                    buf.append('?').append(request.getQueryString());
                }

                if (jUri.equals(buf.toString())) {
                    // This is a retry of an original POST request
                    // so restore method and parameters

                    session.removeAttribute(J_POST);
                    Request baseRequest = (Request)request;
                    // (req instanceof Request)?(Request)
                    // req:HttpConnection.getCurrentConnection().getRequest();
                    baseRequest.setMethod(HttpMethod.POST.asString());
                    baseRequest.setQueryParameters(jPost);
                }
            } else if (jUri != null) {
                session.removeAttribute(J_URI);
            }

            return authentication;
        }
    }
    return null;
}
 
Example #13
Source File: Resource.java    From IoTgo_Android_App with MIT License 2 votes vote down vote up
/** Encode according to this resource type.
 * The default implementation calls URI.encodePath(uri)
 * @param uri 
 * @return String encoded for this resource type.
 */
public String encode(String uri)
{
    return URIUtil.encodePath(uri);
}
 
Example #14
Source File: Resource.java    From IoTgo_Android_App with MIT License 2 votes vote down vote up
/** Encode according to this resource type.
 * The default implementation calls URI.encodePath(uri)
 * @param uri 
 * @return String encoded for this resource type.
 */
public String encode(String uri)
{
    return URIUtil.encodePath(uri);
}