Example usage for javax.servlet.http HttpServletRequest getCookies

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

Introduction

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

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

From source file:net.ymate.framework.webmvc.AbstractWebErrorProcessor.java

private String __doParseExceptionDetail(Throwable e) {
    IRequestContext _requestCtx = WebContext.getRequestContext();
    HttpServletRequest _request = WebContext.getRequest();
    WebContext _context = WebContext.getContext();
    ////from   w  w w  . j a  va 2 s . c o  m
    StringBuilder _errSB = new StringBuilder("An exception occurred at ")
            .append(DateTimeUtils.formatTime(System.currentTimeMillis(), DateTimeUtils.YYYY_MM_DD_HH_MM_SS_SSS))
            .append(":\n");
    _errSB.append("-------------------------------------------------\n");
    _errSB.append("-- ThreadId: ").append(Thread.currentThread().getId()).append("\n");
    _errSB.append("-- RequestMapping: ").append(_requestCtx.getRequestMapping()).append("\n");
    _errSB.append("-- ResponseStatus: ").append(((GenericResponseWrapper) WebContext.getResponse()).getStatus())
            .append("\n");
    _errSB.append("-- Method: ").append(_requestCtx.getHttpMethod().name()).append("\n");
    _errSB.append("-- RemoteAddrs: ").append(JSON.toJSONString(WebUtils.getRemoteAddrs(_request))).append("\n");
    RequestMeta _meta = _context.getAttribute(RequestMeta.class.getName());
    if (_meta != null) {
        _errSB.append("-- Controller: ").append(_meta.getTargetClass().getName()).append(":")
                .append(_meta.getMethod().getName()).append("\n");
    }
    _errSB.append("-- ContextAttributes:").append("\n");
    for (Map.Entry<String, Object> _entry : _context.getAttributes().entrySet()) {
        if (!StringUtils.startsWith(_entry.getKey(), "net.ymate.platform.webmvc")) {
            _errSB.append("\t  ").append(_entry.getKey()).append(": ")
                    .append(JSON.toJSONString(_entry.getValue())).append("\n");
        }
    }
    _errSB.append("-- Parameters:").append("\n");
    for (Map.Entry<String, Object> _entry : _context.getParameters().entrySet()) {
        _errSB.append("\t  ").append(_entry.getKey()).append(": ").append(JSON.toJSONString(_entry.getValue()))
                .append("\n");
    }
    _errSB.append("-- Attributes:").append("\n");
    Enumeration _enum = _request.getAttributeNames();
    while (_enum.hasMoreElements()) {
        String _attrName = (String) _enum.nextElement();
        _errSB.append("\t  ").append(_attrName).append(": ")
                .append(JSON.toJSONString(_request.getAttribute(_attrName))).append("\n");
    }
    _errSB.append("-- Headers:").append("\n");
    _enum = _request.getHeaderNames();
    while (_enum.hasMoreElements()) {
        String _headName = (String) _enum.nextElement();
        if ("cookie".equalsIgnoreCase(_headName)) {
            continue;
        }
        _errSB.append("\t  ").append(_headName).append(": ")
                .append(JSON.toJSONString(_request.getHeader(_headName))).append("\n");
    }
    _errSB.append("-- Cookies:").append("\n");
    Cookie[] _cookies = _request.getCookies();
    if (_cookies != null) {
        for (Cookie _cookie : _cookies) {
            _errSB.append("\t  ").append(_cookie.getName()).append(": ")
                    .append(JSON.toJSONString(_cookie.getValue())).append("\n");
        }
    }
    _errSB.append("-- Session:").append("\n");
    for (Map.Entry<String, Object> _entry : _context.getSession().entrySet()) {
        _errSB.append("\t  ").append(_entry.getKey()).append(": ").append(JSON.toJSONString(_entry.getValue()))
                .append("\n");
    }
    _errSB.append(__doExceptionToString(e));
    _errSB.append("-------------------------------------------------\n");
    //
    return _errSB.toString();
}

From source file:org.guanxi.idp.service.AuthHandler.java

/**
 * Looks for an existing GuanxiPrincipal referenced by a request cookie. When a cookie is created after
 * a successful authentication at the IdP, either via the login page or an application cookie handler,
 * the corresponding GuanxiPrincipal is stored in the servlet context against the cookie value.
 * The new GuanxiPrincipal that is created after successful authentication is stored in the servlet
 * context under GuanxiPrincipal.id/*from  ww  w.j ava 2 s. co  m*/
 *
 * @param request Standard HttpServletRequest
 * @param response Standard HttpServletResponse
 * @param object handler
 * @return true 
 * @throws Exception if an error occurs
 */
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
        throws Exception {
    request.setCharacterEncoding("UTF-8");

    String missingParams = checkRequestParameters(request);
    if (missingParams != null) {
        logger.info("Missing param(s) : " + missingParams);
        request.setAttribute("message",
                messageSource.getMessage("missing.param", new Object[] { missingParams }, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    IdpDocument.Idp idpConfig = (IdpDocument.Idp) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG);

    boolean spSupported = false;
    EntityFarm farm = (EntityFarm) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_ENTITY_FARM);
    EntityManager manager = farm.getEntityManagerForID(request.getParameter(spIDRequestParam));
    if (manager != null) {
        SPMetadata metadata = (SPMetadata) manager.getMetadata(request.getParameter(spIDRequestParam));
        // Apply the trust rules to the SP
        if (metadata != null) {
            if (manager.getTrustEngine().trustEntity(metadata, request.getParameter("shire"))) {
                spSupported = true;
            } else {
                logger.error("Trust failure for " + request.getParameter(spIDRequestParam) + " --> "
                        + request.getParameter("shire"));
            }
        } else {
            logger.error("No Metadata Manager found for " + request.getParameter(spIDRequestParam));
        }
    } else {
        logger.error("No Metadata Manager");
    }

    // Check the locally registered SPs
    if (!spSupported) {
        ServiceProvider[] spList = idpConfig.getServiceProviderArray();
        for (int c = 0; c < spList.length; c++) {
            if (spList[c].getName().equals(request.getParameter(spIDRequestParam))) {
                // If it's in here, we trust it explicitly
                spSupported = true;
            }
        }
    }

    // Did we find the service provider?
    if (!spSupported) {
        logger.error(
                "Service Provider providerId " + request.getParameter(spIDRequestParam) + " not supported");
        request.setAttribute("message", messageSource.getMessage("sp.not.supported",
                new Object[] { request.getParameter(spIDRequestParam) }, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    // Look for our cookie. This is after any application cookie handler has authenticated the user
    String cookieName = getCookieName();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int c = 0; c < cookies.length; c++) {
            if (cookies[c].getName().equals(cookieName)) {
                // Retrieve the principal from the servlet context
                if (servletContext.getAttribute(cookies[c].getValue()) == null) {
                    // Out of date cookie value, so remove the cookie
                    cookies[c].setMaxAge(0);
                    response.addCookie(cookies[c]);
                } else {
                    // Found the principal from a previously established authentication
                    request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL,
                            (GuanxiPrincipal) servletContext.getAttribute(cookies[c].getValue()));
                    return true;
                }
            }
        }
    }

    // Are we getting an authentication request from the login page?
    if (request.getParameter("guanxi:mode") != null) {
        if (request.getParameter("guanxi:mode").equalsIgnoreCase("authenticate")) {
            // Get a new GuanxiPrincipal...
            GuanxiPrincipal principal = gxPrincipalFactory.createNewGuanxiPrincipal(request);
            if (authenticator.authenticate(principal, request.getParameter("userid"),
                    request.getParameter("password"))) {
                // ...associate it with a login name...
                if (principal.getName() == null) {
                    //The login name from the authenticator page
                    principal.setName(request.getParameter("userid"));
                }
                // ...store it in the request for the SSO to use...
                request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL, principal);
                // ...and store it in application scope for the rest of the profile to use
                servletContext.setAttribute(principal.getUniqueId(), principal);

                // Get a new cookie ready to reference the principal in the servlet context
                Cookie cookie = new Cookie(getCookieName(), principal.getUniqueId());
                cookie.setDomain((String) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_DOMAIN));
                cookie.setPath(idpConfig.getCookie().getPath());
                if (((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                        .intValue() != -1)
                    cookie.setMaxAge(
                            ((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                                    .intValue());
                response.addCookie(cookie);

                return true;
            } // if (authenticator.authenticate...
            else {
                logger.error("Authentication error : " + authenticator.getErrorMessage());
                request.setAttribute("message",
                        messageSource.getMessage("authentication.error", null, request.getLocale()));
                request.getRequestDispatcher(errorPage).forward(request, response);
                return false;
            }
        }
    }

    // No embedded cookie authentication or local auth, so show the login page
    String authPage = null;
    AuthPage[] authPages = idpConfig.getAuthenticatorPages().getAuthPageArray();
    for (int c = 0; c < authPages.length; c++) {
        // We'll use the default auth page if none is specified for this service provider
        if (authPages[c].getProviderId().equals(Guanxi.DEFAULT_AUTH_PAGE_MARKER)) {
            authPage = authPages[c].getUrl();
        }

        // Customised auth page for this service provider
        if (authPages[c].getProviderId().equals(request.getParameter(spIDRequestParam))) {
            authPage = authPages[c].getUrl();
        }
    }

    addRequiredParamsAsPrefixedAttributes(request);
    request.getRequestDispatcher(authPage).forward(request, response);

    return false;
}

From source file:com.lp.webapp.zemecs.CommandZE.java

private String getCookieValue(String key, HttpServletRequest request) {
    if (request != null && request.getCookies() != null) {

        for (int i = 0; i < request.getCookies().length; i++) {
            Cookie cookie = request.getCookies()[i];
            if (cookie.getName().equals(key)) {
                return cookie.getValue();
            }// w  ww  . j  av a  2s.  c om
        }
    }
    return null;
}

From source file:org.esgf.globusonline.GOauthView1Controller.java

@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView doPost(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //grab the dataset name, file names and urls from the query string
    String dataset_name = request.getParameter("id");
    String[] file_names = request.getParameterValues("child_id");
    String[] file_urls = request.getParameterValues("child_url");
    String esg_user = "";
    String esg_password = "";
    //String e;/*from  w w  w .  j ava 2  s .c o m*/
    //grab the credential string
    String credential = request.getParameter("credential");
    System.out.println("Starting GlobusOnline workflow");
    //System.out.println("\n\n\n\t\tGO Credential " + credential + "\n\n\n");

    StringBuffer currentURL = request.getRequestURL();
    String currentURI = request.getRequestURI();
    //System.out.println("current URL is: " + currentURL);
    //System.out.println("current URI is: " + currentURI);
    //System.out.println("index is: " + currentURL.lastIndexOf(currentURI));
    String BaseURL = currentURL.substring(0, currentURL.lastIndexOf(currentURI));
    //System.out.println("BaseURL string is: " + BaseURL );

    //Instantiate model object:
    Map<String, Object> model = new HashMap<String, Object>();

    //Bail out if no gsiftp URLs are in file_names
    if (file_names != null) {
        for (int i = 0; i < file_names.length; i++) {
            if (!(file_urls[i] == null) && (file_urls[i].contains("gsiftp"))) {
                break;
            } else {
                model.put(GOFORMVIEW_ERROR, "error");
                String error_msg = "Selected dataset " + dataset_name
                        + " contains no GridFTP URLS, and cannot be transferred with this transfer method.";
                model.put(GOFORMVIEW_ERROR_MSG, error_msg);
                return new ModelAndView("goauthview3", model);
            }
        }
    } else {
        System.out.println("file_urls itself was null\n");
        model.put(GOFORMVIEW_ERROR, "error");
        String error_msg = "Selected dataset(s) " + dataset_name
                + " contain no GridFTP URLS, and cannot be transferred with this transfer method.";
        model.put(GOFORMVIEW_ERROR_MSG, error_msg);
        return new ModelAndView("goauthview3", model);
    }
    //Create a session if it doesn't already exist, so we can save state.
    HttpSession session = request.getSession(true);
    if (session.isNew() == false) {
        session.invalidate();
        session = request.getSession(true);
    }

    //System.out.println("Auth1, session id is:" + session.getId());

    session.setAttribute("fileUrls", file_urls);
    session.setAttribute("fileNames", file_names);
    session.setAttribute("datasetName", dataset_name);
    session.setAttribute("baseurl", BaseURL);
    if (!(credential == null)) {
        session.setAttribute("usercertificatefile", credential);
    }

    Cookie[] cookies = request.getCookies();
    String openId = "";

    for (int i = 0; i < cookies.length; i++) {
        if (cookies[i].getName().equals("esgf.idp.cookie")) {
            openId = cookies[i].getValue();
        }
    }

    LOG.debug("Got User OpenID: " + openId);
    // Create the client
    Properties GOProperties = getGOProperties();
    String PortalID = (String) GOProperties.getProperty("GOesgfPortalID", "bogususer");
    String PortalPass = (String) GOProperties.getProperty("GOesgfPortalPassword", "boguspassword");

    String loginUri = "";
    try {
        GoauthClient cli = new GoauthClient("nexus.api.globusonline.org", "globusonline.org", PortalID,
                PortalPass);
        cli.setIgnoreCertErrors(true);

        // Redirect the user agent to the globusonline log in page
        loginUri = cli.getLoginUrl(response.encodeURL(BaseURL + "/esgf-web-fe/goauthview2"));

    } catch (NexusClientException e) {
        System.out.println("ERROR:  GOesgfPortalID and/or GOesgfPortalPassword wrong or not set.");
        //            e.printStackTrace();
        model.put(GOFORMVIEW_ERROR, "error");
        String error_msg = "GlobusOnline Configuration file not found. Please create /esg/config/globusonline.properties and populate it with GOesgfPortalID and GOesgfPortalPassword";
        model.put(GOFORMVIEW_ERROR_MSG, error_msg);
        return new ModelAndView("goauthview3", model);
    }
    String myproxyServerStr = null;

    return new ModelAndView("redirect:" + loginUri, model);
}

From source file:com.stormcloud.ide.api.filter.UserFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

    try {/*from   ww  w  .ja  v  a  2  s.c  o m*/

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        LOG.info("Filter Request [" + request.getRemoteAddr() + "]");

        MDC.put("api", httpRequest.getRequestURI());

        if (httpRequest.getRequestURI().endsWith("/api/login")) {

            // configure MDC for the remainging trip
            MDC.put("userName", httpRequest.getRemoteUser());

            LOG.debug("Login Request.");

            // it's a login request which succeeded (Basic Auth)
            // so we now need to genereate an authentication token
            // and store it in a cookie we sent back
            // create the cookie with key for consecutive Rest API Calls

            // Get user from db and add to the localthread
            User user = dao.getUser(httpRequest.getRemoteUser());

            if (user == null) {

                LOG.error("User not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;
            }

            // update last login
            user.setLastLogin(Calendar.getInstance().getTime());

            dao.save(user);

            RemoteUser.set(user);

            try {

                // set the key cookie
                Cookie keyCookie = new Cookie("stormcloud-key", createKey(user, httpRequest.getRemoteAddr()));

                keyCookie.setMaxAge(60 * 60 * 24); // 1 day

                keyCookie.setPath("/");
                keyCookie.setSecure(true);

                httpResponse.addCookie(keyCookie);

                // set the username cookie
                Cookie userCookie = new Cookie("stormcloud-user", user.getUserName());

                userCookie.setMaxAge(60 * 60 * 24); // 1 day

                userCookie.setPath("/");
                userCookie.setSecure(true);

                httpResponse.addCookie(userCookie);

            } catch (NoSuchAlgorithmException e) {

                LOG.error(e);

                try {

                    // no go
                    httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());

                    httpResponse.flushBuffer();
                    return;

                } catch (IOException ioe) {
                    LOG.error(ioe);
                }
            }

        } else if (httpRequest.getRequestURI().endsWith("/api/user/createAccount")) {

            // intercept and do something with create account
            LOG.debug("Create Account Request.");

        } else {

            LOG.info("API Request.");

            // any other request than a login
            // we need to check the username and received key
            Cookie[] cookies = httpRequest.getCookies();

            String userName = null;
            String key = null;

            if (cookies != null) {

                LOG.info("Found " + cookies.length + " Cookies");

                // loop trough the cookies
                for (int i = 0; i < cookies.length; i++) {

                    if (cookies[i].getName().equals("stormcloud-user")) {

                        LOG.debug("userName = " + cookies[i].getValue());
                        userName = cookies[i].getValue();
                    }

                    if (cookies[i].getName().equals("stormcloud-key")) {

                        LOG.debug("key = " + cookies[i].getValue());
                        key = cookies[i].getValue();
                    }
                }
            }

            if (userName == null || key == null) {

                LOG.info("Required credentials not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;

            } else {

                // configure MDC for the remainging trip
                MDC.put("userName", userName);

                // get user
                LOG.debug("Get Persisted User");
                User user = dao.getUser(userName);

                if (user == null) {
                    httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                    httpResponse.flushBuffer();
                    return;
                }

                RemoteUser.set(user);

                try {

                    String matchKey = createKey(user, httpRequest.getRemoteAddr());

                    LOG.info("Validating Key.");

                    if (!matchKey.equals(key)) {

                        LOG.warn("Invalid Key!");
                        httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                        httpResponse.flushBuffer();
                        return;

                    } else {

                        LOG.info("Request Authenticated");
                    }

                } catch (NoSuchAlgorithmException e) {

                    LOG.error(e);

                    try {

                        // no go
                        httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
                        httpResponse.flushBuffer();
                        return;

                    } catch (IOException ioe) {
                        LOG.error(ioe);
                    }
                }

            }
        }

        chain.doFilter(request, response);

    } catch (IOException e) {
        LOG.error(e);
    } catch (ServletException e) {
        LOG.error(e);
    } finally {

        // clear the logging diagnostics context
        MDC.clear();

        // Remove the user from memoty
        RemoteUser.destroy();
    }
}

From source file:edu.harvard.iq.dvn.core.web.servlet.FileDownloadServlet.java

private void zipMultipleFiles(HttpServletRequest req, HttpServletResponse res, VDCUser user, VDC vdc,
        UserGroup ipUserGroup) {/* w w w . j a v a  2 s.co  m*/
    // a request for a zip-packaged multiple file archive.

    String fileId = req.getParameter("fileId");
    String studyId = req.getParameter("studyId");
    String versionNumber = req.getParameter("versionNumber");
    System.out.print("zip multiple files version number" + versionNumber);
    Study study = null;
    Collection files = new ArrayList();
    boolean createDirectoriesForCategories = false;

    String fileManifest = "";

    String sessionId = null;
    javax.servlet.http.Cookie cookies[] = req.getCookies();

    for (int i = 0; i < cookies.length; i++) {
        if ("JSESSIONID".equals(cookies[i].getName())) {
            sessionId = cookies[i].getValue();
        }
    }

    if (sessionId == null || "".equals(sessionId)) {
        // if there's no JSESSIONID, we'll use the vdcSession id, for 
        // logging the download counts: 
        String[] stringArray = vdcSession.toString().toString().split("@");
        sessionId = stringArray[1];
    }

    if (fileId != null) {
        String[] idTokens = fileId.split(",");

        for (String tok : idTokens) {
            StudyFile sf;
            try {
                sf = studyFileService.getStudyFile(new Long(tok));
                files.add(sf);
            } catch (Exception ex) {
                fileManifest = fileManifest + tok + " DOES NOT APPEAR TO BE A VALID FILE ID;\r\n";
            }
        }
    } else if (studyId != null) {
        try {
            study = studyService.getStudy(new Long(studyId));
            files = study.getStudyFiles();
            createDirectoriesForCategories = true;
        } catch (Exception ex) {
            if (ex.getCause() instanceof IllegalArgumentException) {
                createErrorResponse404(res);
                return;
            }
        }
    } else {
        createErrorResponse404(res);
        return;
    }

    // check for restricted files
    Iterator iter = files.iterator();
    while (iter.hasNext()) {
        StudyFile file = (StudyFile) iter.next();
        if (file.isFileRestrictedForUser(user, ipUserGroup)) {
            fileManifest = fileManifest + file.getFileName() + " IS RESTRICTED AND CANNOT BE DOWNLOADED\r\n";
            iter.remove();
        }
    }

    if (files.size() == 0) {
        createErrorResponse403(res);
        return;
    }

    Long sizeLimit = Long.valueOf(104857600);
    // that's the default of 100 MB.

    Long sizeTotal = Long.valueOf(0);

    // this is the total limit of the size of all the files we
    // are packaging. if exceeded, we stop packaging files and add
    // a note to the manifest explaining what happened.
    // the value above is the default. a different value can
    // be set with a JVM option.

    String sizeLimitOption = System.getProperty("dvn.batchdownload.limit");

    if (sizeLimitOption != null) {
        Long sizeOptionValue = new Long(sizeLimitOption);
        if (sizeOptionValue > 0) {
            sizeLimit = sizeOptionValue;
        }
    }

    FileDownloadObject remoteDownload = null;

    // now create zip stream
    try {
        // set content type:
        res.setContentType("application/zip");

        // create zipped output stream:

        OutputStream out = res.getOutputStream();
        ZipOutputStream zout = new ZipOutputStream(out);

        List nameList = new ArrayList(); // used to check for duplicates
        List successList = new ArrayList();

        iter = files.iterator();

        while (iter.hasNext()) {
            int fileSize = 0;
            StudyFile file = (StudyFile) iter.next();

            if (sizeTotal < sizeLimit) {
                InputStream in = null;

                String varHeaderLine = null;
                String dbContentType = file.getFileType();

                if (dbContentType != null && dbContentType.equals("text/tab-separated-values")
                        && file.isSubsettable()) {
                    List datavariables = ((TabularDataFile) file).getDataTable().getDataVariables();
                    varHeaderLine = generateVariableHeader(datavariables);
                }

                if (dbContentType == null) {
                    dbContentType = "unknown filetype;";
                }

                Boolean Success = true;

                if (file.isRemote()) {

                    // do the http magic;
                    // remote files may be subject to complex authentication and
                    // authorization.
                    // And for that we have a special method...

                    remoteDownload = initiateRemoteDownload(file, req);

                    if (remoteDownload.getStatus() != 200) {
                        fileManifest = fileManifest + file.getFileName() + " (" + dbContentType
                                + ") COULD NOT be downloaded because an I/O error has occured. \r\n";

                        if (remoteDownload.getInputStream() != null) {
                            remoteDownload.getInputStream().close();
                        }

                        remoteDownload.releaseConnection();

                        Success = false;
                    } else {
                        in = remoteDownload.getInputStream();
                    }
                } else {
                    in = getLocalFileAsStream(file);
                    if (in == null) {
                        fileManifest = fileManifest + file.getFileName() + " (" + dbContentType
                                + ") COULD NOT be downloaded because an I/O error has occured. \r\n";

                        Success = false;
                    }
                }

                if (Success) {
                    // String zipEntryName = file.getFileName();

                    // get file name and category according to study version number chosen by user 

                    Long versionNum = null;
                    if (versionNumber != null)
                        versionNum = Long.valueOf(versionNumber).longValue();
                    String zipEntryName = file.getFileName(versionNum);

                    zipEntryName = checkZipEntryName(zipEntryName, nameList);

                    // ZipEntry e = new ZipEntry(zipEntryName);

                    String zipEntryDirectoryName = file.getCategory(versionNum);
                    ZipEntry e = new ZipEntry(zipEntryDirectoryName + "/" + zipEntryName);

                    zout.putNextEntry(e);

                    if (varHeaderLine != null) {
                        byte[] headerBuffer = varHeaderLine.getBytes();
                        zout.write(headerBuffer);
                        fileSize += (headerBuffer.length);
                    }

                    byte[] dataBuffer = new byte[8192];

                    int i = 0;
                    while ((i = in.read(dataBuffer)) > 0) {
                        zout.write(dataBuffer, 0, i);
                        fileSize += i;
                        out.flush();
                    }
                    in.close();
                    zout.closeEntry();

                    if (dbContentType == null) {
                        dbContentType = "unknown filetype;";
                    }

                    fileManifest = fileManifest + file.getFileName() + " (" + dbContentType + ") " + fileSize
                            + " bytes.\r\n";

                    if (fileSize > 0) {
                        successList.add(file.getId());
                        sizeTotal += Long.valueOf(fileSize);
                    }

                    // if this was a remote stream, let's close
                    // the connection properly:

                    if (remoteDownload != null) {
                        remoteDownload.releaseConnection();
                    }
                }
            } else {
                fileManifest = fileManifest + file.getFileName()
                        + " skipped because the total size of the download bundle exceeded the limit of "
                        + sizeLimit + " bytes.\r\n";
            }
        }

        // finally, let's create the manifest entry:

        ZipEntry e = new ZipEntry("MANIFEST.TXT");

        zout.putNextEntry(e);
        zout.write(fileManifest.getBytes());
        zout.closeEntry();

        zout.close();

        // and finally finally, we can now increment the download
        // counts on all the files successfully zipped:

        Iterator it = successList.iterator();
        while (it.hasNext()) {
            Long fid = (Long) it.next();
            StudyFile file = studyFileService.getStudyFile(new Long(fid));
            Long versionNum = null;
            if (versionNumber != null)
                versionNum = Long.valueOf(versionNumber).longValue();
            System.out.print("versionNumber " + versionNumber);
            StudyVersion sv = file.getStudy().getStudyVersionByNumber(versionNum);
            GuestBookResponse guestbookResponse = (GuestBookResponse) vdcSession.getGuestbookResponseMap()
                    .get("guestBookResponse_" + file.getStudy().getId());
            if (guestbookResponse == null) {
                //need to set up dummy network response
                guestbookResponse = guestBookResponseServiceBean.initNetworkGuestBookResponse(file.getStudy(),
                        file, vdcSession.getLoginBean());
            }
            guestbookResponse.setStudyVersion(sv);
            guestbookResponse.setSessionId(sessionId);

            String friendlyFormatType = FileUtil.getUserFriendlyTypeForMime(file.getFileType());

            guestbookResponse.setDownloadtype("File Download (as Zip archive) - " + friendlyFormatType);

            if (vdc != null) {
                studyService.incrementNumberOfDownloads(fid, vdc.getId(),
                        (GuestBookResponse) guestbookResponse);
            } else {
                studyService.incrementNumberOfDownloads(fid, (Long) null,
                        (GuestBookResponse) guestbookResponse);
            }
        }

    } catch (IOException ex) {
        // if we caught an exception *here*, it means something
        // catastrophic has happened while packaging the zip archive
        // itself (I/O errors on individual files would be caught
        // above); so there's not much we can do except print a
        // generic error message:

        String errorMessage = "An unknown I/O error has occured while generating a Zip archive of multiple data files. Unfortunately, no further diagnostic information on the nature of the problem is avaiable to the Application at this point. It is possible that the problem was caused by a temporary network error. Please try again later and if the problem persists, report it to your DVN technical support contact.";
        createErrorResponse403(res);

        if (remoteDownload != null) {
            remoteDownload.releaseConnection();
        }
    }
}

From source file:com.versatus.jwebshield.filter.SecurityTokenFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpRes = (HttpServletResponse) response;
    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);

    logger.debug("doFilter: request from IP address=" + httpReq.getRemoteAddr());

    if (httpReq.getSession(false) == null) {
        chain.doFilter(request, response);
        return;/*from   ww w  .  j  a v  a 2  s .  c om*/
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {

        logger.error("doFilter", e);
    }

    // Check the user session for the salt cache, if none is present we
    // create one
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache == null) {
        if (tokenTimeout == -1) {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000).build();
        } else {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000)
                    .expireAfterAccess(tokenTimeout, TimeUnit.SECONDS).build();
        }

        httpReq.getSession().setAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME, csrfPreventionSaltCache);

        String nameSalt = RandomStringUtils.random(10, 0, 0, true, true, null, new SecureRandom());
        httpReq.getSession().setAttribute(SecurityConstant.SALT_PARAM_NAME, nameSalt);
    }

    // Generate the salt and store it in the users cache
    String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());

    String saltNameAttr = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);
    SecurityInfo si = new SecurityInfo(saltNameAttr, salt);

    if (SecurityTokenFilter.checkReferer) {
        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
        logger.debug("doFilter: refHeader=" + refHeader);
        if (StringUtils.isNotBlank(refHeader)) {
            try {
                URL refUrl = new URL(refHeader);
                refHeader = refUrl.getHost();
            } catch (MalformedURLException mex) {
                logger.debug("doFilter: parsing referer header failed", mex);
            }
        }

        si.setRefererHost(refHeader);
    }

    logger.debug("doFilter: si=" + si.toString());

    csrfPreventionSaltCache.put(si, si);

    // Add the salt to the current request so it can be used
    // by the page rendered in this request
    httpReq.setAttribute(SecurityConstant.SALT_ATTR_NAME, si);

    // set CSRF cookie
    HttpSession session = httpReq.getSession(false);
    if (session != null && StringUtils.isNotBlank(csrfCookieName)) {

        if (logger.isDebugEnabled()) {
            Cookie[] cookies = httpReq.getCookies();
            // boolean cookiePresent = false;
            for (Cookie c : cookies) {
                String name = c.getName();
                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());
                // if (csrfCookieName.equals(name)) {
                // cookiePresent = true;
                // break;
                // }
            }
        }
        // if (!cookiePresent) {
        byte[] hashSalt = new byte[32];
        SecureRandom sr = new SecureRandom();
        sr.nextBytes(hashSalt);

        String csrfHash = RandomStringUtils.random(64, 0, 0, true, true, null, sr);

        Cookie c = new Cookie(csrfCookieName, csrfHash);
        c.setMaxAge(1800);
        c.setSecure(false);
        c.setPath(httpReq.getContextPath());
        c.setHttpOnly(false);
        httpRes.addCookie(c);
        // session.setAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM,
        // hashStr);
        // }
    }

    chain.doFilter(request, response);
}

From source file:com.egt.core.util.Utils.java

public void trace(String objeto, String metodo, String contexto) {
    System.out.println(objeto + "." + metodo + "(" + contexto + ")");
    FacesContext facesContext = FacesContext.getCurrentInstance();
    System.out.println(objeto + "." + metodo + "(" + facesContext + ")");
    if (facesContext == null) {
        return;//from w  w  w .j av a  2 s .  co  m
    }
    traceContext();
    HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
    System.out.println("request ..................... " + request);
    System.out.println("request.getAuthType ......... " + request.getAuthType());
    System.out.println("request.getUserPrincipal .... " + request.getUserPrincipal());
    Principal principal = facesContext.getExternalContext().getUserPrincipal();
    System.out.println("principal ................... " + principal);
    if (principal != null) {
        System.out.println("principal.getName ........... " + principal.getName());
        System.out.println("isSuperUsuario .............. " + request.isUserInRole("SuperUsuario"));
        System.out.println("isUsuarioEstandar ........... " + request.isUserInRole("UsuarioEstandar"));
        System.out.println("isUsuarioBasico.. ........... " + request.isUserInRole("UsuarioBasico"));
    }
    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
    HttpSession session = request.getSession(false);
    System.out.println("session ..................... " + facesContext.getExternalContext().getSession(false));
    System.out.println("session.getId ............... " + session.getId());
    String key;
    Object object;
    Set sessionKeys = facesContext.getExternalContext().getSessionMap().keySet();
    if (sessionKeys.isEmpty()) {
    } else {
        Iterator iterator = sessionKeys.iterator();
        while (iterator.hasNext()) {
            object = iterator.next();
            if (object instanceof String) {
                key = (String) object;
                object = facesContext.getExternalContext().getSessionMap().get(key);
                if (object != null) {
                    System.out.println(key + " = (" + object.getClass().getName() + ") " + object);
                }
            }
        }
    }
    System.out.println("request.getContextPath ...... " + request.getContextPath());
    System.out.println("request.getServletPath ...... " + request.getServletPath());
    System.out.println("request.getPathInfo ......... " + request.getPathInfo());
    System.out.println("request.getRequestURI ....... " + request.getRequestURI());
    System.out.println("request.getContextPathURL ... " + request.getRequestURL().toString());
    String clave;
    System.out.println("*** parametros ***");
    Iterator iterator = request.getParameterMap().keySet().iterator();
    while (iterator.hasNext()) {
        clave = (String) iterator.next();
        System.out.println(clave + " = " + request.getParameter(clave));
    }
    String cookieName;
    System.out.println("**** cookies  ****");
    Cookie cookies[] = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookieName = cookies[i].getName();
            System.out.println(cookieName + " = " + cookies[i].getValue());
        }
    }
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

public Map<String, de.innovationgate.wga.server.api.Cookie> fetchHttpCookies(
        javax.servlet.http.HttpServletRequest request) {
    Map<String, de.innovationgate.wga.server.api.Cookie> cookies = new HashMap<String, de.innovationgate.wga.server.api.Cookie>();
    Cookie[] rawCookies = request.getCookies();
    if (rawCookies != null) {
        for (javax.servlet.http.Cookie c : rawCookies) {
            cookies.put(c.getName(), new de.innovationgate.wga.server.api.Cookie(c));
        }//from w w w . j  a v  a  2  s. c  o  m
    }
    return cookies;
}

From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    try {/*  w  w w .  j a va 2  s.  c om*/
        if (!initialized.get()) {
            initializeServer(context);
        }
    } catch (Exception e) {
        context.yield();
        throw new ProcessException("Failed to initialize the server", e);
    }

    final HttpRequestContainer container = containerQueue.poll();
    if (container == null) {
        return;
    }

    final long start = System.nanoTime();
    final HttpServletRequest request = container.getRequest();
    FlowFile flowFile = session.create();
    try {
        flowFile = session.importFrom(request.getInputStream(), flowFile);
    } catch (final IOException e) {
        getLogger().error("Failed to receive content from HTTP Request from {} due to {}",
                new Object[] { request.getRemoteAddr(), e });
        session.remove(flowFile);
        return;
    }

    final String charset = request.getCharacterEncoding() == null
            ? context.getProperty(URL_CHARACTER_SET).getValue()
            : request.getCharacterEncoding();

    final String contextIdentifier = UUID.randomUUID().toString();
    final Map<String, String> attributes = new HashMap<>();
    try {
        putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier);
        putAttribute(attributes, "mime.type", request.getContentType());
        putAttribute(attributes, "http.servlet.path", request.getServletPath());
        putAttribute(attributes, "http.context.path", request.getContextPath());
        putAttribute(attributes, "http.method", request.getMethod());
        putAttribute(attributes, "http.local.addr", request.getLocalAddr());
        putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName());
        final String queryString = request.getQueryString();
        if (queryString != null) {
            putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset));
        }
        putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost());
        putAttribute(attributes, "http.remote.addr", request.getRemoteAddr());
        putAttribute(attributes, "http.remote.user", request.getRemoteUser());
        putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI());
        putAttribute(attributes, "http.request.url", request.getRequestURL().toString());
        putAttribute(attributes, "http.auth.type", request.getAuthType());

        putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId());
        final DispatcherType dispatcherType = request.getDispatcherType();
        if (dispatcherType != null) {
            putAttribute(attributes, "http.dispatcher.type", dispatcherType.name());
        }
        putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding());
        putAttribute(attributes, "http.locale", request.getLocale());
        putAttribute(attributes, "http.server.name", request.getServerName());
        putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort());

        final Enumeration<String> paramEnumeration = request.getParameterNames();
        while (paramEnumeration.hasMoreElements()) {
            final String paramName = paramEnumeration.nextElement();
            final String value = request.getParameter(paramName);
            attributes.put("http.param." + paramName, value);
        }

        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                final String name = cookie.getName();
                final String cookiePrefix = "http.cookie." + name + ".";
                attributes.put(cookiePrefix + "value", cookie.getValue());
                attributes.put(cookiePrefix + "domain", cookie.getDomain());
                attributes.put(cookiePrefix + "path", cookie.getPath());
                attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge()));
                attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion()));
                attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure()));
            }
        }

        if (queryString != null) {
            final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString);
            for (final String keyValueString : params) {
                final int indexOf = keyValueString.indexOf("=");
                if (indexOf < 0) {
                    // no =, then it's just a key with no value
                    attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), "");
                } else {
                    final String key = keyValueString.substring(0, indexOf);
                    final String value;

                    if (indexOf == keyValueString.length() - 1) {
                        value = "";
                    } else {
                        value = keyValueString.substring(indexOf + 1);
                    }

                    attributes.put("http.query.param." + URLDecoder.decode(key, charset),
                            URLDecoder.decode(value, charset));
                }
            }
        }
    } catch (final UnsupportedEncodingException uee) {
        throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated
    }

    final Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        final String headerValue = request.getHeader(headerName);
        putAttribute(attributes, "http.headers." + headerName, headerValue);
    }

    final Principal principal = request.getUserPrincipal();
    if (principal != null) {
        putAttribute(attributes, "http.principal.name", principal.getName());
    }

    final X509Certificate certs[] = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    final String subjectDn;
    if (certs != null && certs.length > 0) {
        final X509Certificate cert = certs[0];
        subjectDn = cert.getSubjectDN().getName();
        final String issuerDn = cert.getIssuerDN().getName();

        putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn);
        putAttribute(attributes, "http.issuer.dn", issuerDn);
    } else {
        subjectDn = null;
    }

    flowFile = session.putAllAttributes(flowFile, attributes);

    final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP)
            .asControllerService(HttpContextMap.class);
    final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(),
            container.getContext());

    if (!registered) {
        getLogger().warn(
                "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE",
                new Object[] { request.getRemoteAddr() });

        try {
            container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
            container.getResponse().flushBuffer();
            container.getContext().complete();
        } catch (final Exception e) {
            getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}",
                    new Object[] { request.getRemoteAddr(), e });
        }

        session.remove(flowFile);
        return;
    }

    final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
    session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes),
            "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn),
            receiveMillis);
    session.transfer(flowFile, REL_SUCCESS);
    getLogger().info("Transferring {} to 'success'; received from {}",
            new Object[] { flowFile, request.getRemoteAddr() });
}