Example usage for javax.servlet.http HttpServletRequest getPathInfo

List of usage examples for javax.servlet.http HttpServletRequest getPathInfo

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getPathInfo.

Prototype

public String getPathInfo();

Source Link

Document

Returns any extra path information associated with the URL the client sent when it made this request.

Usage

From source file:com.adito.boot.Util.java

/**
 * Dump all request parameters and some other useful stuff from
 * the request to {@link System#err}/*from  w w  w. jav a  2 s . c  o m*/
 * 
 * @param request request to get parameters from
 */
public static void dumpRequest(HttpServletRequest request) {
    System.err.println("Context Path " + request.getContextPath());
    System.err.println("Path Translated " + request.getPathTranslated());
    System.err.println("Path Info " + request.getPathInfo());
    System.err.println("Query: " + request.getQueryString());
    System.err.println("Request URI: " + request.getRequestURI());
    System.err.println("Request URL: " + request.getRequestURL());
    System.err.println("Is Secure: " + request.isSecure());
    System.err.println("Scheme: " + request.getScheme());
    dumpRequestParameters(request);
    dumpRequestAttributes(request);
    dumpRequestHeaders(request);

}

From source file:edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet.java

private String getCurrentPageUrl(HttpServletRequest request) {
    String path = request.getServletPath().replaceFirst("/", "");
    String pathInfo = request.getPathInfo();
    if (pathInfo != null) {
        path += pathInfo;//  w w  w . j a  v a 2 s .co  m
    }
    path = normalizeServletName(path);
    return UrlBuilder.getUrl(path);
}

From source file:com.doitnext.http.router.RestRouterServlet.java

protected boolean routeRequest(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) {
    SortedSet<Route> routes = this.routes;
    List<PathMatch> pathMatches = new ArrayList<PathMatch>();
    String pathString = req.getPathInfo();
    for (Route route : routes) {
        if (logger.isTraceEnabled()) {
            logger.trace(String.format("Trying to match path '%s' against '%s'", pathString, route.toString()));
        }/*w w w .  j  a  v  a 2  s  .c  o  m*/
        Path path = route.getPathTemplate().match(pathString);
        if (path != null) {
            if (logger.isTraceEnabled()) {
                logger.trace(String.format("Matched path '%s' against '%s'", pathString, route));
            }
            pathMatches.add(new PathMatch(route, path));
        }
    }
    if (pathMatches.isEmpty())
        return do404(method, req, resp); // Resource not found
    else if (logger.isTraceEnabled())
        logger.trace(String.format("There are %d routes that match by uri path.", pathMatches.size()));

    List<PathMatch> pathMatchesByPathAndMethod = new ArrayList<PathMatch>();
    Set<HttpMethod> allowedMethods = new TreeSet<HttpMethod>();
    for (PathMatch pm : pathMatches) {
        if (pm.getRoute().getHttpMethod().equals(method)) {
            pathMatchesByPathAndMethod.add(pm);
            if (logger.isTraceEnabled()) {
                logger.trace(String.format("Http request method: %s matches route %s", method.name(),
                        pm.getRoute()));
            }
        } else {
            allowedMethods.add(pm.getRoute().getHttpMethod());
            if (logger.isTraceEnabled()) {
                logger.trace(String.format(
                        "Http request method: %s does not match route %s.  This route will be excluded from further consideration.",
                        method.name(), pm.getRoute()));
            }
        }
    }

    if (pathMatchesByPathAndMethod.isEmpty()) {
        List<String> am = new ArrayList<String>();
        for (HttpMethod m : allowedMethods)
            am.add(m.name());
        return do405(method, am, req, resp);
    }

    String acceptTypes = req.getHeader("Accept");
    String accepts[] = acceptTypes.split(",");
    List<AcceptKey> acceptKeys = new ArrayList<AcceptKey>();
    for (String accept : accepts) {
        acceptKeys.add(new AcceptKey(accept.trim()));
    }
    List<PathMatch> pathMatchesByResponseType = new ArrayList<PathMatch>();
    for (PathMatch pm : pathMatchesByPathAndMethod) {
        // If this is a wildcard return method just add it 
        if (pm.getRoute().isWildcardReturn()) {
            pathMatchesByResponseType.add(pm);
        } else {
            for (AcceptKey acceptKey : acceptKeys) {
                if (acceptKey.matches(pm.getRoute())) {
                    pathMatchesByResponseType.add(pm);
                    if (logger.isTraceEnabled()) {
                        logger.trace(
                                String.format("Accept key: %s matches route %s", acceptKey, pm.getRoute()));
                    }
                } else if (logger.isTraceEnabled()) {
                    logger.trace(String.format(
                            "Accept key: %s does not match route %s.  This route will be excluded from further consideration.",
                            acceptKey, pm.getRoute()));
                }
            }
        }
    }
    // If a route exists with empty return type and the request has empty return
    // type then remove routes that have non empty return types (except for wildcard returns)
    for (AcceptKey key : acceptKeys) {
        if (StringUtils.isEmpty(key.getReturnType())) {
            for (PathMatch pm : pathMatchesByResponseType) {
                if (pm.getRoute().getReturnFormat().equalsIgnoreCase(key.getReturnFormat())
                        && !StringUtils.isEmpty(pm.getRoute().getReturnType())
                        && !pm.getRoute().isWildcardReturn()) {
                    pathMatchesByResponseType.remove(pm);
                    break;
                }
            }
        }
    }

    if (pathMatchesByResponseType.isEmpty())
        return do406(method, req, resp);
    else if (logger.isTraceEnabled())
        logger.trace(String.format("There are %d routes that match by response type.",
                pathMatchesByResponseType.size()));

    List<PathMatch> pathMatchesByContentType = new ArrayList<PathMatch>();
    String contentTypeHeader = req.getHeader("Content-Type");
    ContentTypeKey contentTypeKey = new ContentTypeKey(contentTypeHeader);
    for (PathMatch pm : pathMatchesByResponseType) {
        Route route = pm.getRoute();
        if (route.isWildcardConsumer())
            pathMatchesByContentType.add(pm);
        else if (contentTypeKey.matches(route)) {
            pathMatchesByContentType.add(pm);
            if (logger.isTraceEnabled()) {
                logger.trace(
                        String.format("Content type key: %s matches route %s", contentTypeKey, pm.getRoute()));
            } else if (logger.isTraceEnabled()) {
                logger.trace(String.format(
                        "Content type key: %s does not match route %s.  This route will be excluded from further consideration.",
                        contentTypeKey, pm.getRoute()));
            }
        }
    }
    if (pathMatchesByContentType.isEmpty())
        return do415(method, req, resp);
    else if (logger.isTraceEnabled()) {
        logger.trace(String.format("There are %d routes that match by request type.",
                pathMatchesByContentType.size()));
    }

    List<PathMatch> pathMatchesFinalCandidates = pathMatchesByContentType;

    if (logger.isTraceEnabled()) {
        logger.trace(String.format(
                "There are %d routes that match by all criteria selecting most specific route. Final candidates:",
                pathMatchesFinalCandidates.size()));
        for (PathMatch pm : pathMatchesFinalCandidates)
            logger.trace(String.format("Final candidate: ", pm.getRoute()));
    }
    PathMatch selectedMatch = pathMatchesFinalCandidates.get(0);
    for (PathMatch pm : pathMatchesFinalCandidates) {
        PathMatch prelimSelection = selectedMatch;
        if (pm != selectedMatch) {
            if (StringUtils.isEmpty(selectedMatch.getRoute().getReturnType())
                    && !StringUtils.isEmpty(pm.getRoute().getReturnType())) {
                selectedMatch = pm;
            } else if (StringUtils.isEmpty(selectedMatch.getRoute().getRequestType())
                    && !StringUtils.isEmpty(pm.getRoute().getRequestType())) {
                selectedMatch = pm;
            }
        }
        if (logger.isTraceEnabled() && prelimSelection != selectedMatch) {
            logger.trace(String.format("Route %s is more specific than %s", selectedMatch, prelimSelection));
        }
    }
    if (logger.isTraceEnabled())
        logger.trace(String.format("Route chosen for invocation %s", selectedMatch));
    try {
        return methodInvoker.invokeMethod(method, selectedMatch, req, resp).handled;
    } catch (Throwable t) {
        return do500(method, req, resp, t);
    }

}

From source file:ch.entwine.weblounge.kernel.site.SiteServlet.java

/**
 * Tries to serve the request as a static resource from the bundle.
 * /* ww w  .  j ava 2 s  .  co m*/
 * @param request
 *          the http servlet request
 * @param response
 *          the http servlet response
 * @throws ServletException
 *           if serving the request fails
 * @throws IOException
 *           if writing the response back to the client fails
 */
protected void serviceResource(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    Http11ResponseType responseType = null;
    String requestPath = request.getPathInfo();

    // There is also a special set of resources that we don't want to expose
    if (isProtected(requestPath)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    String bundlePath = UrlUtils.concat("/site", requestPath);

    // Does the resource exist?
    final URL url = bundle.getResource(bundlePath);
    if (url == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Load the resource from the bundle
    URLConnection connection = url.openConnection();
    String contentEncoding = connection.getContentEncoding();
    long contentLength = connection.getContentLength();
    long lastModified = connection.getLastModified();

    if (contentLength <= 0) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // final Resource resource = Resource.newResource(url);
    // if (!resource.exists()) {
    // response.sendError(HttpServletResponse.SC_NOT_FOUND);
    // return;
    // }

    // We don't allow directory listings
    // if (resource.isDirectory()) {
    // response.sendError(HttpServletResponse.SC_FORBIDDEN);
    // return;
    // }

    String mimeType = tika.detect(bundlePath);

    // Try to get mime type and content encoding from resource
    if (mimeType == null)
        mimeType = connection.getContentType();

    if (mimeType != null) {
        if (contentEncoding != null)
            mimeType += ";" + contentEncoding;
        response.setContentType(mimeType);
    }

    // Send the response back to the client
    InputStream is = connection.getInputStream();
    // InputStream is = resource.getInputStream();
    try {
        logger.debug("Serving {}", url);
        responseType = Http11ProtocolHandler.analyzeRequest(request, lastModified,
                Times.MS_PER_DAY + System.currentTimeMillis(), contentLength);
        if (!Http11ProtocolHandler.generateResponse(response, responseType, is)) {
            logger.warn("I/O error while generating content from {}", url);
        }
    } finally {
        IOUtils.closeQuietly(is);
    }

}

From source file:com.chaosinmotion.securechat.server.LoginServlet.java

/**
 * Handle POST commands. This uses the cookie mechanism for Java
 * servlets to track users for security reasons, and handles the
 * commands for getting a token, for verifying server status, and for
 * logging in and changing a password./*from www .j  a  v a2 s. co m*/
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ReturnResult retVal = null;

    /*
     * Step 1: determine the path element after the api/1/ URL. This
     * determines the command
     */

    String path = req.getPathInfo();
    if (path == null) {
        resp.sendError(404);
        return;
    }
    if (path.startsWith("/"))
        path = path.substring(1);

    /*
     * Now handle commands that do not require the user to be logged in
     */

    try {
        HttpSession session = req.getSession();

        if (path.equalsIgnoreCase("status")) {
            // Requests server status. This simply returns success.
            retVal = new ReturnResult();

        } else if (path.equalsIgnoreCase("token")) {
            // Generates a token used to hash the password sent from
            // the client. We use the token as a 'salt' to salt the
            // sha256-hashed password, in order to avoid a replay
            // attack on the passwords.
            //
            // We generate the random token by generating a UUID.
            // Unlike the client code (where we coded our own UUID
            // system), the server is at a known location, so there
            // is little point to hide the server hardware.

            String token = UUID.randomUUID().toString();
            session.setAttribute("token", token);
            retVal = new SimpleReturnResult("token", token);

        } else if (path.equalsIgnoreCase("login")) {
            // Handles the login request. This pulls the request
            // contents as a JSON object, and calls into our
            // utility class to handle the login logic. We use
            // the same pattern throughout.

            JSONTokener tokener = new JSONTokener(req.getInputStream());
            JSONObject requestParams = new JSONObject(tokener);
            String token = (String) session.getAttribute("token");
            Login.UserInfo uinfo = Login.processRequest(requestParams, token);
            if (uinfo == null) {
                retVal = new ReturnResult(Errors.ERROR_LOGIN, "Login error");
            } else {
                retVal = new ReturnResult();
                session.setAttribute("userinfo", uinfo);
            }

        } else if (path.equalsIgnoreCase("forgotpassword")) {
            // Handle a forgot password request. This is sent when a user
            // is attempting to add a new device but cannot remember his
            // password. This pulls the username, and calls into the
            // forgot password logic, which then sends out a message to
            // the various other devices.

            JSONTokener tokener = new JSONTokener(req.getInputStream());
            JSONObject requestParams = new JSONObject(tokener);
            ForgotPassword.processRequest(requestParams);
            retVal = new ReturnResult();

        } else if (path.equalsIgnoreCase("createaccount")) {
            // Handle an onboarding request to create a new account.
            // This processes the onboarding request with a new
            // account.

            JSONTokener tokener = new JSONTokener(req.getInputStream());
            JSONObject requestParams = new JSONObject(tokener);
            Login.UserInfo uinfo = CreateAccount.processRequest(requestParams);
            if (uinfo == null) {
                retVal = new ReturnResult(Errors.ERROR_DUPLICATEUSER, "Internal Error");
            } else {
                retVal = new ReturnResult();
                session.setAttribute("userinfo", uinfo);
            }
        } else {
            /*
             *    All the commands past this point require a user account.
             */

            Login.UserInfo userinfo = (Login.UserInfo) session.getAttribute("userinfo");
            if (userinfo == null) {
                retVal = new ReturnResult(Errors.ERROR_UNAUTHORIZED, "Not authorized");
            } else {
                /*
                 * Now handle the various command requests
                 */

                if (path.equalsIgnoreCase("updateforgotpassword")) {
                    // Handle a forgotten password. We have an interesting
                    // irony here that the user needs to be logged in 
                    // in order to reset his password. However, this
                    // is handled by the fact that each device stores the
                    // password in an encrypted format as a token on
                    // each device. 
                    //
                    // This also implies there is no way for a user to
                    // reset his password if he doesn't have a device
                    // already associated with is account. This is a
                    // deliberate design decision.
                    //
                    // If we were to associate each account with an e-mail
                    // account, then the reset pathway would be different
                    // and would involve the user arriving at a web site
                    // URL with a random token in the URI.

                    JSONTokener tokener = new JSONTokener(req.getInputStream());
                    JSONObject requestParams = new JSONObject(tokener);
                    if (UpdateForgottenPassword.processRequest(userinfo, requestParams)) {
                        retVal = new ReturnResult();
                    } else {
                        retVal = new ReturnResult(Errors.ERROR_INTERNAL, "Internal error");
                    }

                } else if (path.equalsIgnoreCase("changepassword")) {
                    // Handle a change password request. This requries both
                    // the existing password and the new password. 
                    //
                    // Yes, the user has his device, but by asking for an
                    // existing password this assures that the phone wasn't
                    // for example picked up by someone else while in an
                    // unlocked state.

                    JSONTokener tokener = new JSONTokener(req.getInputStream());
                    JSONObject requestParams = new JSONObject(tokener);
                    String token = (String) session.getAttribute("token");
                    if (ChangePassword.processRequest(userinfo, requestParams, token)) {
                        retVal = new ReturnResult();
                    } else {
                        retVal = new ReturnResult(Errors.ERROR_LOGIN, "Internal error");
                    }
                }
            }
        }

    } catch (Throwable th) {
        retVal = new ReturnResult(th);
    }

    /*
     * If we get here and we still haven't initialized return value,
     * set to a 404 error. We assume this reaches here with a null
     * value because the path doesn't exist.
     */

    if (retVal == null) {
        resp.sendError(404);

    } else {
        /*
         * We now have a return result. Formulate the response
         */

        ServletOutputStream stream = resp.getOutputStream();
        resp.setContentType("application/json");
        stream.print(retVal.toString());
    }
}

From source file:edu.harvard.i2b2.fhir.FetchInterceptor.java

@Override
public boolean incomingRequestPostProcessed(RequestDetails theRequestDetails, HttpServletRequest theRequest,
        HttpServletResponse theResponse) throws AuthenticationException {
    ourLog.info("incomingRequestPostProcessed" + theRequest.getPathInfo() + theRequest.getMethod());
    if (theRequest.getMethod() != "GET") {
        ourLog.debug("exiting fetch interceptor as its not a GET request");
        return true;
    }//from ww w.j  av a2s.co m

    try {
        //if patient id is not specified run a a population query
        FetchRequest req = new FetchRequest(theRequestDetails);
        String fsId = req.getPatientId() + "-" + req.getRequestDetails().getResourceName();
        if (req.getPatientId() == null || req.getPatientId().equals("")) {// throw new
            // FetcherException("Pa
            ourLog.info("reqDet:" + theRequestDetails.getRequestPath());
            //String path=theRequestDetails.getRequestPath();
            String path = "Patient?gender=male";
            alterResponse(theResponse, path);
            return false;
        }
    } catch (IOException e) {
        ourLog.error(e.getMessage(), e);
    }

    List<String> list = new ArrayList<String>();
    list.add(theRequestDetails.getOperation());
    list.add(theRequestDetails.getResourceName());
    if (theRequestDetails.getId() != null && theRequestDetails.getId().getIdPart() != null) {
        list.add(theRequestDetails.getId().getIdPart());
    }
    ourLog.info("incomingRequestPostProcessed" + list.toString());
    try {
        String msg = LocalUtils.readFile("samples/PatientFhirBundlePut.xml");
        ApplicationContext appContext = AppContext.getApplicationContext();
        if (appContext == null) {
            ourLog.warn("appContextIsNull");
        } else {
            //Cache cache = (Cache) appContext.getBean("cacheImpl");
            //String res = cache.put(msg);

            //injectPOJO(null,null,null, theRequestDetails);
            // new MyDao().inject();
            Fetcher fetcher = (Fetcher) appContext.getBean("fetcherImpl");
            fetcher.getData(theRequestDetails);
            //ourLog.info(res);

        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (FetcherException e) {
        e.printStackTrace();
    }

    return true;
}

From source file:com.telefonica.euro_iaas.sdc.puppetwrapper.auth.OpenStackAuthenticationFilterTest.java

@Test
public void doFilterTestAnyPath() throws IOException, ServletException {
    HttpServletRequest servletRequest = mock(HttpServletRequest.class);
    HttpServletResponse servletResponse = mock(HttpServletResponse.class);
    FilterChain filterChain = mock(FilterChain.class);
    HttpSession httpSession = mock(HttpSession.class);
    Authentication authResult = mock(Authentication.class);
    PaasManagerUser paasUser = mock(PaasManagerUser.class);

    when(servletRequest.getHeader(anyString())).thenReturn("3df25213cac246f8bccad5c70cb3582e")
            .thenReturn("00000000000000000000000000000194").thenReturn("1234");
    when(servletRequest.getPathInfo()).thenReturn("/path");
    when(servletRequest.getSession()).thenReturn(httpSession);
    when(httpSession.getId()).thenReturn("1234");
    when(authenticationManager.authenticate(any(Authentication.class))).thenReturn(authResult);

    when(authResult.getPrincipal()).thenReturn(paasUser);

    openStackAuthenticationFilter.doFilter(servletRequest, servletResponse, filterChain);
}

From source file:contestWebsite.Data.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    UserCookie userCookie = UserCookie.getCookie(req);
    boolean loggedIn = userCookie != null && userCookie.authenticate();
    if (loggedIn && userCookie.isAdmin()) {
        String choice = req.getPathInfo();
        if (choice == null) {
            resp.sendRedirect("/data/overview");
        } else if (choice.equals("/overview")) {
            resp.sendRedirect("/data/overview");
        } else if (choice.equals("/registrations")) {
            String edit = req.getParameter("edit");
            if (edit != null) {
                resp.sendRedirect("/editRegistration?key=" + req.getParameter("edit"));
            } else {
                resp.sendRedirect("/data/registrations");
            }/*from   w  w  w .  j a  v a 2  s.  c o  m*/
        } else if (choice.equals("/questions")) {
            Map<String, String[]> params = req.getParameterMap();
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
            try {
                for (String paramName : params.keySet()) {
                    if (!paramName.equals("choice") && !paramName.equals("updated")) {
                        Key key = KeyFactory.createKey("feedback", Long.parseLong(paramName));
                        String option = params.get(paramName)[0];
                        if (option.equals("r")) {
                            Entity q = datastore.get(key);
                            q.setProperty("resolved", true);
                            datastore.put(q);
                        } else if (option.equals("d")) {
                            datastore.delete(key);
                        } else {
                            resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                                    "Invalid option (must be 'r' or 'q'): " + option);
                        }
                    }
                }
                txn.commit();
            } catch (Exception e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                return;
            } finally {
                if (txn.isActive()) {
                    txn.rollback();
                }
            }

            resp.sendRedirect("/data/questions?updated=1");
        } else if (choice.equals("/scores")) {
            try {
                JSONArray testsGradedJSON = new JSONArray(req.getParameter("testsGraded"));
                ArrayList<String> testsGraded = new ArrayList<String>();
                for (int i = 0; i < testsGradedJSON.length(); i++) {
                    testsGraded.add(testsGradedJSON.get(i).toString());
                }

                DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
                Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
                try {
                    Entity contestInfo = Retrieve.contestInfo();
                    contestInfo.setProperty("testsGraded", testsGraded);
                    datastore.put(contestInfo);
                    txn.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                } finally {
                    if (txn.isActive()) {
                        txn.rollback();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString());
            }
        } else {
            resp.sendRedirect("/data/overview");
        }
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Contest Administrator privileges required for that operation");
    }
}

From source file:com.jd.survey.web.statistics.StatisticsController.java

/**
 * Shows a list of Survey Entries for a Survey Definition, Supports Paging 
 * @param surveyId// w  ww  .  j ava2  s  .c  o m
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/list", produces = "text/html", method = RequestMethod.GET)
public String listSurveyEntries(@RequestParam(value = "sid", required = true) Long surveyDefinitionId,
        @RequestParam(value = "qid", required = false) Long questionId, Model uiModel, Principal principal,
        HttpServletRequest httpServletRequest) {

    try {

        Question question;
        User user = userService.user_findByLogin(principal.getName());
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        //get the first question
        if (questionId == null) {
            question = surveySettingsService.question_findByOrder(surveyDefinitionId, (short) 1, (short) 1);
        } else {
            question = surveySettingsService.question_findById(questionId);
        }
        populateModel(uiModel, surveyDefinitionId, question, user);
        return "statistics/statistics";

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:io.apiman.manager.ui.server.servlets.ApiManagerProxyServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from ww  w.jav  a  2 s  .co m*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    StringBuilder url = new StringBuilder();

    String endpoint = getConfig().getManagementApiEndpoint();
    if (endpoint == null) {
        endpoint = getDefaultEndpoint(req);
    }

    url.append(endpoint);
    if (!url.toString().endsWith("/")) { //$NON-NLS-1$
        url.append('/');
    }
    String pathInfo = req.getPathInfo();
    if (pathInfo != null && pathInfo.startsWith("/")) { //$NON-NLS-1$
        url.append(pathInfo.substring(1));
    } else {
        url.append(pathInfo);
    }

    String authHeaderValue = null;
    ApiAuthType authType = getConfig().getManagementApiAuthType();
    switch (authType) {
    case basic: {
        String username = getConfig().getManagementApiAuthUsername();
        String password = getConfig().getManagementApiAuthPassword();
        String encoded = base64Encode(username + ":" + password); //$NON-NLS-1$
        authHeaderValue = "Basic " + encoded; //$NON-NLS-1$
        break;
    }
    case authToken: {
        ITokenGenerator tokenGenerator = getTokenGenerator();
        BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req);
        String token = creds.getToken();
        authHeaderValue = "AUTH-TOKEN " + token; //$NON-NLS-1$
        break;
    }
    case bearerToken: {
        ITokenGenerator tokenGenerator = getTokenGenerator();
        BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req);
        String token = creds.getToken();
        authHeaderValue = "Bearer " + token; //$NON-NLS-1$
        break;
    }
    case samlBearerToken: {
        ITokenGenerator tokenGenerator = getTokenGenerator();
        BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req);
        String token = creds.getToken();
        // TODO base64 decode the token, then re-encode it with "SAML-BEARER-TOKEN:"
        authHeaderValue = "Basic SAML-BEARER-TOKEN:" + token; //$NON-NLS-1$
        break;
    }
    }

    URL remoteUrl = new URL(url.toString());
    HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection();
    InputStream remoteIS = null;
    OutputStream responseOS = null;
    try {
        if (authHeaderValue != null) {
            remoteConn.setRequestProperty("Authorization", authHeaderValue); //$NON-NLS-1$
        }
        remoteConn.connect();
        Map<String, List<String>> headerFields = remoteConn.getHeaderFields();
        for (String headerName : headerFields.keySet()) {
            if (headerName == null) {
                continue;
            }
            if (EXCLUDE_HEADERS.contains(headerName)) {
                continue;
            }
            String headerValue = remoteConn.getHeaderField(headerName);
            resp.setHeader(headerName, headerValue);
            if (url.toString().contains("apiregistry")) { //$NON-NLS-1$
                String type = "json"; //$NON-NLS-1$
                if (url.toString().endsWith("xml")) { //$NON-NLS-1$
                    type = "xml"; //$NON-NLS-1$
                }
                resp.setHeader("Content-Disposition", "attachment; filename=api-registry." + type); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
        resp.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-1$ //$NON-NLS-2$
        remoteIS = remoteConn.getInputStream();
        responseOS = resp.getOutputStream();
        IOUtils.copy(remoteIS, responseOS);
        resp.flushBuffer();
    } catch (Exception e) {
        resp.sendError(500, e.getMessage());
    } finally {
        IOUtils.closeQuietly(responseOS);
        IOUtils.closeQuietly(remoteIS);
    }
}