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.lareferencia.provider.controller.ProviderController.java

public ModelAndView defaultHandler(final HttpServletRequest request, final HttpServletResponse response,
        final Arguments arguments) {
    final Map<String, Object> model = new HashMap<String, Object>();

    // Debugging.
    response.setContentType("text/xml; charset=UTF-8");

    // registro de la ip para estadsticas
    statsManager.countIPAccess(request.getRemoteAddr());

    // The OAI protocol includes the original HTTP request.
    final String requestURL = request.getRequestURL().toString();
    model.put("RequestURL", requestURL);

    // responseDate
    String dateString = dateFormater.format(new DateTime().toDate());
    System.out.println(dateString);
    model.put("ResponseDate", dateString);

    // adminEmail
    model.put("AdminEmail", adminEmail);

    try {//ww  w  . ja  v a2 s  .  com
        if (this.getProvider() == null)
            throw new ServerException(
                    "There was a configuration problem. ProviderController expects a non-null 'provider'.");

        // The 'verb' parameter must be set.
        if (arguments.getVerb() == null)
            throw new BadArgumentException("A 'verb' argument is required.");

        // Restrict arguments just to the ones defined by the spec.
        final String[] allowedArguments = { "from", "identifier", "metadataPrefix", "resumptionToken", "set",
                "until", "verb" };

        final Set<String> allowedArgumentSet = new HashSet<String>();
        for (String argument : allowedArguments)
            allowedArgumentSet.add(argument);

        Set<String> requestParameters = (Set<String>) request.getParameterMap().keySet();
        for (String parameter : requestParameters) {
            if (!allowedArgumentSet.contains(parameter))
                throw new BadArgumentException("Unknown argument '" + parameter + "'.");
        }

        IProvider provider = this.getProvider();
        final String verb = arguments.getVerb();

        if (verb.equals("GetRecord")) {
            // Check required arguments.
            if (arguments.getIdentifier() == null)
                throw new BadArgumentException("An 'identifier' argument is required for this verb.");
            if (arguments.getMetadataPrefix() == null)
                throw new BadArgumentException("A 'metadataPrefix' argument is required for this verb.");

            // Check unsupported arguments.
            if (arguments.getFrom() != null || arguments.getUntil() != null
                    || arguments.getResumptionToken() != null || arguments.getSet() != null)
                throw new BadArgumentException(
                        "Only the 'identifier' and 'metadataPrefix' arguments are valid for this verb.");

            // Retrieve the requested Record.
            final MetadataFormat format = this.metadataFormatMap.get(arguments.getMetadataPrefix());
            if (format == null)
                throw new CannotDisseminateFormatException();

            model.put("GetRecord", provider.getRecord(arguments.getIdentifier(), format));
        } else if (verb.equals("ListRecords") || verb.equals("ListIdentifiers")) {

            //log.info("ListRecords/ListIdentifiers Request / RT: " + arguments.getResumptionToken());
            System.out.println("ListRecords/ListIdentifiers Request / RT: " + arguments.getResumptionToken());

            // Check unsupported arguments.
            if (arguments.getIdentifier() != null)
                throw new BadArgumentException("The 'identifier' argument is not valid for this verb.");

            StateHolder state = null;

            if (StringUtils.isNotEmpty(arguments.getResumptionToken())) {
                if (arguments.getFrom() != null || arguments.getUntil() != null
                        || arguments.getIdentifier() != null || arguments.getSet() != null
                        || arguments.getMetadataPrefix() != null)
                    throw new BadArgumentException(
                            "A 'resumptionToken' argument cannot be used in conjunction with any others.");

                state = new StateHolder(arguments.getResumptionToken()); // el estado se obtiene del RT
            } else {
                // Check required arguments.
                if (StringUtils.isEmpty(arguments.getMetadataPrefix()))
                    throw new BadArgumentException("A 'metadataPrefix' argument is required for this verb.");

                state = new StateHolder(); // si no hay rt  es un estado inicial
            }

            // list records actualiza el state, que queda conteniendo la informacin para generar RT
            List<Record> records = provider.listRecords(arguments.getSet(), state,
                    !verb.equals("ListIdentifiers"));

            model.put("ResumptionToken", state.getResumptionToken());
            model.put("ListRecords", records);
        } else if (verb.equals("ListSets")) {
            // Check unsupported arguments.
            if (arguments.getFrom() != null || arguments.getUntil() != null || arguments.getSet() != null
                    || arguments.getIdentifier() != null || arguments.getMetadataPrefix() != null)
                throw new BadArgumentException(
                        "No arguments are allowed for this verb other than an optional 'resumptionToken'.");

            // TODO: This model dispenses with the ability to use resumption tokens
            // to iterate over sets, which may not be a bad thing.
            model.put("ListSets", provider.listSets());
        } else if (verb.equals("Identify")) {
            if (requestParameters.size() > 1)
                throw new BadArgumentException("No additional arguments are allowed for this verb.");

            model.put("Origins", provider.listOrigins());
        } else if (verb.equals("ListMetadataFormats")) {
            // Check required arguments.
            if (arguments.getFrom() != null || arguments.getUntil() != null
                    || arguments.getResumptionToken() != null || arguments.getSet() != null
                    || arguments.getMetadataPrefix() != null)
                throw new BadArgumentException(
                        "Only the 'identifier' argument (or no argument) is valid for this verb.");

            // Get the list of allowed metadata formats.
            List<MetadataFormat> formats = null;
            /*
            if(arguments.getIdentifier() != null)
            {
               formats = new ArrayList<MetadataFormat>();
                    
               // Collect matching prefixes and populate a List with matching
               // MetadataFormat instances.
               final String[] prefixes = provider.getMetadataPrefixes(arguments.getIdentifier());
               for(String prefix : prefixes)
               {
                  final MetadataFormat format = metadataFormatMap.get(prefix);
                  if(format != null)
             formats.add(format);
               }
            }
            else*/
            formats = this.getMetadataFormats();

            if (formats != null && formats.size() == 0)
                throw new NoMetadataFormatsException();

            model.put("ListMetadataFormats", formats);
        } else {
            throw new BadArgumentException(
                    "The 'verb' argument must be one of (GetRecord|Identify|ListIdentifiers|ListMetadataFormats|ListRecords|ListSets).");
        }

        return new ModelAndView("oai/" + verb, model);
    } catch (ProtocolException e) {

        //log.warn("Protocol error", e);

        model.put("ErrorCode", e.getCode());
        model.put("ErrorMessage", e.getMessage());
        return new ModelAndView("oai/Error", model);

    } catch (ServerException e) {
        try {
            //log.warn("OAI Service Error: " + e.getMessage(), e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "OAI Service Error: " + e.getMessage());
        } catch (IOException ioe) {
            //log.warn("Could not send error to client", ioe);
        }
    } catch (Throwable th) {
        try {
            //log.warn("Unexpected Error", th);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unexpected error");
        } catch (IOException ioe) {
            //log.warn("Could not send error to client", ioe);
        }
    }

    return new ModelAndView("oai/Error", model);
}

From source file:com.ebay.pulsar.analytics.resources.PulsarQueryResource.java

@POST
@Path("today")
@Consumes(MediaType.APPLICATION_JSON)/* ww w  .  ja va 2  s.co  m*/
@Produces(MediaType.APPLICATION_JSON)
public Response today(@Context HttpServletRequest request, CoreRequest req) {
    if (logger.isDebugEnabled()) {
        logger.debug("Today API called from IP: " + request.getRemoteAddr());
    }
    req.setNamespace(RequestNameSpace.today);
    req.setGranularity("fifteen_minute");

    Calendar c = Calendar.getInstance();
    long msEnd = c.getTimeInMillis();
    c.setTimeZone(TimeZone.getTimeZone("MST"));

    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);

    long msStart = c.getTimeInMillis();
    long msDiff = msEnd - msStart;

    if (msDiff < 0) {
        msStart = msStart - 86400000;
        msDiff = msDiff + 86400000;
    }

    if (msDiff < MS_15MINS) {
        // If the now time is 00:00:00 - 00:14:59 (Round to 0), let's do no
        // rounding.
        if (msDiff < 1000) {
            // If we really have the exact 00:00:00 time, let's just add 1
            // sec for end time.
            msEnd = msStart + 1000;
        } else {
            msEnd = msStart + msDiff;
        }
    } else {
        long msOffset = msDiff / MS_15MINS * MS_15MINS; // normalize to 0,
        // 15, 30, 45min of
        // each hour
        msEnd = msStart + msOffset;
    }
    Date end = new Date(msEnd);

    Date start = new Date(msStart);

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("MST"));

    req.setStartTime(dateFormat.format(start));
    req.setEndTime(dateFormat.format(end));

    boolean trace = request.getParameter("debug") == null ? false : true;
    return processRequest(req, trace);
}

From source file:com.xpn.xwiki.user.impl.xwiki.MyPersistentLoginManager.java

/**
 * Returns the original client IP. Needed because request.getRemoteAddr returns the address of the last requesting
 * host, which can be either the real client, or a proxy. The original method prevents logging in when using a
 * cluster of reverse proxies in front of XWiki.
 * /*w ww  . ja va  2  s  . co m*/
 * @param request The servlet request.
 * @return The IP of the actual client.
 */
protected String getClientIP(HttpServletRequest request) {
    String remoteIP = request.getHeader("X-Forwarded-For");
    if (remoteIP == null || "".equals(remoteIP)) {
        remoteIP = request.getRemoteAddr();
    } else if (remoteIP.indexOf(',') != -1) {
        remoteIP = remoteIP.substring(0, remoteIP.indexOf(','));
    }
    return remoteIP;
}

From source file:ee.ria.xroad.proxy.clientproxy.AbstractClientProxyHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    if (baseRequest.isHandled()) {
        // If some handler already processed the request, we do nothing.
        return;// w ww  .  ja v  a  2  s. c  o  m
    }

    boolean handled = false;
    OpMonitoringData opMonitoringData = storeOpMonitoringData
            ? new OpMonitoringData(CLIENT, getEpochMillisecond())
            : null;

    long start = PerformanceLogger.log(log, "Received request from " + request.getRemoteAddr());
    log.info("Received request from {}", request.getRemoteAddr());

    MessageProcessorBase processor = null;

    try {
        processor = createRequestProcessor(target, request, response, opMonitoringData);

        if (processor != null) {
            handled = true;
            start = logPerformanceBegin(request);
            processor.process();
            success(processor, start, opMonitoringData);

            if (log.isTraceEnabled()) {
                log.info("Request successfully handled ({} ms)", System.currentTimeMillis() - start);
            } else {
                log.info("Request successfully handled");
            }
        }
    } catch (CodedException.Fault | ClientException e) {
        handled = true;

        String errorMessage = e instanceof ClientException
                ? "Request processing error (" + e.getFaultDetail() + ")"
                : "Request processing error";

        log.error(errorMessage, e);

        updateOpMonitoringSoapFault(opMonitoringData, e);

        // Exceptions caused by incoming message and exceptions
        // derived from faults sent by serverproxy already contain
        // full error code. Thus, we must not attach additional
        // error code prefixes to them.

        failure(processor, response, e);
    } catch (CodedExceptionWithHttpStatus e) {
        handled = true;

        // No need to log faultDetail hence not sent to client.
        log.error("Request processing error", e);

        // Respond with HTTP status code and plain text error message
        // instead of SOAP fault message. No need to update operational
        // monitoring fields here either.

        failure(response, e);
    } catch (Throwable e) { // We want to catch serious errors as well
        handled = true;

        // All the other exceptions get prefix Server.ClientProxy...
        CodedException cex = translateWithPrefix(SERVER_CLIENTPROXY_X, e);

        updateOpMonitoringSoapFault(opMonitoringData, cex);

        log.error("Request processing error ({})", cex.getFaultDetail(), e);

        failure(processor, response, cex);
    } finally {
        baseRequest.setHandled(handled);

        if (handled) {
            if (storeOpMonitoringData) {
                opMonitoringData.setResponseOutTs(getEpochMillisecond());
                OpMonitoring.store(opMonitoringData);
            }

            logPerformanceEnd(start);
        }
    }
}

From source file:net.sourceforge.subsonic.backend.controller.MultiController.java

public ModelAndView sendMail(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String from = request.getParameter("from");
    String to = request.getParameter("to");
    String subject = request.getParameter("subject");
    String text = request.getParameter("text");

    EmailSession session = new EmailSession();
    session.sendMessage(from, Arrays.asList(to), null, null, null, subject, text);

    LOG.info("Sent email on behalf of " + request.getRemoteAddr() + " to " + to + " with subject '" + subject
            + "'");

    return null;//from   www .j  a  v  a 2s .  com
}

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

@ApiOperation(value = " Create Integration Archetype ")
@ApiErrors(value = { @ApiError(code = 500, reason = "Unable To Create") })
@RequestMapping(value = "/integration", consumes = MediaType.APPLICATION_JSON_VALUE, produces = ServiceConstants.MEDIATYPE_ZIP, method = RequestMethod.POST)
public @ResponseBody byte[] createIntegrationArchetype(HttpServletRequest request,
        @ApiParam(value = "Projectinfo to create", name = "projectInfo") @RequestBody ProjectInfo projectInfo)
        throws PhrescoException, IOException {
    LOGGER.debug("ProjectService.createIntegrationArchetype() : Entry");
    if (projectInfo == null) {
        LOGGER.warn("ProjectService.createIntegrationArchetype()", "status=\"Bad Request\"",
                "remoteAddress=" + request.getRemoteAddr(), "user=" + request.getParameter("userId"));
    }//from   w  ww .  j a va  2  s .c om
    String tempFolderPath = "";
    FileInputStream fis = null;
    try {
        tempFolderPath = ServerUtil.getTempFolderPath();
        addIntegrationTest(projectInfo, tempFolderPath);
        ArchiveUtil.createArchive(tempFolderPath, tempFolderPath + ZIP, ArchiveType.ZIP);
        LOGGER.debug("ProjectService.createIntegrationArchetype() : Exit");
        fis = new FileInputStream(new File(tempFolderPath + ZIP));
        return IOUtils.toByteArray(fis);
    } catch (Exception pe) {
        LOGGER.error("ProjectService.createIntegrationArchetype()", "remoteAddress=" + request.getRemoteAddr(),
                "user=" + request.getParameter("userId"), "status=\"Failure\"",
                "message=\"" + pe.getLocalizedMessage() + "\"");
        throw new PhrescoException(pe);
    } finally {
        Utility.closeStream(fis);
    }
}

From source file:energy.usef.core.endpoint.ReceiverEndpoint.java

/**
 * Sends a client message to a queue./*  w  ww .ja  v  a2s.  c o m*/
 *
 * @param messageText message
 * @param request {@link HttpServletRequest}
 * @return status
 */
@POST
@Path("/receiveMessage")
@Consumes(TEXT_XML)
public Response receiveMessage(String messageText, @Context HttpServletRequest request) {
    try {
        // verify that the signed message has not been received yet.
        incomingMessageVerificationService.checkSignedMessageHash(DigestUtils.sha256(messageText));

        // transform the text/xml to a SignedMessage message
        SignedMessage signedMessage = XMLUtil.xmlToMessage(messageText, SignedMessage.class,
                config.getBooleanProperty(ConfigParam.VALIDATE_INCOMING_XML).booleanValue());

        // Get original senders IP-address, both directly and from the proxy('s).
        String addresslist = request.getRemoteAddr() + "," + request.getRemoteHost();
        String address = request.getHeader("X-Forwarded-For");
        if (address != null) {
            addresslist += "," + address;
        }

        // check if the sender is allowed to send messages to this endpoint
        messageFilterService.filterMessage(signedMessage.getSenderDomain(), addresslist);

        // verify sender by trying to unsing message
        String unsignedContent = verifyMessage(signedMessage);
        LOGGER_CONFIDENTIAL.debug("Received msg: {} ", unsignedContent);

        Message message = (Message) XMLUtil.xmlToMessage(unsignedContent,
                config.getBooleanProperty(ConfigParam.VALIDATE_INCOMING_XML).booleanValue());

        incomingMessageVerificationService.validateMessageId(message.getMessageMetadata().getMessageID());
        incomingMessageVerificationService
                .validateMessageValidUntil(message.getMessageMetadata().getValidUntil());

        // Check if the metadata is correct and the participant exists
        incomingMessageVerificationService.validateSender(signedMessage, message);

        jmsService.sendMessageToInQueue(unsignedContent);

        return Response.status(OK)
                .entity("Correctly received msg " + unsignedContent + " and set in to the IN queue").build();

    } catch (BusinessException e) {
        LOGGER.warn(e.getMessage(), e);
        return createBusinessErrorResponse(e);
    } catch (TechnicalException e) {
        LOGGER.error(e.getMessage(), e);
        return createErrorResponse(e.getMessage());
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return createErrorResponse("Unknown server problem occurred.");
    }
}

From source file:bbdn.lti2.LTI2Servlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*w  w  w .j  a v a 2s  . c  om*/
        doRequest(request, response);
    } catch (Exception e) {
        String ipAddress = request.getRemoteAddr();
        String uri = request.getRequestURI();
        M_log.warn("General LTI2 Failure URI=" + uri + " IP=" + ipAddress);
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        doErrorJSON(request, response, null, "General failure", e);
    }
}

From source file:org.jasig.cas.support.pac4j.web.flow.ClientBackChannelAction.java

private void log(HttpServletRequest request) {

    logger.debug("=========================================================");
    logger.debug("ClientBackChannelAction.doExecute: ");
    logger.debug("request.method: " + request.getMethod());
    logger.debug("request.requestURI: " + request.getRequestURI());
    logger.debug("request.queryString: " + request.getQueryString());
    logger.debug("request. host port remoteaddress: " + request.getRemoteHost() + " " + request.getRemotePort()
            + " " + request.getRemoteAddr());
    logger.debug("request. parameter:");
    Enumeration enParams = request.getParameterNames();
    while (enParams.hasMoreElements()) {
        String paramName = (String) enParams.nextElement();
        logger.debug(paramName + ": " + request.getParameter(paramName));
    }//  w w  w.ja v a2s. c  o  m

    logger.debug("request. attribute:");
    Enumeration enParams2 = request.getAttributeNames();
    while (enParams2.hasMoreElements()) {
        String paramName2 = (String) enParams2.nextElement();
        logger.debug(paramName2 + ": " + request.getAttribute(paramName2));
    }
    logger.debug("=========================================================");
}

From source file:br.interactive.ecm.gerais.service.UsuarioService.java

public LoginDTO login(LoginDTO user, HttpServletRequest request) {

    if (!StringUtil.notEmpty(user.getSenha())) {
        throw new BusinessException(new ErrorMessage("seguranca.login.naoencontrado"));
    }//  w  ww .  j a  va2 s  . c  o  m

    //        Usuario usua = usuarioDAO.getUsuarioByLoginSenha(user.getLogin(), user.getSenha());
    // FIXME Obter usuario
    Usuario usua = new Usuario();
    Pessoa p = new Pessoa();
    p.setTxNome("Nome do Usuario");
    p.setUsuario(usua);
    usua.setPessoa(p);

    //        this.validarUsuarioParaAutenticacao(usua);
    UserSession userSession = userSessionDAO.getUserSessionLoginBrowserIp(usua.getTxLogin(),
            request.getHeader("user-agent"), request.getRemoteAddr());

    if (userSession != null) {
        userSessionDAO.remove(userSession);
    }

    String token = UUID.randomUUID().toString();
    UserSession session = new UserSession();
    session.setTxLogin(usua.getTxLogin());
    session.setTxToken(token);
    session.setDtStartOrRefreshSession(new Date());
    session.setDtExpiredSession(DateUtils.addMinutes(new Date(), 120));
    session.setTxBrowser(request.getHeader("user-agent"));
    session.setTxIpAdress(request.getRemoteAddr());
    userSessionDAO.persist(session);
    user.sethToken(token);

    usua.setNbTentativas(Short.valueOf("0"));
    usua.setDtDataAcesso(Calendar.getInstance());
    usuarioDAO.merge(usua);

    return user;
}