Example usage for javax.servlet.http HttpServletRequest getRemoteAddr

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

Introduction

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

Prototype

public String getRemoteAddr();

Source Link

Document

Returns the Internet Protocol (IP) address of the client or last proxy that sent the request.

Usage

From source file:org.apache.hadoop.gateway.AuditLoggingTest.java

@Test
/**//from w w w.ja v  a  2s .  co  m
 * One NoOp filter in chain. Single audit event with same with specified request URI is expected:
 * 
 * action=access request_type=uri outcome=unavailable
 */
public void testNoopFilter() throws ServletException, IOException, URISyntaxException {

    FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
    EasyMock.replay(config);

    HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
    GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
    EasyMock.expect(request.getMethod()).andReturn(METHOD).anyTimes();
    EasyMock.expect(request.getPathInfo()).andReturn(PATH).anyTimes();
    EasyMock.expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
    EasyMock.expect(request.getRemoteAddr()).andReturn(ADDRESS).anyTimes();
    EasyMock.expect(request.getRemoteHost()).andReturn(HOST).anyTimes();
    EasyMock.expect(request.getServletContext()).andReturn(context).anyTimes();
    EasyMock.expect(context.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE)).andReturn(gatewayConfig)
            .anyTimes();
    EasyMock.expect(gatewayConfig.getHeaderNameForRemoteAddress()).andReturn("Custom-Forwarded-For").anyTimes();
    EasyMock.replay(request);
    EasyMock.replay(context);
    EasyMock.replay(gatewayConfig);

    HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.replay(response);

    FilterChain chain = EasyMock.createNiceMock(FilterChain.class);
    EasyMock.replay(chain);

    Filter filter = EasyMock.createNiceMock(Filter.class);
    EasyMock.replay(filter);

    GatewayFilter gateway = new GatewayFilter();
    gateway.addFilter("path", "filter", filter, null, null);
    gateway.init(config);
    gateway.doFilter(request, response, chain);
    gateway.destroy();

    assertThat(CollectAppender.queue.size(), is(1));
    Iterator<LoggingEvent> iterator = CollectAppender.queue.iterator();
    LoggingEvent accessEvent = iterator.next();
    verifyAuditEvent(accessEvent, CONTEXT_PATH + PATH, ResourceType.URI, Action.ACCESS,
            ActionOutcome.UNAVAILABLE, null, "Request method: GET");

}

From source file:com.alfaariss.oa.authorization.method.web.ip.IPAuthorizationMethod.java

/**
 * DD The first range that matches will decide if the method succeeds or fails
 * @see com.alfaariss.oa.sso.authorization.web.IWebAuthorizationMethod#authorize(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, com.alfaariss.oa.api.session.ISession)
 *///from www . ja  v a  2 s  . c om
public UserEvent authorize(HttpServletRequest request, HttpServletResponse response, ISession session)
        throws OAException {
    UserEvent event = UserEvent.AUTHZ_METHOD_SUCCESSFUL;
    if (request == null)
        throw new IllegalArgumentException("Supplied request == null");
    if (response == null)
        throw new IllegalArgumentException("Supplied response == null");
    if (session == null)
        throw new IllegalArgumentException("Supplied session == null");

    String sUserIP = request.getRemoteAddr();

    boolean bInrange = false;
    for (IPAuthRange oRange : _lRanges) {
        bInrange = oRange.matchRange(sUserIP);
        if (bInrange)
            break;
    }

    //in range? match   result
    //--------------------------
    // false    false   true
    // false    true    false
    // true     false   false
    // true     true    true
    if (!(bInrange ^ _bMatch)) {
        event = _oAction.perform(session);
    }

    _eventLogger.info(new UserEventLogItem(session, request.getRemoteAddr(), event, this, null));

    return event;
}

From source file:com.photon.phresco.service.rest.api.ProjectService.java

@ApiOperation(value = " Create Project ")
@ApiErrors(value = { @ApiError(code = 500, reason = "Unable To Create") })
@RequestMapping(value = ServiceConstants.REST_API_PROJECT_CREATE, consumes = MediaType.APPLICATION_JSON_VALUE, produces = ServiceConstants.MEDIATYPE_ZIP, method = RequestMethod.POST)
public @ResponseBody byte[] createProject(HttpServletRequest request,
        @ApiParam(value = "Projectinfo to create", name = "projectInfo") @RequestBody ProjectInfo projectInfo)
        throws PhrescoException, IOException {
    LOGGER.debug("ProjectService.createProject : Entry");
    if (projectInfo == null) {
        LOGGER.warn("ProjectService.createProject", "status=\"Bad Request\"",
                "remoteAddress=" + request.getRemoteAddr(), "user=" + request.getParameter("userId"));
        return null;
    }/*from ww w  . j av a 2s  .  co  m*/
    FileInputStream fis = null;
    String tempFolderPath = "";
    try {
        tempFolderPath = ServerUtil.getTempFolderPath();
        ProjectServiceManager projectService = PhrescoServerFactory.getProjectService();
        buildCreateLogMessage(request, projectInfo);
        for (int i = 0; i < projectInfo.getAppInfos().size(); i++) {
            projectService.createProject(cloneProjectInfo(projectInfo, i), tempFolderPath);
        }
        addIntegrationTest(projectInfo, tempFolderPath);
        ArchiveUtil.createArchive(tempFolderPath, tempFolderPath + ZIP, ArchiveType.ZIP);
        LOGGER.debug("ProjectService.createProject() : Exit");
        fis = new FileInputStream(new File(tempFolderPath + ZIP));
        return IOUtils.toByteArray(fis);
    } catch (Exception pe) {
        LOGGER.error("ProjectService.createProject", "remoteAddress=" + request.getRemoteAddr(),
                "user=" + request.getParameter("userId"), "status=\"Failure\"",
                "message=\"" + pe.getLocalizedMessage() + "\"");
        throw new PhrescoException(pe);
    } finally {
        Utility.closeStream(fis);
    }
}

From source file:com.krawler.interceptors.LogInterceptor.java

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2,
        Exception arg3) throws Exception {
    HttpSession session = request.getSession();
    String userid = (String) session.getAttribute("userid");
    String userName = (String) session.getAttribute("username");
    Boolean freeFlag = (Boolean) session.getAttribute("isfreeuser"); // null check require
    String ipAddress = request.getHeader("x-real-ip");
    boolean logUnknown = ConfigReader.getinstance().getBoolean("logUnknownUser", false);

    if (ipAddress == null || ipAddress.length() == 0) {
        ipAddress = request.getRemoteAddr();
    }/*from w  ww  .  ja va  2  s.  c om*/

    boolean loggingAllowed = (freeFlag == null && logUnknown) || Boolean.TRUE.equals(freeFlag);

    if (loggingAllowed) {
        AuditFeature aFeature = auditLoggerService.getAuditFeature(request.getPathInfo());

        if (aFeature == null) {
            LOG.warn("No feature exists for url:" + request.getPathInfo());
        } else {
            auditLogger = new AuditLogger();
            auditLogger.setUserid(userid);
            auditLogger.setUserName(userName);
            auditLogger.setAuditFeature(aFeature);
            auditLogger.setSessionId(request.getSession().getId());
            auditLogger.setTime(System.currentTimeMillis());
            auditLogger.setIpAddress(ipAddress);
            addAuditLog(auditLogger);
        }
    }
}

From source file:com.cndatacom.user.control.UserControl.java

/**
 * /* w ww. j  a  v  a2s  .  c om*/
 * ??: </br>
 * : </br>???
 * ?</br>
 * May 12, 2014</br>
 * @param request
 * @param response
 */
@RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
public void getUserInfo(HttpServletRequest request, HttpServletResponse response) {
    logger.info("getUserInfo ");
    System.out.println("?" + request.getRemoteAddr());
    String userName = SecurityContextHolder.getContext().getAuthentication().getName();
    logger.info("??" + userName);
    try {
        String status = "0";
        String name = "";
        //SysUser sysUser = userService.loadUserByUsername(userName);
        //SysUser sysUser = (SysUser) JSONObject.toBean(JSONObject.fromObject(cacheProxy.get(userName)),SysUser.class);
        SysUser sysUser = new Gson().fromJson(cacheProxy.get(userName), SysUser.class);
        if (sysUser != null) {
            status = "1";
            name = sysUser.getName();
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", status);
        map.put("description", "");
        map.put("userName", userName);
        map.put("name", name);
        String data = JSONObject.fromObject(map).toString();
        logger.info("??: " + data);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(data);
        response.getWriter().flush();
        response.getWriter().close();
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:com.streamsets.pipeline.lib.http.HttpReceiverServlet.java

@VisibleForTesting
boolean validatePostRequest(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    boolean valid = false;
    if (validateAppId(req, res)) {
        String compression = req.getHeader(HttpConstants.X_SDC_COMPRESSION_HEADER);
        if (compression == null) {
            valid = true;/*w  ww  .jav a 2 s .  c  o m*/
        } else {
            switch (compression) {
            case HttpConstants.SNAPPY_COMPRESSION:
                valid = true;
                break;
            default:
                String requestor = req.getRemoteAddr() + ":" + req.getRemotePort();
                LOG.warn("Invalid compression '{}' in request from '{}', returning error", compression,
                        requestor);
                res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                        "Unsupported compression: " + compression);
                break;
            }
        }
    }
    return valid && getReceiver().validate(req, res);
}

From source file:com.ewcms.content.vote.web.ResultServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletOutputStream out = null;//www.j ava 2  s .  co m
    StringBuffer output = new StringBuffer();
    try {
        String id = req.getParameter("id");

        if (!id.equals("") && StringUtils.isNumeric(id)) {
            Long questionnaireId = new Long(id);

            ServletContext application = getServletContext();
            WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);
            QuestionnaireService questionnaireService = (QuestionnaireService) wac
                    .getBean("questionnaireService");

            String ipAddr = req.getRemoteAddr();

            output = questionnaireService.getQuestionnaireResultClientToHtml(questionnaireId,
                    getServletContext().getContextPath(), ipAddr);
        }
        out = resp.getOutputStream();
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        out.write(output.toString().getBytes("UTF-8"));
        out.flush();
    } finally {
        if (out != null) {
            out.close();
            out = null;
        }
    }
}

From source file:com.enonic.vertical.adminweb.AdminLogInServlet.java

private void handlerLogout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
    User user = securityService.getLoggedInAdminConsoleUser();

    if (session != null && user != null) {
        AdminService admin = lookupAdminBean();
        String remoteAddr = request.getRemoteAddr();
        createLogEntry(user, admin, user.getUserStoreKey(), remoteAddr, LogType.LOGOUT.asInteger(), null);

        try {/*from w w w .  j  a v a2 s. c o m*/
            securityService.logoutAdminUser();
            redirectClientToAdminPath("login", (MultiValueMap) null, request, response);
        } catch (VerticalAdminException vae) {
            String page = "login page";
            String message = "Failed to redirect to %0: %t";
            VerticalAdminLogger.fatalAdmin(this.getClass(), 0, message, page, vae);
        }
    } else {
        try {
            redirectClientToAdminPath("login", (MultiValueMap) null, request, response);
        } catch (VerticalAdminException vae) {
            String message = "Failed to redirect to %0: %t";
            VerticalAdminLogger.fatalAdmin(this.getClass(), 0, message, "login page", vae);
        }
    }
}

From source file:com.krawler.esp.handlers.ProfileHandler.java

public static void insertAuditLog(Session session, AuditAction action, String details,
        HttpServletRequest request, String recid) throws ServiceException {
    try {/*from   w w  w.  jav  a2 s .c o m*/
        User user = (User) session.load(User.class, AuthHandler.getUserid(request));
        String ipaddr = null;
        if (StringUtil.isNullOrEmpty(request.getHeader("x-real-ip"))) {
            ipaddr = request.getRemoteAddr();
        } else {
            ipaddr = request.getHeader("x-real-ip");
        }

        insertAuditLog(session, action, details, ipaddr, user, recid);
    } catch (Exception e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    }
}

From source file:net.sourceforge.subsonic.ajax.PlaylistService.java

private PlaylistInfo convert(HttpServletRequest request, Player player, boolean sendM3U, int offset)
        throws Exception {
    String url = request.getRequestURL().toString();

    if (sendM3U && player.isJukebox()) {
        jukeboxService.updateJukebox(player, offset);
    }//from  w w  w. j  a v a  2  s.  c  om
    boolean isCurrentPlayer = player.getIpAddress() != null
            && player.getIpAddress().equals(request.getRemoteAddr());

    boolean m3uSupported = player.isExternal() || player.isExternalWithPlaylist();
    sendM3U = player.isAutoControlEnabled() && m3uSupported && isCurrentPlayer && sendM3U;
    Locale locale = RequestContextUtils.getLocale(request);

    List<PlaylistInfo.Entry> entries = new ArrayList<PlaylistInfo.Entry>();
    Playlist playlist = player.getPlaylist();
    for (MediaFile file : playlist.getFiles()) {
        String albumUrl = url.replaceFirst("/dwr/.*",
                "/main.view?pathUtf8Hex=" + StringUtil.utf8HexEncode(file.getParentPath()));
        String streamUrl = url.replaceFirst("/dwr/.*", "/stream?player=" + player.getId() + "&pathUtf8Hex="
                + StringUtil.utf8HexEncode(file.getPath()));

        // Rewrite URLs in case we're behind a proxy.
        if (settingsService.isRewriteUrlEnabled()) {
            String referer = request.getHeader("referer");
            albumUrl = StringUtil.rewriteUrl(albumUrl, referer);
            streamUrl = StringUtil.rewriteUrl(streamUrl, referer);
        }

        String format = formatFormat(player, file);
        entries.add(new PlaylistInfo.Entry(file.getTrackNumber(), file.getTitle(), file.getArtist(),
                file.getAlbumName(), file.getGenre(), file.getYear(), formatBitRate(file),
                file.getDurationSeconds(), file.getDurationString(), format, formatContentType(format),
                formatFileSize(file.getFileSize(), locale), albumUrl, streamUrl));
    }
    boolean isStopEnabled = playlist.getStatus() == Playlist.Status.PLAYING && !player.isExternalWithPlaylist();
    float gain = jukeboxService.getGain();
    return new PlaylistInfo(entries, playlist.getIndex(), isStopEnabled, playlist.isRepeatEnabled(), sendM3U,
            gain);
}