Example usage for javax.servlet.http HttpServletRequest getHeaderNames

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

Introduction

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

Prototype

public Enumeration<String> getHeaderNames();

Source Link

Document

Returns an enumeration of all the header names this request contains.

Usage

From source file:io.personium.engine.rs.AbstractService.java

/**
 * Service./*w w  w . ja  va 2  s  . c o  m*/
 * @param cell Cell??
 * @param schema URI
 * @param svcName ???
 * @param req Request
 * @param res Response
 * @param is 
 * @return Response
 */
public final Response run(final String cell, final String schema, final String svcName,
        final HttpServletRequest req, final HttpServletResponse res, final InputStream is) {
    StringBuilder msg = new StringBuilder();
    msg.append("[" + PersoniumEngineConfig.getVersion() + "] " + ">>> Request Started ");
    msg.append(" method:");
    msg.append(req.getMethod());
    msg.append(" method:");
    msg.append(req.getRequestURL());
    msg.append(" url:");
    msg.append(cell);
    msg.append(" schema:");
    msg.append(schema);
    msg.append(" svcName:");
    msg.append(svcName);
    log.info(msg);

    // ? ????
    Enumeration<String> multiheaders = req.getHeaderNames();
    for (String headerName : Collections.list(multiheaders)) {
        Enumeration<String> headers = req.getHeaders(headerName);
        for (String header : Collections.list(headers)) {
            log.debug("RequestHeader['" + headerName + "'] = " + header);
        }
    }
    this.setServiceName(svcName);

    // ?URL??
    String targetCell = cell;
    if (cell == null) {
        targetCell = getCell();
    }
    String targetSchema = schema;
    if (schema == null) {
        targetSchema = getSchemaURI();
    }
    String targetServiceName = svcName;

    String baseUrl;
    try {
        baseUrl = parseRequestUri(req, res);
    } catch (MalformedURLException e) {
        // URL???????
        return makeErrorResponse("Server Error", PersoniumEngineException.STATUSCODE_SERVER_ERROR);
    }

    Response response = null;
    PersoniumEngineContext pecx = null;
    try {
        try {
            pecx = new PersoniumEngineContext();
        } catch (PersoniumEngineException e) {
            return errorResponse(e);
        }

        // ???
        try {
            this.sourceManager = this.getServiceCollectionManager();
            pecx.setSourceManager(this.sourceManager);
            this.serviceSubject = this.sourceManager.getServiceSubject();
        } catch (PersoniumEngineException e) {
            return errorResponse(e);
        }
        // ??
        pecx.loadGlobalObject(baseUrl, targetCell, targetSchema, targetSchema, targetServiceName);
        // ???
        String source = "";
        try {
            String sourceName = this.sourceManager.getScriptNameForServicePath(targetServiceName);
            source = this.sourceManager.getSource(sourceName);
        } catch (PersoniumEngineException e) {
            return errorResponse(e);
        } catch (Exception e) {
            log.info("User Script not found to targetCell(" + targetCell + ", targetschema(" + targetSchema
                    + "), targetServiceName(" + targetServiceName + ")");
            log.info(e.getMessage(), e);
            return errorResponse(new PersoniumEngineException("404 Not Found (User Script)",
                    PersoniumEngineException.STATUSCODE_NOTFOUND));
        }
        // JSGI
        try {
            response = pecx.runJsgi(source, req, res, is, this.serviceSubject);
        } catch (PersoniumEngineException e) {
            return errorResponse(e);
        } catch (Exception e) {
            log.warn(" unknown Exception(" + e.getMessage() + ")");
            return errorResponse(new PersoniumEngineException("404 Not Found (Service Execute Error)",
                    PersoniumEngineException.STATUSCODE_NOTFOUND));
        }
    } finally {
        IOUtils.closeQuietly(pecx);
    }
    return response;
}

From source file:org.fcrepo.server.access.FedoraAccessServlet.java

public void getDatastreamDissemination(Context context, String PID, String dsID, Date asOfDateTime,
        HttpServletResponse response, HttpServletRequest request) throws IOException, ServerException {
    ServletOutputStream out = null;/* www  .j a  v  a2  s  . c om*/
    MIMETypedStream dissemination = null;
    dissemination = m_access.getDatastreamDissemination(context, PID, dsID, asOfDateTime);
    try {
        // testing to see what's in request header that might be of interest
        if (logger.isDebugEnabled()) {
            for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                Enumeration<?> headerValues = request.getHeaders(name);
                StringBuffer sb = new StringBuffer();
                while (headerValues.hasMoreElements()) {
                    sb.append((String) headerValues.nextElement());
                }
                String value = sb.toString();
                logger.debug("FEDORASERVLET REQUEST HEADER CONTAINED: {} : {}", name, value);
            }
        }

        // Dissemination was successful;
        // Return MIMETypedStream back to browser client
        if (dissemination.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            String location = "";
            for (Property prop : dissemination.header) {
                if (prop.name.equalsIgnoreCase(HttpHeaders.LOCATION)) {
                    location = prop.value;
                    break;
                }
            }

            response.sendRedirect(location);
        } else {
            int status = dissemination.getStatusCode();
            response.setStatus(status);
            if (status == HttpStatus.SC_OK) {
                response.setContentType(dissemination.getMIMEType());
            }
            Property[] headerArray = dissemination.header;
            if (headerArray != null) {
                for (int i = 0; i < headerArray.length; i++) {
                    if (headerArray[i].name != null
                            && !headerArray[i].name.equalsIgnoreCase("transfer-encoding")
                            && !headerArray[i].name.equalsIgnoreCase("content-type")) {
                        response.addHeader(headerArray[i].name, headerArray[i].value);
                        logger.debug(
                                "THIS WAS ADDED TO FEDORASERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER {} : {}",
                                headerArray[i].name, headerArray[i].value);
                    }
                }
            }
            out = response.getOutputStream();
            int byteStream = 0;
            logger.debug("Started reading dissemination stream");
            InputStream dissemResult = dissemination.getStream();
            byte[] buffer = new byte[BUF];
            while ((byteStream = dissemResult.read(buffer)) != -1) {
                out.write(buffer, 0, byteStream);
            }
            buffer = null;
            dissemResult.close();
            dissemResult = null;
            out.flush();
            out.close();
            logger.debug("Finished reading dissemination stream");
        }
    } finally {
        dissemination.close();
    }
}

From source file:edu.indiana.d2i.htrc.oauth2.filter.OAuth2Filter.java

/**
 * Extract the access token from servlet request header and validate it via WSO2 IS. If token is invalid or
 * expired filter will throw a error and stop of handing over the request to next filter in chain. If there is no
 * token header filter will reject the request without any checks.
 * @param servletRequest in-coming request object
 * @param servletResponse servlet response object
 * @param filterChain servlet filter chain
 * @throws IOException//w w w  .j ava 2  s. c o  m
 * @throws ServletException
 */
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    String errMsg = null;
    String requestId = randomUUID();

    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse res = (HttpServletResponse) servletResponse;
    OAuth2RequestWrapper modifiedRequest = new OAuth2RequestWrapper(req);

    modifiedRequest.setRequestId(requestId);
    modifiedRequest.setRemoteAddress(req.getRemoteAddr());

    ContextExtractor contextExtractor = new ContextExtractor(req);
    Auditor auditor = AuditorFactory.getAuditor(contextExtractor.getContextMap());

    String accessToken = null;
    OAuth2TokenValidationResponseDTO responseDTO = null;

    try {
        OAuthAccessResourceRequest accessResourceRequest = new OAuthAccessResourceRequest(req,
                TokenType.BEARER);
        accessToken = accessResourceRequest.getAccessToken();

        auditor.log("OAUTH2_FILTER_REQUEST_RECEIVED", requestId, accessToken);

        Enumeration headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            auditor.log(headerName, ":", req.getHeader(headerName));
        }

        responseDTO = validateToken(accessToken);

        List<String> registered_user = new ArrayList<String>();

        registered_user.add(responseDTO.getAuthorizedUser());

        if (responseDTO.getAuthorizedUser() != null) {
            modifiedRequest.setRemoteUser(responseDTO.getAuthorizedUser());
        }

        Map<String, List<String>> contextMap = contextExtractor.getContextMap();
        if (responseDTO.getAuthorizedUser() != null) {
            contextMap.put(KEY_REMOTE_USER, registered_user);
        }

        // We need to create new auditor instance after we create the context map out of servlet request.
        auditor = AuditorFactory.getAuditor(contextMap);

        auditor.log("OAUTH2_FILTER_REQUEST_AUTHENTICATED", requestId, accessToken);
    } catch (OAuthProblemException e) {
        errMsg = "OAuth exception.";
        log.error(errMsg, e);
        auditor.log("OAUTH2_FILTER_UNAUTHENTICATED_REQUEST", requestId, accessToken);
        auditor.error(errMsg, accessToken, e.getError(), e.getMessage());
        respondWithError(res, e);
        return;
    } catch (OAuthSystemException e) {
        errMsg = "OAuth system exception.";
        log.error(errMsg, e);
        auditor.log("OAUTH2_FILTER_UNAUTHENTICATED_REQUEST", requestId, accessToken);
        auditor.error(errMsg, accessToken, e.getMessage());
        throw new ServletException(e);
    } catch (RemoteException re) {
        errMsg = "Error occurred while invoking token validation service.";
        log.error(errMsg, re);
        auditor.log("OAUTH2_FILTER_UNAUTHENTICATED_REQUEST", requestId, accessToken);
        auditor.error(errMsg, accessToken, re.getMessage());
        throw new ServletException(errMsg, re);
    }

    filterChain.doFilter(modifiedRequest, servletResponse);
}

From source file:com.nominanuda.web.http.ServletHelper.java

public HttpRequest copyRequest(HttpServletRequest servletRequest, boolean stripContextPath) throws IOException {
    final InputStream is = getServletRequestBody(servletRequest);
    String method = servletRequest.getMethod();
    String uri = getRequestLineURI(servletRequest, stripContextPath);
    String ct = servletRequest.getContentType();
    @SuppressWarnings("unused")
    String charenc = getCharacterEncoding(servletRequest);
    String cenc = getContentEncoding(servletRequest);
    long contentLength = servletRequest.getContentLength();
    HttpRequest req;/*w w w .j  av a 2  s . c o  m*/
    if (is == null) {
        req = new BasicHttpRequest(method, uri);
    } else {
        req = new BasicHttpEntityEnclosingRequest(method, uri);
        HttpEntity entity = buildEntity(servletRequest, is, contentLength, ct, cenc);
        if (entity != null) {
            ((BasicHttpEntityEnclosingRequest) req).setEntity(entity);
        }
    }
    Enumeration<?> names = servletRequest.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Enumeration<?> vals = servletRequest.getHeaders(name);
        while (vals.hasMoreElements()) {
            String value = (String) vals.nextElement();
            req.addHeader(name, value);
        }
    }
    return req;
}

From source file:com.tremolosecurity.proxy.filter.HttpFilterRequestImpl.java

public HttpFilterRequestImpl(HttpServletRequest request, AuthInfo authInfo) {
    this.request = request;

    this.headers = new HashMap<String, Attribute>();
    this.cookies = new HashMap<String, ArrayList<Cookie>>();
    this.params = new HashMap<String, Attribute>();
    this.paramNames = new ArrayList<String>();

    Enumeration enumer = request.getParameterNames();
    while (enumer.hasMoreElements()) {
        String name = (String) enumer.nextElement();
        this.paramNames.add(name);
    }//from  ww w.j a v  a 2s  . c o m

    this.authInfo = authInfo;

    boolean first = true;

    ProxyUtil.loadParams(request, this.params);

    enumer = request.getHeaderNames();
    while (enumer.hasMoreElements()) {
        String name = (String) enumer.nextElement();
        Enumeration enumerVals = request.getHeaders(name);
        Attribute attrib = new Attribute(name);
        this.headers.put(attrib.getName().toLowerCase(), attrib);
        while (enumerVals.hasMoreElements()) {
            attrib.getValues().add((String) enumerVals.nextElement());
        }
    }

    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        cookies = new Cookie[0];
    }
    for (int i = 0; i < cookies.length; i++) {
        ArrayList<Cookie> cookieList = this.cookies.get(cookies[i].getName());
        if (cookieList == null) {
            cookieList = new ArrayList<Cookie>();
            this.cookies.put(cookies[i].getName(), cookieList);
        }
        cookieList.add(cookies[i]);

    }

}

From source file:com.funambol.transport.http.server.Sync4jServlet.java

/**
 * Log the headers of the request//from w ww.  jav a 2 s . c  o  m
 * @param request HttpServletRequest
 */
private void showHeaders(HttpServletRequest request) {
    Enumeration enumHeaders = request.getHeaderNames();
    StringBuffer sb = new StringBuffer("Http header: \n");
    String headerName = null;
    String headerValue = null;
    while (enumHeaders.hasMoreElements()) {
        headerName = (String) enumHeaders.nextElement();
        headerValue = request.getHeader(headerName);
        sb.append("> ").append(headerName);
        sb.append(": ").append(headerValue).append("\n");
    }
    log.trace(sb.toString());
}

From source file:com.netflix.genie.web.controllers.JobRestControllerUnitTests.java

/**
 * Make sure directory forwarding happens when all conditions are met.
 *
 * @throws IOException      on error//  w w w  . ja v  a 2s  . c  o  m
 * @throws ServletException on error
 * @throws GenieException   on error
 */
@Test
public void canHandleForwardJobOutputRequestWithError() throws IOException, ServletException, GenieException {
    this.jobsProperties.getForwarding().setEnabled(true);
    final String jobId = UUID.randomUUID().toString();
    final String forwardedFrom = null;
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    Mockito.doNothing().when(this.genieResourceHttpRequestHandler).handleRequest(request, response);

    final String jobHostName = UUID.randomUUID().toString();
    Mockito.when(this.jobSearchService.getJobHost(jobId)).thenReturn(jobHostName);

    //Mock parts of the http request
    final String http = "http";
    Mockito.when(request.getScheme()).thenReturn(http);
    final int port = 8080;
    Mockito.when(request.getServerPort()).thenReturn(port);
    final String requestURI = "/" + jobId + "/" + UUID.randomUUID().toString();
    Mockito.when(request.getRequestURI()).thenReturn(requestURI);
    Mockito.when(request.getHeaderNames()).thenReturn(null);

    final String requestUrl = UUID.randomUUID().toString();
    Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(requestUrl));

    final int errorCode = 404;
    Mockito.when(this.restTemplate.execute(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(),
            Mockito.anyString(), Mockito.anyString()))
            .thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND));

    this.controller.getJobOutput(jobId, forwardedFrom, request, response);

    Mockito.verify(this.jobSearchService, Mockito.times(1)).getJobHost(Mockito.eq(jobId));
    Mockito.verify(this.restTemplate, Mockito.times(1)).execute(Mockito.anyString(), Mockito.any(),
            Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString());
    Mockito.verify(response, Mockito.times(1)).sendError(Mockito.eq(errorCode), Mockito.anyString());
    Mockito.verify(this.genieResourceHttpRequestHandler, Mockito.never()).handleRequest(request, response);
}

From source file:org.abstracthorizon.proximity.webapp.controllers.RepositoryController.java

/**
 * Repository list./*from   ww  w  . j a  v a 2s  . c o m*/
 * 
 * @param request the request
 * @param response the response
 * 
 * @return the model and view
 * 
 * @throws Exception the exception
 */
public ModelAndView repositoryList(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String requestURI = request.getRequestURI()
            .substring(request.getContextPath().length() + request.getServletPath().length());
    if (requestURI.length() == 0) {
        requestURI = "/";
    }
    logger.debug("Got repository request on URI " + requestURI);
    String orderBy = request.getParameter("orderBy") == null ? "name" : request.getParameter("orderBy");
    String targetRepository = request.getParameter("repositoryId");
    String targetGroup = request.getParameter("repositoryGroupId");

    Item item = null;
    ProximityRequest pRequest = new ProximityRequest();
    pRequest.setPath(requestURI);
    pRequest.setTargetedReposId(targetRepository);
    pRequest.setTargetedReposGroupId(targetGroup);
    pRequest.setGrantee(null);
    pRequest.getAttributes().put(ProximityRequest.REQUEST_REMOTE_ADDRESS, request.getRemoteAddr());

    // issue #42, collect header information
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        pRequest.getAttributes().put("http." + headerName.toLowerCase(), request.getHeader(headerName));
    }

    try {
        logger.debug("Got request for " + targetRepository + " repository on URI: " + requestURI);
        item = proximity.retrieveItem(pRequest);
        logger.debug("Got response " + item.getProperties().getPath());

        if (item.getProperties().isDirectory()) {
            List items = null;
            items = proximity.listItems(pRequest);
            PropertyComparator.sort(items, new MutableSortDefinition(orderBy, true, true));
            Map result = new HashMap();
            result.put("items", items);
            result.put("orderBy", orderBy);
            result.put("requestUri", requestURI);
            result.put("requestPathList", explodeUriToList(requestURI));
            return new ModelAndView("repository/repositoryList", result);
        } else {
            // TODO: check for If-Modified-Since?
            // response.setContentType("application/octet-stream");
            response.setContentType(
                    getWebApplicationContext().getServletContext().getMimeType(item.getProperties().getName()));
            response.setContentLength((int) item.getProperties().getSize());
            response.setDateHeader("Last-Modified", item.getProperties().getLastModified().getTime());
            InputStream is = item.getStream();
            OutputStream os = response.getOutputStream();
            IOUtils.copy(is, os);
            is.close();
            return null;
        }
    } catch (ItemNotFoundException ex) {
        logger.info("Item not found on URI " + requestURI);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    } catch (AccessDeniedException ex) {
        logger.info("Access forbidden to " + requestURI + " for " + request.getRemoteAddr(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }
}

From source file:org.fcrepo.server.access.FedoraAccessServlet.java

/**
 * <p>/*  ww  w  . j av  a  2 s. co  m*/
 * This method calls the Fedora Access Subsystem to retrieve a MIME-typed
 * stream corresponding to the dissemination request.
 * </p>
 *
 * @param context
 *        The read only context of the request.
 * @param PID
 *        The persistent identifier of the Digital Object.
 * @param sDefPID
 *        The persistent identifier of the Service Definition object.
 * @param methodName
 *        The method name.
 * @param userParms
 *        An array of user-supplied method parameters.
 * @param asOfDateTime
 *        The version datetime stamp of the digital object.
 * @param response
 *        The servlet response.
 * @param request
 *        The servlet request.
 * @throws IOException
 *         If an error occurrs with an input or output operation.
 * @throws ServerException
 *         If an error occurs in the Access Subsystem.
 */
public void getDissemination(Context context, String PID, String sDefPID, String methodName,
        Property[] userParms, Date asOfDateTime, HttpServletResponse response, HttpServletRequest request)
        throws IOException, ServerException {
    ServletOutputStream out = null;
    MIMETypedStream dissemination = null;
    dissemination = m_access.getDissemination(context, PID, sDefPID, methodName, userParms, asOfDateTime);
    out = response.getOutputStream();
    try {
        // testing to see what's in request header that might be of interest
        if (logger.isDebugEnabled()) {
            for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                Enumeration<?> headerValues = request.getHeaders(name);
                StringBuffer sb = new StringBuffer();
                while (headerValues.hasMoreElements()) {
                    sb.append((String) headerValues.nextElement());
                }
                String value = sb.toString();
                logger.debug("FEDORASERVLET REQUEST HEADER CONTAINED: {} : {}", name, value);
            }
        }

        // Dissemination was successful;
        // Return MIMETypedStream back to browser client
        if (dissemination.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            String location = "";
            for (Property prop : dissemination.header) {
                if (prop.name.equalsIgnoreCase(HttpHeaders.LOCATION)) {
                    location = prop.value;
                    break;
                }
            }

            response.sendRedirect(location);
        } else {
            response.setContentType(dissemination.getMIMEType());
            Property[] headerArray = dissemination.header;
            if (headerArray != null) {
                for (int i = 0; i < headerArray.length; i++) {
                    if (headerArray[i].name != null
                            && !headerArray[i].name.equalsIgnoreCase("transfer-encoding")
                            && !headerArray[i].name.equalsIgnoreCase("content-type")) {
                        response.addHeader(headerArray[i].name, headerArray[i].value);
                        logger.debug(
                                "THIS WAS ADDED TO FEDORASERVLET  RESPONSE HEADER FROM ORIGINATING  PROVIDER {} : {}",
                                headerArray[i].name, headerArray[i].value);
                    }
                }
            }
            int byteStream = 0;
            logger.debug("Started reading dissemination stream");
            InputStream dissemResult = dissemination.getStream();
            byte[] buffer = new byte[BUF];
            while ((byteStream = dissemResult.read(buffer)) != -1) {
                out.write(buffer, 0, byteStream);
            }
            buffer = null;
            dissemResult.close();
            dissemResult = null;
            out.flush();
            out.close();
            logger.debug("Finished reading dissemination stream");
        }
    } finally {
        dissemination.close();
    }
}