Example usage for javax.servlet.http HttpServletRequest getRemoteUser

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

Introduction

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

Prototype

public String getRemoteUser();

Source Link

Document

Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.

Usage

From source file:org.j2free.util.ServletUtils.java

/**
 * //from  www .ja  va  2s. c o m
 * @param req
 * @return
 */
public static String describeRequest(HttpServletRequest req) {

    if (req == null) {
        return EMPTY;
    }

    HttpSession session = null;
    try {
        session = req.getSession();
    } catch (Exception e) {
    }

    StringBuilder body = new StringBuilder();
    body.append("Browser: " + req.getHeader("User-Agent"));

    body.append("\n\nRequest Info");
    body.append("\nRequest URI: " + req.getRequestURI());
    body.append("\nRequest URL: " + req.getRequestURL().toString());
    body.append("\nPath Info: " + req.getPathInfo());
    body.append("\nQuery String: " + req.getQueryString());

    if (session != null) {
        body.append("\n\nSession Info");
        body.append("\nSession ID: " + session.getId());
        body.append("\nSession Created: " + new Date(session.getCreationTime()).toString());
        body.append("\nSession Last Accessed: " + new Date(session.getLastAccessedTime()).toString());
    }

    body.append("\n\nUser Info");
    body.append("\nRemote User: " + req.getRemoteUser());
    body.append("\nUser Principal: " + req.getUserPrincipal());

    body.append("\n\nServer Info");
    String hostname = "", serverInstance = "", ip = "";
    try {
        hostname = java.net.InetAddress.getLocalHost().getHostName();
        serverInstance = System.getProperty("com.sun.aas.instanceName");
        ip = java.net.InetAddress.getLocalHost().getHostAddress();
        body.append("\nInstance: " + serverInstance + " : " + ip + " : " + hostname);
    } catch (Exception e) {
    }

    return body.toString();
}

From source file:com.almende.eve.transport.http.DebugServlet.java

@Override
public void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws IOException, ServletException {

    if (!handleSession(req, resp)) {
        if (!resp.isCommitted()) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }/* ww  w.  j a  v  a2s  .co  m*/
        resp.flushBuffer();
        return;
    }

    // retrieve the url and the request body
    final String body = StringUtil.streamToString(req.getInputStream());
    final String url = req.getRequestURI();
    final String id = getId(url);
    if (id == null || id.equals("") || id.equals(myUrl.toASCIIString())) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Couldn't parse URL, missing 'id'");
        resp.flushBuffer();
        return;
    }

    String sender = req.getHeader("X-Eve-SenderUrl");
    if (sender == null || sender.equals("")) {
        sender = "web://" + req.getRemoteUser() + "@" + req.getRemoteAddr();
    }
    URI senderUrl = null;
    try {
        senderUrl = new URI(sender);
    } catch (final URISyntaxException e) {
        LOG.log(Level.WARNING, "Couldn't parse senderUrl:" + sender, e);
    }
    final HttpTransport transport = HttpService.get(myUrl, id);
    if (transport != null) {
        try {
            final String response = transport.receive(body, senderUrl);
            // TODO: It doesn't need to be json, should we handle mime-types
            // better?
            resp.addHeader("Content-Type", "application/json");
            resp.getWriter().println(response);
            resp.getWriter().close();
        } catch (final IOException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Receiver raised exception:" + e.getMessage());
        }
    } else {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Couldn't load transport");
    }
    resp.flushBuffer();
}

From source file:edu.mit.isda.permitws.permitclient.java

/**
 * get Remote user/*from   w  w w  .  j av  a2  s .  c o  m*/
 * @param request
 * @return
 */
protected String getRemoteUser(HttpServletRequest request) {
    String user = request.getRemoteUser();
    if (null == user) {
        user = (String) request.getAttribute("REMOTE_USER");
    }
    System.out.println("***** REMOTE_USER - " + user);
    return user;

}

From source file:org.eclipse.orion.internal.server.servlets.workspace.WorkspaceResourceHandler.java

private boolean handleRemoveProject(HttpServletRequest request, HttpServletResponse response,
        WorkspaceInfo workspace) throws IOException, JSONException, ServletException {
    IPath path = new Path(request.getPathInfo());
    //format is /workspaceId/project/<projectId>
    if (path.segmentCount() != 3)
        return false;
    String workspaceId = path.segment(0);
    String projectName = path.segment(2);
    try {//from   w w  w.  j av  a2  s.  c  o  m
        ProjectInfo project = getMetaStore().readProject(workspaceId, projectName);
        if (project == null) {
            //nothing to do if project does not exist
            return true;
        }

        removeProject(request.getRemoteUser(), workspace, project);
    } catch (CoreException e) {
        ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Error removing project", e);
        LogHelper.log(error);
        return statusHandler.handleRequest(request, response, error);
    }

    return true;
}

From source file:edu.vt.middleware.servlet.filter.RequestDumperFilter.java

/** {@inheritDoc} */
@SuppressWarnings(value = "unchecked")
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (this.config == null) {
        return;/*from  ww  w . ja v  a 2s. co m*/
    }

    // Just pass through to next filter if we're not at TRACE level
    if (!logger.isTraceEnabled()) {
        chain.doFilter(request, response);
        return;
    }

    // Create a variable to hold the (possibly different) request
    // passed to downstream filters
    ServletRequest downstreamRequest = request;

    // Render the generic servlet request properties
    final StringWriter sw = new StringWriter();
    final PrintWriter writer = new PrintWriter(sw);
    writer.println("Dumping request...");
    writer.println("-----------------------------------------------------");
    writer.println("REQUEST received " + Calendar.getInstance().getTime());
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");

    final Enumeration<Locale> locales = request.getLocales();
    for (int i = 0; locales.hasMoreElements(); i++) {
        if (i > 0) {
            writer.print(", ");
        }
        writer.print(locales.nextElement());
    }
    writer.println();

    final Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        final String name = paramNames.nextElement();
        writer.print("         parameter=" + name + "=");

        final String[] values = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                writer.print(", ");
            }
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        final HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());

        Cookie[] cookies = hrequest.getCookies();
        if (cookies == null) {
            cookies = new Cookie[0];
        }
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }

        final Enumeration<String> headerNames = hrequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String name = headerNames.nextElement();
            final String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());

        // Create a wrapped request that contains the request body
        // and that we will pass to downstream filters
        final ByteArrayRequestWrapper wrappedRequest = new ByteArrayRequestWrapper(hrequest);
        downstreamRequest = wrappedRequest;
        writer.println(wrappedRequest.getRequestBodyAsString());
    }
    writer.println("-----------------------------------------------------");

    // Log the resulting string
    writer.flush();
    logger.trace(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(downstreamRequest, response);
}

From source file:alpha.portal.webapp.controller.CardFormController.java

/**
 * Sets the a card deleted status./* w w  w .  j av a  2s  .  co m*/
 * 
 * @param jspCard
 *            the jsp card
 * @param request
 *            the request
 * @return the string
 * @throws Exception
 *             the exception
 */
private String setACardDeletedStatus(final AlphaCard jspCard, final HttpServletRequest request)
        throws Exception {

    final AlphaCard alphaCard = this.alphaCardManager.get(jspCard.getAlphaCardIdentifier());

    final Adornment contributor = alphaCard.getAlphaCardDescriptor()
            .getAdornment(AdornmentType.Contributor.getName());
    if ((contributor.getValue() == null) || contributor.getValue().isEmpty()) {
        this.saveError(request, this.getText("adornment.noAccess", request.getLocale()));
        final String cardId = alphaCard.getAlphaCardIdentifier().getCardId();
        final String caseId = alphaCard.getAlphaCardIdentifier().getCaseId();
        return "redirect:/caseform?activeCardId=" + cardId + "&caseId=" + caseId;
    } else {
        final Long contributorID = Long.parseLong(contributor.getValue());
        final User currentUser = this.getUserManager().getUserByUsername(request.getRemoteUser());
        if (contributorID != currentUser.getId()) {
            this.saveError(request, this.getText("adornment.noAccess", request.getLocale()));
            final String cardId = alphaCard.getAlphaCardIdentifier().getCardId();
            final String caseId = alphaCard.getAlphaCardIdentifier().getCaseId();
            return "redirect:/caseform?activeCardId=" + cardId + "&caseId=" + caseId;
        }
    }

    Adornment deletedAdornment = null;
    if (alphaCard.getAlphaCardDescriptor().getAdornment(AdornmentType.Deleted.getName()) == null) {
        deletedAdornment = new Adornment(AdornmentType.Deleted.getName());
        deletedAdornment.setValue(AdornmentTypeDeleted.FALSE.value());
        alphaCard.getAlphaCardDescriptor().setAdornment(deletedAdornment);
    }

    deletedAdornment = alphaCard.getAlphaCardDescriptor().getAdornment(AdornmentType.Deleted.getName());

    if (request.getParameter("setDeleted") != null) {
        deletedAdornment.setValue(AdornmentTypeDeleted.TRUE.value());
        this.alphaCardManager.save(alphaCard);
        this.saveMessage(request, this.getText("card.deleted", request.getLocale()));
    } else if (request.getParameter("setNotDeleted") != null) {
        deletedAdornment.setValue(AdornmentTypeDeleted.FALSE.value());
        this.alphaCardManager.save(alphaCard);
        this.saveMessage(request, this.getText("card.updated", request.getLocale()));
    }

    final AlphaCardIdentifier identifier = alphaCard.getAlphaCardIdentifier();
    return "redirect:/caseform?caseId=" + identifier.getCaseId() + "&activeCardId=" + identifier.getCardId();
}

From source file:org.opennms.web.controller.event.EventController.java

/**
 * Acknowledge the events specified in the POST and then redirect the client
 * to an appropriate URL for display./*from  ww  w.j  ava  2  s . c  o  m*/
 */
public ModelAndView acknowledge(HttpServletRequest request, HttpServletResponse response) throws Exception {

    // required parameter
    String[] eventIdStrings = request.getParameterValues("event");
    String action = request.getParameter("actionCode");

    if (eventIdStrings == null) {
        throw new MissingParameterException("event", new String[] { "event", "actionCode" });
    }

    if (action == null) {
        throw new MissingParameterException("actionCode", new String[] { "event", "actionCode" });
    }

    List<Filter> filters = new ArrayList<Filter>();
    filters.add(new EventIdListFilter(WebSecurityUtils.safeParseInt(eventIdStrings)));
    EventCriteria criteria = new EventCriteria(filters.toArray(new Filter[0]));

    LOG.debug("criteria = {}, action = {}", criteria, action);
    if (action.equals(AcknowledgeType.ACKNOWLEDGED.getShortName())) {
        m_webEventRepository.acknowledgeMatchingEvents(request.getRemoteUser(), new Date(), criteria);
    } else if (action.equals(AcknowledgeType.UNACKNOWLEDGED.getShortName())) {
        m_webEventRepository.unacknowledgeMatchingEvents(criteria);
    } else {
        throw new ServletException("Unknown acknowledge action: " + action);
    }

    return getRedirectView(request);
}

From source file:org.atomserver.AtomServer.java

private void log500Error(Throwable e, Abdera abdera, RequestContext request) {
    if (errlog != null) {
        Log http500log = errlog.getLog();
        if (http500log.isInfoEnabled()) {
            try {
                http500log.info(/* w  w  w  . j av a2s .  c  o  m*/
                        "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
                http500log.info("==> 500 ERROR occurred for {" + request.getUri() + "} Type:: "
                        + e.getClass().getName() + " Reason:: " + e.getMessage());
                http500log.error("500 Error:: ", e);
                http500log.info("METHOD:: " + request.getMethod());
                if (request.getPrincipal() != null) {
                    http500log.info("PRINCIPAL:: " + request.getPrincipal().getName());
                }
                http500log.info("HEADERS:: ");
                String[] headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    for (int ii = 0; ii < headerNames.length; ii++) {
                        http500log
                                .info("Header(" + headerNames[ii] + ")= " + request.getHeader(headerNames[ii]));
                    }
                }
                http500log.info("PARAMETERS:: ");
                String[] paramNames = request.getParameterNames();
                if (paramNames != null) {
                    for (int ii = 0; ii < paramNames.length; ii++) {
                        http500log.info(
                                "Parameter(" + paramNames[ii] + ")= " + request.getParameter(paramNames[ii]));
                    }
                }
                if (request instanceof HttpServletRequestContext) {
                    HttpServletRequestContext httpRequest = (HttpServletRequestContext) request;
                    javax.servlet.http.HttpServletRequest servletRequest = httpRequest.getRequest();
                    if (servletRequest != null) {
                        http500log.info("QUERY STRING::" + servletRequest.getQueryString());
                        http500log.info("AUTH TYPE:: " + servletRequest.getAuthType());
                        http500log.info("REMOTE USER:: " + servletRequest.getRemoteUser());
                        http500log.info("REMOTE ADDR:: " + servletRequest.getRemoteAddr());
                        http500log.info("REMOTE HOST:: " + servletRequest.getRemoteHost());
                    }
                }
                http500log.info("BODY:: ");
                if (request.getDocument() != null) {
                    java.io.StringWriter stringWriter = new java.io.StringWriter();
                    request.getDocument().writeTo(abdera.getWriterFactory().getWriter("PrettyXML"),
                            stringWriter);

                    //http500log.info( "\n" + stringWriter.toString() );
                    String requestString = stringWriter.toString();
                    if (requestString != null && requestString.length() > MAX_REQ_BODY_DUMP) {
                        requestString = requestString.substring(0, (MAX_REQ_BODY_DUMP - 1));
                    }

                    http500log.info("\n" + requestString);
                }
            } catch (Exception ee) {
            }
        }
    }
}

From source file:oculus.memex.rest.PreclusterDetailsResource.java

@POST
@Path("fetchAds")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public ClustersDetailsResult fetchAds(String clustersIds, @Context HttpServletRequest request) {
    TimeLog log = new TimeLog();
    log.pushTime("Cluster tip search");
    HashMap<Integer, ClusterDetailsResult> results = new HashMap<Integer, ClusterDetailsResult>();
    try {//from  w  ww .  j  a va 2s . com
        JSONObject jo = new JSONObject(clustersIds);
        JSONArray clusterids = jo.getJSONArray("ids");
        HashMap<Integer, HashSet<Integer>> clusterAds = new HashMap<Integer, HashSet<Integer>>();

        log.pushTime("Fetch Ad IDs");
        Cluster.getAdsInClusters(clusterids, clusterAds, 2000);
        log.popTime();

        log.pushTime("Fetch Ad Contents");
        for (Integer clusterid : clusterAds.keySet()) {
            log.pushTime("Fetch contents for cluster: " + clusterid);
            HashSet<Integer> members = clusterAds.get(clusterid);
            ArrayList<DataRow> result = new ArrayList<DataRow>();
            PreclusterDetailsResource.getDetails(members, result, request.getRemoteUser());
            log.popTime();

            log.pushTime("Prepare results for cluster: " + clusterid);
            ArrayList<HashMap<String, String>> details = DataUtil.sanitizeHtml(result);
            ArrayList<StringMap> serializableDetails = new ArrayList<StringMap>();
            for (HashMap<String, String> map : details) {
                serializableDetails.add(new StringMap(map));
            }
            results.put(clusterid, new ClusterDetailsResult(serializableDetails));
            log.popTime();
        }
        log.popTime();
        log.popTime();
        return new ClustersDetailsResult(results);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.openkm.servlet.admin.PropertyGroupsServlet.java

/**
 * List property groups/*from   w  w w .  j a  va  2s . co  m*/
 */
private void list(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ParseException, RepositoryException, DatabaseException {
    log.debug("list({}, {})", new Object[] { request, response });
    ServletContext sc = getServletContext();
    FormUtils.resetPropertyGroupsForms();
    OKMPropertyGroup okmPropGroups = OKMPropertyGroup.getInstance();
    List<PropertyGroup> groups = okmPropGroups.getAllGroups(null);
    Map<PropertyGroup, List<Map<String, String>>> pGroups = new LinkedHashMap<PropertyGroup, List<Map<String, String>>>();

    for (PropertyGroup group : groups) {
        List<FormElement> mData = okmPropGroups.getPropertyGroupForm(null, group.getName());
        List<Map<String, String>> fMaps = new ArrayList<Map<String, String>>();

        for (FormElement fe : mData) {
            fMaps.add(FormUtils.toString(fe));
        }

        pGroups.put(group, fMaps);
    }

    sc.setAttribute("pGroups", pGroups);
    sc.getRequestDispatcher("/admin/property_groups_list.jsp").forward(request, response);

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_PROPERTY_GROUP_LIST", null, null, null);
    log.debug("list: void");
}