Example usage for javax.servlet.http HttpServletRequest getRemoteHost

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

Introduction

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

Prototype

public String getRemoteHost();

Source Link

Document

Returns the fully qualified name of the client or the last proxy that sent the request.

Usage

From source file:org.wrml.server.WrmlServlet.java

/**
 * Get the requested resource's id from the the {@link HttpServletRequest}.
 *
 * @param request The {@link HttpServletRequest} that holds the {@link URI}.
 * @return The requested resource's id from the the {@link HttpServletRequest}.
 * @throws URISyntaxException Thrown if there is a syntax problem when constructing the {@link URI}.
 *///from   w ww.j  a v a2s  .c  om
URI getRequestUri(final HttpServletRequest request) throws URISyntaxException {
    // Due to the quirky nature of a servlet container, we're after the entire path.  
    // This seems to work with servlet 3.0 and Tomcat 7.X
    String path = request.getServletPath();
    String extra = request.getPathInfo();
    if (path != null && extra != null) {
        path += request.getPathInfo();
    } else if (path == null) {
        path = extra;
    }

    if (path.endsWith("/")) {
        path = path.substring(0, path.length() - 1);
    }

    final String host = StringUtils.defaultIfEmpty(request.getHeader(WRML_HOST_HEADER_NAME),
            request.getRemoteHost());
    final String portString = StringUtils.defaultIfEmpty(request.getHeader(WRML_PORT_HEADER_NAME),
            Integer.toString(request.getRemotePort()));
    final String scheme = StringUtils.defaultIfEmpty(request.getHeader(WRML_SCHEME_HEADER_NAME),
            request.getScheme());
    int port = -1;

    port = Integer.parseInt(portString);
    if (port == 80) {
        port = -1;
    }
    final URI requestUri = new URI(scheme, null, host, port, path, null, null);

    LOGGER.debug("Determined request URI: {}", requestUri);
    return requestUri;
}

From source file:com.adito.core.actions.AuthenticatedDispatchAction.java

/**
 * This abstract class will populate all the common variables required by an
 * action within the webstudio framework, such as current user, permission
 * database, user database etc// www .jav a2s .  c o  m
 * 
 * @param mapping
 * @param form
 * @param request
 * @param response
 * 
 * @exception Exception if business logic throws an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // Setup mode
    boolean setupMode = ContextHolder.getContext().isSetupMode();
    if (setupMode) {
        if ((getNavigationContext(mapping, form, request, response) & SessionInfo.SETUP_CONSOLE_CONTEXT) == 0) {
            return mapping.findForward("setup");
        } else {
            /*
             * Make the mapping and form available, this helps with reusing
             * some JSP pages
             */
            request.setAttribute(Constants.REQ_ATTR_ACTION_MAPPING, mapping);
            request.setAttribute(Constants.REQ_ATTR_FORM, form);

            //
            CoreUtil.checkNavigationContext(this, mapping, form, request, response);
            return super.execute(mapping, form, request, response);
        }
    }
    try {
        try {
            if (!SystemDatabaseFactory.getInstance().verifyIPAddress(request.getRemoteAddr())) {
                String link = null;
                log.error(request.getRemoteHost() + " is not authorized");
                if (log.isInfoEnabled())
                    log.info("Logging off, IP address verification failed.");

                if (LogonControllerFactory.getInstance().hasClientLoggedOn(request,
                        response) == LogonController.LOGGED_ON) {
                    LogonControllerFactory.getInstance().logoffSession(request, response);
                }

                if (link != null) {
                    ActionForward fwd = new ActionForward(link, true);
                    return fwd;
                } else {
                    // Do not direct to logon page for Ajax requests
                    if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
                        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                        return null;
                    }
                    return (mapping.findForward("logon"));
                }
            } else {
                /*
                 * Make the mapping and form available, this helps with
                 * reusing some JSP pages
                 */
                request.setAttribute(Constants.REQ_ATTR_ACTION_MAPPING, mapping);
                request.setAttribute(Constants.REQ_ATTR_FORM, form);

                int logonStatus = LogonControllerFactory.getInstance().hasClientLoggedOn(request, response);
                if (logonStatus == LogonController.INVALID_TICKET) {
                    ActionMessages msgs = new ActionMessages();
                    msgs.add(Globals.ERROR_KEY, new ActionMessage("login.invalidTicket"));
                    saveErrors(request, msgs);
                } else if (logonStatus == LogonController.LOGGED_ON) {
                    SessionInfo session = LogonControllerFactory.getInstance().getSessionInfo(request);
                    // Set the logon ticket / domain logon ticket again
                    LogonControllerFactory.getInstance().addCookies(new ServletRequestAdapter(request),
                            new ServletResponseAdapter(response),
                            (String) request.getSession().getAttribute(Constants.LOGON_TICKET),
                            getSessionInfo(request));

                    ActionForward fwd = checkIntercept(mapping, request, response);
                    if (fwd != null) {
                        return fwd;
                    }

                    /*
                     * Make sure the current navigation context is correct.
                     * If not, then check the user can switch to the correct
                     * and switch it.
                     */
                    CoreUtil.checkNavigationContext(this, mapping, form, request, response);

                    PropertyProfile profile = null;
                    if (request.getSession().getAttribute(Constants.SESSION_LOCKED) == null) {
                        profile = (PropertyProfile) request.getSession()
                                .getAttribute(Constants.SELECTED_PROFILE);
                        if (profile == null) {
                            request.getSession().setAttribute(Constants.ORIGINAL_REQUEST,
                                    Util.getOriginalRequest(request));
                            return mapping.findForward("selectPropertyProfile");
                        }
                        doCheckPermissions(mapping, session, request);
                        return super.execute(mapping, form, request, response);
                    }
                }
            }
        } catch (NoPermissionException e) {
            if (log.isDebugEnabled())
                log.debug("User " + e.getPrincipalName()
                        + " attempted to access page they do have have permission for. Resource type = "
                        + e.getResourceType()
                        + ". Now attempting to find the first valid item in the current menu tree to display.",
                        e);
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        } catch (SecurityException ex) {
            // Not logged in or expired
        } catch (ServletException ex) {
            throw ex;
        }

        // Do not direct to logon page for Ajax requests
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            return null;
        }

        return gotoLogon(mapping, form, request, response);
    } catch (Throwable t) {
        log.error("Failed to process authenticated request.", t);
        throw t instanceof Exception ? (Exception) t : new Exception(t);
    }
}

From source file:edu.umich.its.lti.google.GoogleLtiServlet.java

/**
 * This records TcSessionData holding LTI session specific data, and returns
 * it for sharing it's unique key with the browser, ensuring requests coming
 * from the browser carrying this key are for the correct LTI session.
 * //  www. j a  va  2  s .co  m
 * @param request
 *            HttpServletRequest holding the session
 */
private TcSessionData lockInSession(HttpServletRequest request) {
    // Store TC data in session.
    TcSessionData result = null;
    String ltiSecret = getGoogleServiceAccount(request.getRemoteHost()).getLtiSecret();
    String ltiKey = getGoogleServiceAccount(request.getRemoteHost()).getLtiKey();
    String ltiUrl = getGoogleServiceAccount(request.getRemoteHost()).getLtiUrl();
    String ltiKeyFromLaunch = request.getParameter("oauth_consumer_key");
    if ((ltiKey.equals(ltiKeyFromLaunch))) {
        OauthCredentials oauthCredentials = new OauthCredentials(ltiKey, ltiSecret, ltiUrl);
        result = new TcSessionData(request, oauthCredentials);
    } else {
        M_log.error(
                "The LTI key from the launch of the application is not same as LTI key from the properties file");
        return result;
    }
    if (getIsEmpty(result.getUserEmailAddress())) {
        throw new IllegalStateException(
                "Google Drive LTI was opened by user without email address. Please verify the tool is configured by checking the SEND EMAIL ADDRESSES TO EXTERNAL TOOL option for course (context_id): "
                        + result.getContextId());
    }
    request.setAttribute(SESSION_ATTR_TC_DATA, result);
    request.getSession().setAttribute(SESSION_ATTR_TC_DATA, result);
    return result;
}

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(//ww w  .  j ava 2 s .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:siddur.solidtrust.site.APIController.java

@Transactional(readOnly = true)
@RequestMapping(value = "/euroncap")
public @ResponseBody Object euroncap(@RequestParam("id") String id, HttpServletRequest request)
        throws Exception {
    AccessItem ai = new AccessItem();
    ai.setRequest(id);/*from   w w w  . j ava 2 s .  c o  m*/
    ai.setIp(request.getRemoteHost());
    ai.setUsername(request.getAttribute(SolidtrustConstants.CLIENT_ID) + "");
    ai.setService(Product.EURONCAP.getId());

    AzureCar entity = null;

    if (!StringUtils.isEmpty(id)) {
        entity = azureService.findByLicensePlate(id.trim());
    }

    Object result = null;
    if (entity != null) {

        String brand = entity.getBrand();
        String model = entity.getType();
        @SuppressWarnings("deprecation")
        String build = (entity.getDateOfBuild().getYear() + 1900) + "";

        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
        FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
        QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Euroncap.class)
                .get();

        String s = "0, 0, 0";
        String[] boostArray = null;
        boostArray = s.split(",");

        @SuppressWarnings("rawtypes")
        BooleanJunction bj = qb.bool();
        if (brand != null) {
            QueryParser parser = new QueryParser(Version.LUCENE_36, "brand", analyzer);
            LuceneUtil.setBoost(0, boostArray, parser.parse(brand), bj);
        }

        if (model != null) {
            try {
                model = ss.find(model, "1");
            } catch (Exception e1) {
                log4j.warn(e1.getMessage(), e1);
            }
            QueryParser parser = new QueryParser(Version.LUCENE_36, "model", analyzer);
            LuceneUtil.setBoost(1, boostArray, parser.parse(model), bj);
        }

        if (build != null) {
            @SuppressWarnings("rawtypes")
            BooleanJunction rangebj = qb.bool();
            Query range = rangebj.must(new TermRangeQuery("buildFrom", "0000", build, true, true))
                    .must(new TermRangeQuery("buildTo", build, "9999", true, true)).createQuery();
            LuceneUtil.setBoost(2, boostArray, range, bj);
        }

        Query query = bj.createQuery();
        FullTextQuery persistenceQuery = fullTextEntityManager.createFullTextQuery(query, Euroncap.class);
        persistenceQuery.setMaxResults(15);

        @SuppressWarnings("unchecked")
        List<Euroncap> list = persistenceQuery.getResultList();

        if (list.isEmpty()) {
            result = "no data";
            ai.setStatus(0);
            ai.setResponse(null);
        } else {

            Euroncap nearestEu = list.get(0);

            if (entity.getDateOfBuild() != null) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(entity.getDateOfBuild());
                int year = cal.get(Calendar.YEAR);
                int distance = 3000;
                for (Euroncap eu : list) {
                    int y = 0;
                    try {
                        y = Integer.parseInt(eu.getBuild());
                    } catch (Exception e) {
                    }

                    int d = Math.abs(year - y);
                    if (d < distance) {
                        distance = d;
                        nearestEu = eu;
                    }
                }
            }
            result = nearestEu;
            ai.setResponse(nearestEu.toString());

        }
    } else {
        String r = "Not found:" + id;
        ai.setResponse(r);
        result = r;
        ai.setStatus(0);
    }

    free.save(ai);
    return result;
}

From source file:siddur.solidtrust.site.APIController.java

@RequestMapping(value = "/car_manual")
public @ResponseBody Object carManual(@RequestParam("brand") String brand, @RequestParam("model") String model,
        HttpServletRequest request, HttpServletResponse resp) {
    resp.setHeader("Access-Control-Allow-Origin", "*");
    AccessItem ai = new AccessItem();
    ai.setRequest(brand + " " + model);
    ai.setIp(request.getRemoteHost());
    ai.setUsername(request.getAttribute(SolidtrustConstants.CLIENT_ID) + "");
    ai.setService(Product.CAR_MANUAL.getId());

    final String address = request.getLocalAddr();
    final int port = request.getLocalPort();
    String portStr = port == 80 ? "" : ":" + port;
    String prex = "http://" + address + portStr + "/solidtrust/images/";

    Object result = null;//from  w  w w.  j av a2  s.co m
    try {
        List<Manual> list = manualRep.findByBrandAndModel(brand, model);
        if (list.size() > 0) {
            siddur.solidtrust.manual.Car car = new siddur.solidtrust.manual.Car();
            Manual m = list.get(0);
            car.setAcceleration(m.getAcceleration());
            car.setAverageMileage(m.getAverageMileage());
            car.setBrand(m.getBrand());
            car.setBuildFrom(m.getBuildFrom());
            car.setBuildTo(m.getBuildTo());
            car.setImage(prex + m.getImage() + "_1.jpg");
            car.setModel(m.getModel());
            car.setNewPrice(m.getNewPrice());
            car.setRoadTax(m.getRoadTax());
            car.setTireSize(m.getTireSize());
            car.setTopspeed(m.getTopspeed());
            for (Manual manual : list) {
                String[] files = manual.getManual().split(";");
                for (String f : files) {
                    ManualItem mi = new ManualItem();
                    mi.setBuildYear(manual.getBuild());
                    mi.setImage(prex + manual.getImage() + "_1.jpg");
                    mi.setUrl(f);
                    car.getManual().add(mi);
                }
            }
            result = car;
        }
    } catch (Exception e) {
        ai.setStatus(-1);
        log4j.info(e.getMessage(), e);
    }
    if (result == null) {
        result = "no data";
        ai.setStatus(0);
    }
    ai.setResponse(result + "");
    free.save(ai);
    return result;
}

From source file:org.apache.ranger.biz.AssetMgr.java

public void createPluginInfo(String serviceName, String pluginId, HttpServletRequest request, int entityType,
        long downloadedVersion, long lastKnownVersion, long lastActivationTime, int httpCode) {
    RangerRESTUtils restUtils = new RangerRESTUtils();

    final String ipAddress = request != null ? request.getRemoteAddr() : null;
    final String appType = restUtils.getAppIdFromPluginId(pluginId);

    String tmpHostName = null;/*from   w w  w . ja v  a  2  s  .c  o m*/
    if (StringUtils.isNotBlank(pluginId)) {
        tmpHostName = restUtils.getHostnameFromPluginId(pluginId, serviceName);
    }
    if (StringUtils.isBlank(tmpHostName) && request != null) {
        tmpHostName = request.getRemoteHost();
    }

    final String hostName = (StringUtils.isBlank(tmpHostName)) ? ipAddress : tmpHostName;

    RangerPluginInfo pluginSvcVersionInfo = new RangerPluginInfo();

    pluginSvcVersionInfo.setServiceName(serviceName);
    pluginSvcVersionInfo.setAppType(appType);
    pluginSvcVersionInfo.setHostName(hostName);
    pluginSvcVersionInfo.setIpAddress(ipAddress);

    if (entityType == RangerPluginInfo.ENTITY_TYPE_POLICIES) {
        pluginSvcVersionInfo.setPolicyActiveVersion(lastKnownVersion);
        pluginSvcVersionInfo.setPolicyActivationTime(lastActivationTime);
        pluginSvcVersionInfo.setPolicyDownloadedVersion(downloadedVersion);
        pluginSvcVersionInfo.setPolicyDownloadTime(new Date().getTime());
    } else {
        pluginSvcVersionInfo.setTagActiveVersion(lastKnownVersion);
        pluginSvcVersionInfo.setTagActivationTime(lastActivationTime);
        pluginSvcVersionInfo.setTagDownloadedVersion(downloadedVersion);
        pluginSvcVersionInfo.setTagDownloadTime(new Date().getTime());
    }

    createOrUpdatePluginInfo(pluginSvcVersionInfo, httpCode);
}

From source file:org.apache.nifi.processors.standard.servlets.ListenHTTPServlet.java

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    final ProcessContext context = processContext;

    ProcessSessionFactory sessionFactory;
    do {//w w  w  .j  a  v a  2 s.  c o  m
        sessionFactory = sessionFactoryHolder.get();
        if (sessionFactory == null) {
            try {
                Thread.sleep(10);
            } catch (final InterruptedException e) {
            }
        }
    } while (sessionFactory == null);

    final ProcessSession session = sessionFactory.createSession();
    FlowFile flowFile = null;
    String holdUuid = null;
    String foundSubject = null;
    try {
        final long n = filesReceived.getAndIncrement() % FILES_BEFORE_CHECKING_DESTINATION_SPACE;
        if (n == 0 || !spaceAvailable.get()) {
            if (context.getAvailableRelationships().isEmpty()) {
                spaceAvailable.set(false);
                if (logger.isDebugEnabled()) {
                    logger.debug("Received request from " + request.getRemoteHost()
                            + " but no space available; Indicating Service Unavailable");
                }
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                return;
            } else {
                spaceAvailable.set(true);
            }
        }
        response.setHeader("Content-Type", MediaType.TEXT_PLAIN);

        final boolean contentGzipped = Boolean.parseBoolean(request.getHeader(GZIPPED_HEADER));

        final X509Certificate[] certs = (X509Certificate[]) request
                .getAttribute("javax.servlet.request.X509Certificate");
        foundSubject = DEFAULT_FOUND_SUBJECT;
        if (certs != null && certs.length > 0) {
            for (final X509Certificate cert : certs) {
                foundSubject = cert.getSubjectDN().getName();
                if (authorizedPattern.matcher(foundSubject).matches()) {
                    break;
                } else {
                    logger.warn("Rejecting transfer attempt from " + foundSubject
                            + " because the DN is not authorized, host=" + request.getRemoteHost());
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "not allowed based on dn");
                    return;
                }
            }
        }

        final String destinationVersion = request.getHeader(PROTOCOL_VERSION_HEADER);
        Integer protocolVersion = null;
        if (destinationVersion != null) {
            try {
                protocolVersion = Integer.valueOf(destinationVersion);
            } catch (final NumberFormatException e) {
                // Value was invalid. Treat as if the header were missing.
            }
        }

        final boolean destinationIsLegacyNiFi = (protocolVersion == null);
        final boolean createHold = Boolean.parseBoolean(request.getHeader(FLOWFILE_CONFIRMATION_HEADER));
        final String contentType = request.getContentType();

        final InputStream unthrottled = contentGzipped ? new GZIPInputStream(request.getInputStream())
                : request.getInputStream();

        final InputStream in = (streamThrottler == null) ? unthrottled
                : streamThrottler.newThrottledInputStream(unthrottled);

        if (logger.isDebugEnabled()) {
            logger.debug("Received request from " + request.getRemoteHost() + ", createHold=" + createHold
                    + ", content-type=" + contentType + ", gzip=" + contentGzipped);
        }

        final AtomicBoolean hasMoreData = new AtomicBoolean(false);
        final FlowFileUnpackager unpackager;
        if (APPLICATION_FLOW_FILE_V3.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV3();
        } else if (APPLICATION_FLOW_FILE_V2.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV2();
        } else if (APPLICATION_FLOW_FILE_V1.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV1();
        } else {
            unpackager = null;
        }

        final Set<FlowFile> flowFileSet = new HashSet<>();

        do {
            final long startNanos = System.nanoTime();
            final Map<String, String> attributes = new HashMap<>();
            flowFile = session.create();
            flowFile = session.write(flowFile, new OutputStreamCallback() {
                @Override
                public void process(final OutputStream rawOut) throws IOException {
                    try (final BufferedOutputStream bos = new BufferedOutputStream(rawOut, 65536)) {
                        if (unpackager == null) {
                            IOUtils.copy(in, bos);
                            hasMoreData.set(false);
                        } else {
                            attributes.putAll(unpackager.unpackageFlowFile(in, bos));

                            if (destinationIsLegacyNiFi) {
                                if (attributes.containsKey("nf.file.name")) {
                                    // for backward compatibility with old nifi...
                                    attributes.put(CoreAttributes.FILENAME.key(),
                                            attributes.remove("nf.file.name"));
                                }

                                if (attributes.containsKey("nf.file.path")) {
                                    attributes.put(CoreAttributes.PATH.key(),
                                            attributes.remove("nf.file.path"));
                                }
                            }

                            hasMoreData.set(unpackager.hasMoreData());
                        }
                    }
                }
            });

            final long transferNanos = System.nanoTime() - startNanos;
            final long transferMillis = TimeUnit.MILLISECONDS.convert(transferNanos, TimeUnit.NANOSECONDS);

            // put metadata on flowfile
            final String nameVal = request.getHeader(CoreAttributes.FILENAME.key());
            if (StringUtils.isNotBlank(nameVal)) {
                attributes.put(CoreAttributes.FILENAME.key(), nameVal);
            }

            // put arbitrary headers on flow file
            for (Enumeration<String> headerEnum = request.getHeaderNames(); headerEnum.hasMoreElements();) {
                String headerName = headerEnum.nextElement();
                if (headerPattern != null && headerPattern.matcher(headerName).matches()) {
                    String headerValue = request.getHeader(headerName);
                    attributes.put(headerName, headerValue);
                }
            }

            String sourceSystemFlowFileIdentifier = attributes.get(CoreAttributes.UUID.key());
            if (sourceSystemFlowFileIdentifier != null) {
                sourceSystemFlowFileIdentifier = "urn:nifi:" + sourceSystemFlowFileIdentifier;

                // If we receveied a UUID, we want to give the FlowFile a new UUID and register the sending system's
                // identifier as the SourceSystemFlowFileIdentifier field in the Provenance RECEIVE event
                attributes.put(CoreAttributes.UUID.key(), UUID.randomUUID().toString());
            }

            flowFile = session.putAllAttributes(flowFile, attributes);
            session.getProvenanceReporter().receive(flowFile, request.getRequestURL().toString(),
                    sourceSystemFlowFileIdentifier, "Remote DN=" + foundSubject, transferMillis);
            flowFile = session.putAttribute(flowFile, "restlistener.remote.source.host",
                    request.getRemoteHost());
            flowFile = session.putAttribute(flowFile, "restlistener.remote.user.dn", foundSubject);
            flowFileSet.add(flowFile);

            if (holdUuid == null) {
                holdUuid = flowFile.getAttribute(CoreAttributes.UUID.key());
            }
        } while (hasMoreData.get());

        if (createHold) {
            String uuid = (holdUuid == null) ? UUID.randomUUID().toString() : holdUuid;

            if (flowFileMap.containsKey(uuid)) {
                uuid = UUID.randomUUID().toString();
            }

            final FlowFileEntryTimeWrapper wrapper = new FlowFileEntryTimeWrapper(session, flowFileSet,
                    System.currentTimeMillis());
            FlowFileEntryTimeWrapper previousWrapper;
            do {
                previousWrapper = flowFileMap.putIfAbsent(uuid, wrapper);
                if (previousWrapper != null) {
                    uuid = UUID.randomUUID().toString();
                }
            } while (previousWrapper != null);

            response.setStatus(HttpServletResponse.SC_SEE_OTHER);
            final String ackUri = "/" + basePath + "/holds/" + uuid;
            response.addHeader(LOCATION_HEADER_NAME, ackUri);
            response.addHeader(LOCATION_URI_INTENT_NAME, LOCATION_URI_INTENT_VALUE);
            response.getOutputStream().write(ackUri.getBytes("UTF-8"));
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Ingested {} from Remote Host: [{}] Port [{}] SubjectDN [{}]; placed hold on these {} files with ID {}",
                        new Object[] { flowFileSet, request.getRemoteHost(), request.getRemotePort(),
                                foundSubject, flowFileSet.size(), uuid });
            }
        } else {
            response.setStatus(HttpServletResponse.SC_OK);
            logger.info(
                    "Received from Remote Host: [{}] Port [{}] SubjectDN [{}]; transferring to 'success' {}",
                    new Object[] { request.getRemoteHost(), request.getRemotePort(), foundSubject, flowFile });

            session.transfer(flowFileSet, ListenHTTP.RELATIONSHIP_SUCCESS);
            session.commit();
        }
    } catch (final Throwable t) {
        session.rollback();
        if (flowFile == null) {
            logger.error("Unable to receive file from Remote Host: [{}] SubjectDN [{}] due to {}",
                    new Object[] { request.getRemoteHost(), foundSubject, t });
        } else {
            logger.error("Unable to receive file {} from Remote Host: [{}] SubjectDN [{}] due to {}",
                    new Object[] { flowFile, request.getRemoteHost(), foundSubject, t });
        }
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t.toString());
    }
}

From source file:com.reachcall.pretty.http.ProxyServlet.java

@SuppressWarnings("unchecked")
public void copyHeaders(HttpServletRequest req, HttpRequestBase method) {
    Enumeration names = req.getHeaderNames();

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();

        if (name.equalsIgnoreCase(HEADER_CONTENT_LENTH)) {
            continue;
        }//from  www  .j  a  va2 s . c  o m

        Enumeration values = req.getHeaders(name);

        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            LOG.log(Level.FINER, "{0} : {1}", new Object[] { name, value });

            if (name.equalsIgnoreCase(HEADER_HOST) || name.equalsIgnoreCase(HEADER_X_FORWARDED_FOR)) {
                continue;
            } else {
                method.addHeader(name, value);
            }
        }

        setVHost(req.getHeader("Host"));
    }
    method.addHeader(HEADER_REMOTE_HOST, req.getRemoteAddr());
    String xff = req.getHeader(HEADER_X_FORWARDED_FOR);

    if (xff == null) {
        xff = "";
    } else {
        xff = xff + ", ";
    }

    method.addHeader(HEADER_X_FORWARDED_FOR, xff + req.getRemoteHost());

    if (req.getHeader(HEADER_X_ORIGINAL_REQUEST_URL) == null) {
        method.addHeader(HEADER_X_ORIGINAL_REQUEST_URL, req.getRequestURL().toString());
    }
}

From source file:org.opencastproject.ingest.endpoint.IngestRestService.java

private Response ingestZippedMediaPackage(HttpServletRequest request, String wdID, String wiID) {
    if (isIngestLimitEnabled()) {
        setIngestLimit(getIngestLimit() - 1);
        logger.debug("An ingest has started so remaining ingest limit is " + getIngestLimit());
    }//from   w w w.  j a  va2s. co  m
    InputStream in = null;

    logger.info("Received new request from {} to ingest a zipped mediapackage", request.getRemoteHost());

    try {
        String workflowDefinitionId = wdID;
        String workflowIdAsString = wiID;
        Long workflowInstanceIdAsLong = null;
        Map<String, String> workflowConfig = new HashMap<String, String>();
        if (ServletFileUpload.isMultipartContent(request)) {
            boolean isDone = false;
            for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) {
                FileItemStream item = iter.next();
                if (item.isFormField()) {
                    if (WORKFLOW_INSTANCE_ID_PARAM.equals(item.getFieldName())) {
                        workflowIdAsString = IOUtils.toString(item.openStream(), "UTF-8");
                        continue;
                    } else if (WORKFLOW_DEFINITION_ID_PARAM.equals(item.getFieldName())) {
                        workflowDefinitionId = IOUtils.toString(item.openStream(), "UTF-8");
                        continue;
                    } else {
                        logger.debug("Processing form field: " + item.getFieldName());
                        workflowConfig.put(item.getFieldName(), IOUtils.toString(item.openStream(), "UTF-8"));
                    }
                } else {
                    logger.debug("Processing file item");
                    // once the body gets read iter.hasNext must not be invoked or the stream can not be read
                    // MH-9579
                    in = item.openStream();
                    isDone = true;
                }
                if (isDone)
                    break;
            }
        } else {
            logger.debug("Processing file item");
            in = request.getInputStream();
        }

        /* Try to convert the workflowId to integer */
        if (!StringUtils.isBlank(workflowIdAsString)) {
            try {
                workflowInstanceIdAsLong = Long.parseLong(workflowIdAsString);
            } catch (NumberFormatException e) {
                logger.warn("{} '{}' is not numeric", WORKFLOW_INSTANCE_ID_PARAM, workflowIdAsString);
            }
        }
        if (StringUtils.isBlank(workflowDefinitionId)) {
            workflowDefinitionId = defaultWorkflowDefinitionId;
        }

        WorkflowInstance workflow = ingestService.addZippedMediaPackage(in, workflowDefinitionId,
                workflowConfig, workflowInstanceIdAsLong);
        return Response.ok(WorkflowParser.toXml(workflow)).build();
    } catch (MediaPackageException e) {
        logger.warn(e.getMessage());
        return Response.serverError().status(Status.BAD_REQUEST).build();
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    } finally {
        IOUtils.closeQuietly(in);
        if (isIngestLimitEnabled()) {
            setIngestLimit(getIngestLimit() + 1);
            logger.debug("An ingest has finished so increased ingest limit to " + getIngestLimit());
        }
    }
}