Example usage for javax.servlet.http Cookie getValue

List of usage examples for javax.servlet.http Cookie getValue

Introduction

In this page you can find the example usage for javax.servlet.http Cookie getValue.

Prototype

public String getValue() 

Source Link

Document

Gets the current value of this Cookie.

Usage

From source file:memedb.httpd.MemeDBHandler.java

protected Credentials getCredentials(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    Credentials cred = null;//from ww w. j a  v  a2 s . c  o m

    if (request.getRequestURI().equals("/_auth")) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        log.debug("login attempt for {}", username);
        if (!allowAnonymous && "anonymous".equals(username)) {
            sendNoAuthError(response, "Bad username / password combination");
            return null;
        }
        if (username != null) {
            if (password == null) {
                password = "";
            }
            if (allowAnonymous && allowAnonymousAsSa && "anonymous".equals(username)) {
                return new SACredentials("anonymous", "", timeout);
            }
            cred = memeDB.getAuthentication().authenticate(username, password);
            if (cred != null) {
                if (request.getParameter("setcookie") == null
                        || request.getParameter("setcookie").toLowerCase().equals("false")) {
                    Cookie cookie = new Cookie(COOKIE_ID, cred.getToken());
                    cookie.setMaxAge(timeout);
                    response.addCookie(cookie);
                }
                return cred;
            } else {
                log.warn("Bad login attempt for {}", username);
                sendNoAuthError(response, "Bad username / password combination");
                return null;
            }
        }
    }

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(COOKIE_ID)) {
                cred = memeDB.getAuthentication().getCredentialsFromToken(cookie.getValue());
                if (cred != null) {
                    log.debug("Got credentials from cookie token: {}", cookie.getValue());
                    return cred;
                }
            }
        }
    }

    String param = request.getParameter("token");
    if (param != null && !param.equals("")) {
        cred = memeDB.getAuthentication().getCredentialsFromToken(param);
        if (cred != null) {
            log.debug("Authenticated as {} => {} via Req param", cred.getUsername(), cred.getToken());
            addCredentialedCookie(response, cred);
            return cred;
        }
    }

    String headerparam = request.getHeader("MemeDB-Token");
    if (headerparam != null && !headerparam.equals("")) {
        log.info("Attempting authentication with token {}", headerparam);
        cred = memeDB.getAuthentication().getCredentialsFromToken(headerparam);
        if (cred != null) {
            log.info("Got credentials!");
            log.debug("Authenticated as {} => {} via HTTP-Header", cred.getUsername(), cred.getToken());
            addCredentialedCookie(response, cred);
            return cred;
        }
    }

    String authHeader = request.getHeader("Authorization");
    if (authHeader != null) {
        String[] authSplit = authHeader.split(" ");
        if (authSplit.length == 2) {
            String userpass = new String(Base64.decodeBase64(authSplit[1].getBytes()));
            if (userpass != null) {
                String[] ar = userpass.split(":");
                if (ar.length > 0) {
                    String u = ar[0];
                    String p = "";
                    if (ar.length > 1) {
                        p = ar[1];
                    }
                    if (!allowAnonymous && "anonymous".equals(u)) {
                    } else {
                        cred = memeDB.getAuthentication().authenticate(u, p);

                        if (cred != null) {
                            log.debug("Authenticated as {} => {} via HTTP-AUTH", cred.getUsername(),
                                    cred.getToken());
                            addCredentialedCookie(response, cred);
                        }
                        return cred;
                    }
                }
            }
        }
        response.addHeader("WWW-Authenticate", " Basic realm=\"" + realm + "\"");
        sendNoAuthError(response, "You need a username and password");
        return null;
    }

    if (allowAnonymous) {
        if (allowAnonymousAsSa)
            return new SACredentials("anonymous", "", timeout);
        return new AnonCredentials("", timeout);
    }

    log.warn("Error authenticating");
    response.addHeader("WWW-Authenticate", " Basic realm=\"" + realm + "\"");
    sendNoAuthError(response, "You need a username and password");
    return null;
}

From source file:com.jfinal.core.Controller.java

private Locale getLocaleFromCookie() {
    Cookie cookie = getCookieObject(I18N_LOCALE);
    if (cookie != null) {
        return I18N.localeFromString(cookie.getValue());
    } else {//from  w w  w .j  av a 2  s.c o m
        Locale defaultLocale = I18N.getDefaultLocale();
        setLocaleToCookie(defaultLocale);
        return I18N.localeFromString(defaultLocale.toString());
    }
}

From source file:com.google.gsa.valve.rootAuth.RootAuthorizationProcess.java

/**
 * It manages session and checks the session (if it exists) is still valid.
 * // ww w.ja v  a 2  s .c o  m
 * @param gsaAuthCookie authentication cookie
 * 
 * @return the user session if it exists, null otherwise
 * 
 * @throws nonValidSessionException
 */
public UserSession manageSessions(Cookie gsaAuthCookie) throws nonValidSessionException {

    UserSession userSession = null;

    logger.debug("ManageSessions method. Check if Session is enabled [" + isSessionEnabled + "]");

    if (isSessionEnabled) {

        //check if the session is active
        logger.debug("The session is enabled");

        String userID = null;
        try {
            userID = URLDecoder.decode(gsaAuthCookie.getValue(), ENCODING);
        } catch (UnsupportedEncodingException e) {
            logger.error("Error during decoding Auth Cookie: " + e.getMessage(), e);
            userID = gsaAuthCookie.getValue();
        }

        logger.debug("the userID has been read: " + userID);

        boolean isSessionInvalid = sessions.isSessionInvalid(userID);
        logger.debug("Session invalidity checked: " + isSessionInvalid);
        if (isSessionInvalid) {
            //protect this code
            synchronized (sessions) {
                logger.debug("the session is invalid");
                boolean doesSessionStillExist = sessions.doesSessionExist(userID);
                logger.debug("Session still exists: " + doesSessionStillExist);
                if (doesSessionStillExist) {
                    logger.debug("the session does exists: let's delete it");
                    //delete Session
                    sessions.deleteSession(userID);
                }

                logger.debug("Setting session invalidity");
                throw new nonValidSessionException("The session is invalid. It does not longer exists");
            }

        } //end session invalid

        //look for the existing session
        userSession = sessions.getUserSession(userID);
        if (userSession == null) {

            logger.error("User Session is not valid");
            throw new nonValidSessionException("The session does not exists");

        } else {
            if (isSessionEnabled) {
                //update the last access
                int sessionTimeout = new Integer(valveConf.getSessionConfig().getSessionTimeout()).intValue();
                if (sessionTimeout >= 0) {
                    long lastAccessTime = getCurrentTime();
                    if (lastAccessTime > 0) {
                        logger.debug("New access time: " + lastAccessTime);
                        userSession.setSessionLastAccessTime(lastAccessTime);
                        sessions.addSession(userID, userSession);
                    }
                }
            }
        }

    }

    return userSession;
}

From source file:mfi.filejuggler.responsibles.BasicApplication.java

@Responsible(conditions = { Condition.SYS_SYSTEM_INFO, Condition.SYS_EXECUTE_JOB })
public void fjSystemInfo(StringBuilder sb, Map<String, String> parameters, Model model) throws Exception {

    if (model.lookupConversation().getCondition().equals(Condition.SYS_EXECUTE_JOB)) {
        String executeJob = StringUtils.trimToEmpty(parameters.get("execute_job"));
        for (String schedulerName : CronSchedulers.getInstance().getSchedulersIDs().keySet()) {
            if (StringUtils.equalsIgnoreCase(schedulerName, executeJob)) {
                Runnable r = CronSchedulers.getInstance().getSchedulersInstances().get(schedulerName);
                r.run();/*from  w w w  .  ja v a  2s.  co  m*/
                model.lookupConversation().getMeldungen().add(r.getClass().getName() + " wurde gestartet");
                break;
            }
        }
    }

    String warfilename = KVMemoryMap.getInstance().readValueFromKey("application.warfile");
    String builddate = KVMemoryMap.getInstance().readValueFromKey("application.builddate");
    if (warfilename == null) {
        warfilename = "Development Version";
    }
    if (builddate == null) {
        builddate = "n/v";
    }

    ButtonBar buttonBar = new ButtonBar();
    buttonBar.getButtons().add(new Button("Reload", Condition.SYS_SYSTEM_INFO));
    sb.append(HTMLUtils.buildMenuNar(model, "Systeminformationen", Condition.FS_NAVIGATE, buttonBar, false));

    String attributeLeftCol = model.isPhone() ? HTMLUtils.buildAttribute("width", "40%") : null;

    HTMLTable table = new HTMLTable();

    table.addTD("Anwendungsvariablen:", 2, HTMLTable.TABLE_HEADER);
    table.addNewRow();
    table.addTD("Build:", 1, null);
    table.addTD(builddate, 1, null);
    table.addNewRow();
    table.addTD("Systemzeit:", 1, null);
    table.addTD(Hilfsklasse.zeitstempelAlsString(), 1, null);
    table.addNewRow();
    table.addTD("Zwischenablage:", 1, attributeLeftCol);
    String clip;
    if (model.getZwischenablage() != null) {
        clip = HTMLUtils.spacifyFilePath(model.getZwischenablage(), model);
    } else {
        clip = "[ leer ]";
    }
    table.addTD(clip, 1, null);
    table.addNewRow();
    table.addTD("Session:", 1, null);
    table.addTD(StringHelper.langenStringFuerAnzeigeAufbereiten(model.getSessionID()), 1, null);
    table.addNewRow();
    table.addTD("Login:", 1, null);
    table.addTD(StringHelper.langenStringFuerAnzeigeAufbereiten(model.getLoginCookieID()), 1, null);
    table.addNewRow();
    if (model.lookupConversation().getCookiesReadFromRequest() != null && model.isDevelopmentMode()) {
        for (Cookie cookieReadFromRequest : model.lookupConversation().getCookiesReadFromRequest()) {
            String cookieName = cookieReadFromRequest.getName();
            String cookieValue = cookieReadFromRequest.getValue();
            table.addTD("Cookie (Request):", 1, null);
            table.addTD(cookieName, 1, null);
            table.addNewRow();
            table.addTD("", 1, null);
            table.addTD(StringHelper.langenStringFuerAnzeigeAufbereiten(cookieValue), 1, null);
            table.addNewRow();
        }
    }
    table.addTD("Conversation ID:", 1, null);
    table.addTD(model.lookupConversation().getConversationID().toString(), 1, null);
    table.addNewRow();
    table.addTD("Remote IP:", 1, null);
    table.addTD(parameters.get(ServletHelper.SERVLET_REMOTE_IP), 1, null);
    table.addNewRow();
    table.addTD("LocalNetwork:", 1, null);
    table.addTD(ServletHelper.isLocalNetworkClient(parameters) + "", 1, null);
    table.addNewRow();
    table.addTD("Touch / Phone / Tablet:", 1, null);
    table.addTD(Boolean.toString(model.isClientTouchDevice()) + " / " + Boolean.toString(model.isPhone())
            + " / " + Boolean.toString(model.isTablet()), 1, null);
    table.addNewRow();
    table.addTD("Ist FullScreen:", 1, null);
    table.addTD(Boolean.toString(model.isIstWebApp()), 1, null);
    table.addNewRow();
    table.addTD("Ajax / current request:", 1, null);
    table.addTD(Boolean.toString(ServletHelper.lookupUseAjax()) + " / "
            + ServletHelper.lookupIsCurrentRequestTypeAjax(parameters), 1, null);
    table.addNewRow();
    table.addTD("Gzip Response:", 1, null);
    table.addTD(Boolean.toString(ServletHelper.lookupUseGzip(parameters)), 1, null);
    table.addNewRow();

    if (model.isPhone()) {
        sb.append(table.buildTable(model));
        table = new HTMLTable();
    }

    table.addTD("Java", 2, HTMLTable.TABLE_HEADER);
    table.addNewRow();
    table.addTD("total / max memory:", 1, attributeLeftCol);
    table.addTD(DateiZugriff.speicherGroesseFormatieren(Runtime.getRuntime().totalMemory()) + " / "
            + DateiZugriff.speicherGroesseFormatieren(Runtime.getRuntime().maxMemory()), 1, null);
    table.addNewRow();
    table.addTD("freeMemory:", 1, null);
    table.addTD(DateiZugriff.speicherGroesseFormatieren(Runtime.getRuntime().freeMemory()), 1, null);
    table.addNewRow();
    table.addTD("catalina.home:", 1, null);
    table.addTD(
            HTMLUtils.spacifyFilePath(
                    System.getProperties().getProperty(ServletHelper.SYSTEM_PROPERTY_CATALINA_HOME), model),
            1, null);
    table.addNewRow();
    table.addTD("catalina.base:", 1, null);
    table.addTD(
            HTMLUtils.spacifyFilePath(
                    System.getProperties().getProperty(ServletHelper.SYSTEM_PROPERTY_CATALINA_BASE), model),
            1, null);
    table.addNewRow();
    table.addTD("WarFile:", 1, HTMLTable.NO_BORDER);
    table.addTD(HTMLUtils.spacifyFilePath(warfilename, model), 1, HTMLTable.NO_BORDER);
    table.addNewRow();

    if (model.isPhone()) {
        sb.append(table.buildTable(model));
        table = new HTMLTable();
    }

    table.addTD("Hardware / Software", 2, HTMLTable.TABLE_HEADER);
    table.addNewRow();
    table.addTD("CPU Cores:", 1, attributeLeftCol);
    table.addTD(Runtime.getRuntime().availableProcessors() + "", 1, null);
    table.addNewRow();
    table.addTD("Architecture:", 1, null);
    table.addTD(System.getProperty("sun.arch.data.model", "") + " bit", 1, null);
    table.addNewRow();
    table.addTD("Java Version:", 1, null);
    table.addTD(System.getProperty("java.version", ""), 1, null);
    table.addNewRow();
    table.addTD("Java VM:", 1, null);
    table.addTD(System.getProperty("java.vm.name", ""), 1, null);
    table.addNewRow();
    table.addTD("Server:", 1, null);
    table.addTD(KVMemoryMap.getInstance().readValueFromKey("application.server"), 1, null);
    table.addNewRow();

    if (model.isPhone()) {
        sb.append(table.buildTable(model));
        table = new HTMLTable();
    }

    table.addTD("Cron Jobs", 2, HTMLTable.TABLE_HEADER);
    table.addNewRow();

    int a = 0;
    List<String> jobs = new LinkedList<String>();
    jobs.add("");
    for (String schedulerName : CronSchedulers.getInstance().getSchedulersIDs().keySet()) {
        jobs.add(schedulerName);
        String cssClass = a % 2 != 0 ? attributeLeftCol : HTMLUtils.buildAttribute("class", "alt");
        Scheduler s = CronSchedulers.getInstance().getSchedulers().get(schedulerName);
        table.addTD(schedulerName, 1, cssClass);
        table.addTD(((s != null && s.isStarted()) ? "@ " : "not running")
                + CronSchedulers.getInstance().lookupCronStringOfScheduler(schedulerName), 1, cssClass);
        table.addNewRow();
        table.addTD("", 1, cssClass);
        table.addTD(CronSchedulers.getInstance().getSchedulersInstances().get(schedulerName).status(), 1,
                cssClass);
        table.addNewRow();
        a++;
    }

    if (model.isPhone()) {
        sb.append(table.buildTable(model));
        table = new HTMLTable();
    }

    table.addTD("Manueller Job-Start", 2, HTMLTable.TABLE_HEADER);
    table.addNewRow();
    table.addTDSource(HTMLUtils.buildDropDownListe("execute_job", jobs, null), 2, null);
    table.addNewRow();
    String buttonJobStart = new Button("Job starten", Condition.SYS_EXECUTE_JOB).printForUseInTable();
    table.addTDSource(buttonJobStart, 2, HTMLTable.NO_BORDER);
    table.addNewRow();

    sb.append(table.buildTable(model));
    return;
}

From source file:com.liferay.lms.servlet.SCORMFileServerServlet.java

/**
 * Procesa los metodos HTTP GET y POST.<br>
 * Busca en la ruta que se le ha pedido el comienzo del directorio
 * "contenidos" y sirve el fichero.//from w  w  w.j av  a  2s.  c om
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws ServletException, java.io.IOException {
    String mime_type;
    String charset;
    String patharchivo;
    String uri;

    try {
        User user = PortalUtil.getUser(request);

        if (user == null) {
            String userId = null;
            String companyId = null;
            Cookie[] cookies = ((HttpServletRequest) request).getCookies();
            if (Validator.isNotNull(cookies)) {
                for (Cookie c : cookies) {
                    if ("COMPANY_ID".equals(c.getName())) {
                        companyId = c.getValue();
                    } else if ("ID".equals(c.getName())) {
                        userId = hexStringToStringByAscii(c.getValue());
                    }
                }
            }

            if (userId != null && companyId != null) {
                try {
                    Company company = CompanyLocalServiceUtil.getCompany(Long.parseLong(companyId));
                    Key key = company.getKeyObj();

                    String userIdPlain = Encryptor.decrypt(key, userId);

                    user = UserLocalServiceUtil.getUser(Long.valueOf(userIdPlain));

                    // Now you can set the liferayUser into a thread local
                    // for later use or
                    // something like that.

                } catch (Exception pException) {
                    throw new RuntimeException(pException);
                }
            }
        }

        String rutaDatos = SCORMContentLocalServiceUtil.getBaseDir();

        // Se comprueba que el usuario tiene permisos para acceder.
        // Damos acceso a todo el mundo al directorio "personalizacion",
        // para permitir mostrar a todos la pantalla de identificacion.
        uri = URLDecoder.decode(request.getRequestURI(), "UTF-8");
        uri = uri.substring(uri.indexOf("scorm/") + "scorm/".length());
        patharchivo = rutaDatos + "/" + uri;

        String[] params = uri.split("/");
        long groupId = GetterUtil.getLong(params[1]);
        String uuid = params[2];
        SCORMContent scormContent = SCORMContentLocalServiceUtil.getSCORMContentByUuidAndGroupId(uuid, groupId);

        boolean allowed = false;
        if (user == null) {
            user = UserLocalServiceUtil.getDefaultUser(PortalUtil.getDefaultCompanyId());
        }
        PermissionChecker pc = PermissionCheckerFactoryUtil.create(user);
        allowed = pc.hasPermission(groupId, SCORMContent.class.getName(), scormContent.getScormId(),
                ActionKeys.VIEW);
        if (!allowed) {
            AssetEntry scormAsset = AssetEntryLocalServiceUtil.getEntry(SCORMContent.class.getName(),
                    scormContent.getPrimaryKey());
            long scormAssetId = scormAsset.getEntryId();
            int typeId = new Long((new SCORMLearningActivityType()).getTypeId()).intValue();
            long[] groupIds = user.getGroupIds();
            for (long gId : groupIds) {
                List<LearningActivity> acts = LearningActivityLocalServiceUtil
                        .getLearningActivitiesOfGroupAndType(gId, typeId);
                for (LearningActivity act : acts) {
                    String entryId = LearningActivityLocalServiceUtil.getExtraContentValue(act.getActId(),
                            "assetEntry");
                    if (Validator.isNotNull(entryId) && Long.valueOf(entryId) == scormAssetId) {
                        allowed = pc.hasPermission(gId, LearningActivity.class.getName(), act.getActId(),
                                ActionKeys.VIEW);
                        if (allowed) {
                            break;
                        }
                    }
                }
                if (allowed) {
                    break;
                }
            }

        }
        if (allowed) {

            File archivo = new File(patharchivo);

            // Si el archivo existe y no es un directorio se sirve. Si no,
            // no se hace nada.
            if (archivo.exists() && archivo.isFile()) {

                // El content type siempre antes del printwriter
                mime_type = MimeTypesUtil.getContentType(archivo);
                charset = "";
                if (archivo.getName().toLowerCase().endsWith(".html")
                        || archivo.getName().toLowerCase().endsWith(".htm")) {
                    mime_type = "text/html";
                    if (isISO(FileUtils.readFileToString(archivo))) {
                        charset = "ISO-8859-1";
                    }
                }
                if (archivo.getName().toLowerCase().endsWith(".swf")) {
                    mime_type = "application/x-shockwave-flash";
                }
                if (archivo.getName().toLowerCase().endsWith(".mp4")) {
                    mime_type = "video/mp4";
                }
                if (archivo.getName().toLowerCase().endsWith(".flv")) {
                    mime_type = "video/x-flv";
                }
                response.setContentType(mime_type);
                if (Validator.isNotNull(charset)) {
                    response.setCharacterEncoding(charset);

                }
                response.addHeader("Content-Type",
                        mime_type + (Validator.isNotNull(charset) ? "; " + charset : ""));
                /*if (archivo.getName().toLowerCase().endsWith(".swf")
                      || archivo.getName().toLowerCase().endsWith(".flv")) {
                   response.addHeader("Content-Length",
                String.valueOf(archivo.length()));
                }
                */
                if (archivo.getName().toLowerCase().endsWith("imsmanifest.xml")) {
                    FileInputStream fis = new FileInputStream(patharchivo);

                    String sco = ParamUtil.get(request, "scoshow", "");
                    Document manifest = SAXReaderUtil.read(fis);
                    if (sco.length() > 0) {

                        Element organizatEl = manifest.getRootElement().element("organizations")
                                .element("organization");
                        Element selectedItem = selectItem(organizatEl, sco);
                        if (selectedItem != null) {
                            selectedItem.detach();
                            java.util.List<Element> items = organizatEl.elements("item");
                            for (Element item : items) {

                                organizatEl.remove(item);
                            }
                            organizatEl.add(selectedItem);
                        }
                    }
                    //clean unused resources.
                    Element resources = manifest.getRootElement().element("resources");
                    java.util.List<Element> theResources = resources.elements("resource");
                    Element organizatEl = manifest.getRootElement().element("organizations")
                            .element("organization");
                    java.util.List<String> identifiers = getIdentifierRefs(organizatEl);
                    for (Element resource : theResources) {
                        String identifier = resource.attributeValue("identifier");
                        if (!identifiers.contains(identifier)) {
                            resources.remove(resource);
                        }
                    }
                    response.getWriter().print(manifest.asXML());
                    fis.close();
                    return;

                }

                if (mime_type.startsWith("text") || mime_type.endsWith("javascript")
                        || mime_type.equals("application/xml")) {

                    java.io.OutputStream out = response.getOutputStream();
                    FileInputStream fis = new FileInputStream(patharchivo);

                    byte[] buffer = new byte[512];
                    int i = 0;

                    while (fis.available() > 0) {
                        i = fis.read(buffer);
                        if (i == 512)
                            out.write(buffer);
                        else
                            out.write(buffer, 0, i);

                    }

                    fis.close();
                    out.flush();
                    out.close();
                    return;
                }
                //If not manifest
                String fileName = archivo.getName();
                long length = archivo.length();
                long lastModified = archivo.lastModified();
                String eTag = fileName + "_" + length + "_" + lastModified;
                long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME;
                String ifNoneMatch = request.getHeader("If-None-Match");
                if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("ETag", eTag); // Required in 304.
                    response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
                    return;
                }
                long ifModifiedSince = request.getDateHeader("If-Modified-Since");
                if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("ETag", eTag); // Required in 304.
                    response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
                    return;
                }

                // If-Match header should contain "*" or ETag. If not, then return 412.
                String ifMatch = request.getHeader("If-Match");
                if (ifMatch != null && !matches(ifMatch, eTag)) {
                    response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                    return;
                }

                // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
                long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
                if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
                    response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                    return;
                }

                // Validate and process range -------------------------------------------------------------

                // Prepare some variables. The full Range represents the complete file.
                Range full = new Range(0, length - 1, length);
                List<Range> ranges = new ArrayList<Range>();

                // Validate and process Range and If-Range headers.
                String range = request.getHeader("Range");
                if (range != null) {

                    // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
                    if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
                        response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                        return;
                    }

                    // If-Range header should either match ETag or be greater then LastModified. If not,
                    // then return full file.
                    String ifRange = request.getHeader("If-Range");
                    if (ifRange != null && !ifRange.equals(eTag)) {
                        try {
                            long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                            if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                                ranges.add(full);
                            }
                        } catch (IllegalArgumentException ignore) {
                            ranges.add(full);
                        }
                    }

                    // If any valid If-Range header, then process each part of byte range.
                    if (ranges.isEmpty()) {
                        for (String part : range.substring(6).split(",")) {
                            // Assuming a file with length of 100, the following examples returns bytes at:
                            // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
                            long start = sublong(part, 0, part.indexOf("-"));
                            long end = sublong(part, part.indexOf("-") + 1, part.length());

                            if (start == -1) {
                                start = length - end;
                                end = length - 1;
                            } else if (end == -1 || end > length - 1) {
                                end = length - 1;
                            }

                            // Check if Range is syntactically valid. If not, then return 416.
                            if (start > end) {
                                response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                                return;
                            }

                            // Add range.
                            ranges.add(new Range(start, end, length));
                        }
                    }
                }
                boolean acceptsGzip = false;
                String disposition = "inline";

                if (mime_type.startsWith("text")) {
                    //String acceptEncoding = request.getHeader("Accept-Encoding");
                    // acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
                    // mime_type += ";charset=UTF-8";
                }

                // Else, expect for images, determine content disposition. If content type is supported by
                // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
                else if (!mime_type.startsWith("image")) {
                    String accept = request.getHeader("Accept");
                    disposition = accept != null && accepts(accept, mime_type) ? "inline" : "attachment";
                }

                // Initialize response.
                response.reset();
                response.setBufferSize(DEFAULT_BUFFER_SIZE);
                response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
                response.setHeader("Accept-Ranges", "bytes");
                response.setHeader("ETag", eTag);
                response.setDateHeader("Last-Modified", lastModified);
                response.setDateHeader("Expires", expires);

                // Send requested file (part(s)) to client ------------------------------------------------

                // Prepare streams.
                RandomAccessFile input = null;
                OutputStream output = null;

                try {
                    // Open streams.
                    input = new RandomAccessFile(archivo, "r");
                    output = response.getOutputStream();

                    if (ranges.isEmpty() || ranges.get(0) == full) {

                        // Return full file.
                        Range r = full;
                        response.setContentType(mime_type);
                        response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

                        if (content) {

                            // Content length is not directly predictable in case of GZIP.
                            // So only add it if there is no means of GZIP, else browser will hang.
                            response.setHeader("Content-Length", String.valueOf(r.length));

                            // Copy full range.
                            copy(input, output, r.start, r.length);
                        }

                    } else if (ranges.size() == 1) {

                        // Return single part of file.
                        Range r = ranges.get(0);
                        response.setContentType(mime_type);
                        response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
                        response.setHeader("Content-Length", String.valueOf(r.length));
                        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

                        if (content) {
                            // Copy single part range.
                            copy(input, output, r.start, r.length);
                        }

                    } else {

                        // Return multiple parts of file.
                        response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
                        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

                        if (content) {
                            // Cast back to ServletOutputStream to get the easy println methods.
                            ServletOutputStream sos = (ServletOutputStream) output;

                            // Copy multi part range.
                            for (Range r : ranges) {
                                // Add multipart boundary and header fields for every range.
                                sos.println();
                                sos.println("--" + MULTIPART_BOUNDARY);
                                sos.println("Content-Type: " + mime_type);
                                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                                // Copy single part range of multi part range.
                                copy(input, output, r.start, r.length);
                            }

                            // End with multipart boundary.
                            sos.println();
                            sos.println("--" + MULTIPART_BOUNDARY + "--");
                        }
                    }
                } finally {
                    // Gently close streams.
                    close(output);
                    close(input);
                }
            } else {
                //java.io.OutputStream out = response.getOutputStream();
                response.sendError(404);
                //out.write(uri.getBytes());
            }
        } else {
            response.sendError(401);
        }
    } catch (Exception e) {
        System.out.println("Error en el processRequest() de ServidorArchivos: " + e.getMessage());
    }
}

From source file:com.mmj.app.web.controller.manage.ManageController.java

/**
 * Cookie?????/*from  w ww. j  a v a 2 s.co m*/
 * 
 * @param request
 * @return
 */
private List<String> getShowMenuBar(HttpServletRequest request) {
    Cookie cookies[] = request.getCookies();
    Cookie sCookie = null;
    String svalue = null;
    String sname = null;
    for (int i = 0; i < cookies.length; i++) {
        sCookie = cookies[i];
        sname = sCookie.getName();
        if ("menuConfig".equals(sname)) {
            svalue = sCookie.getValue();
            if (svalue != null) {
                return Arrays.asList(svalue.split("-_-"));
            }
            return Collections.<String>emptyList();
        }
    }
    return Collections.<String>emptyList();
}

From source file:com.netspective.sparx.form.DialogContext.java

public String getClientPersistentValue(DialogField field) {
    if (cookieValues == null) {
        cookieValues = new HashMap();
        final Cookie[] cookies = getHttpRequest().getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                final Cookie cookie = cookies[i];
                final String cookieName = getDialog().getCookieName();
                if (cookie.getName().equals(cookieName)) {
                    try {
                        UrlQueryStringParser parser = new UrlQueryStringParser(
                                new ByteArrayInputStream(cookie.getValue().getBytes()));
                        cookieValues = parser.parseArgs();
                    } catch (IOException e) {
                        getDialog().getLog().error(e);
                    }/*  w w w  .ja  va2s.com*/
                }
            }
        }
    }

    if (cookieValues != null)
        return (String) cookieValues.get(field.getQualifiedName());
    else
        return null;
}

From source file:com.tremolosecurity.proxy.filter.PostProcess.java

protected void setHeadersCookies(HttpFilterRequest req, UrlHolder holder, HttpRequestBase method,
        String finalURL) throws Exception {
    Iterator<String> names;
    names = req.getHeaderNames();//from  w w  w  .  j  a va 2  s .  c  o m
    String cookieName = null;
    URL url = new URL(finalURL);

    while (names.hasNext()) {
        String name = names.next();
        if (name.equalsIgnoreCase("Cookie")) {
            cookieName = name;
            continue;
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Header : " + name);
        }

        Attribute attrib = req.getHeader(name);
        Iterator<String> attrVals = attrib.getValues().iterator();
        while (attrVals.hasNext()) {
            String val = attrVals.next();

            if (name.equalsIgnoreCase("Content-Type")) {
                continue;
            } else if (name.equalsIgnoreCase("If-Range")) {
                continue;
            } else if (name.equalsIgnoreCase("Range")) {
                continue;
            } else if (name.equalsIgnoreCase("If-None-Match")) {
                continue;
            }

            if (name.equalsIgnoreCase("HOST")) {

                if (holder.isOverrideHost()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Final URL : '" + finalURL + "'");
                    }

                    val = url.getHost();
                    if (url.getPort() != -1) {
                        StringBuffer b = new StringBuffer();
                        b.append(val).append(":").append(url.getPort());
                        val = b.toString();
                    }
                }
            } else if (name.equalsIgnoreCase("Referer")) {

                if (holder.isOverrideReferer()) {
                    URL origRef = new URL(val);
                    StringBuffer newRef = new StringBuffer();

                    newRef.append(url.getProtocol()).append("://").append(url.getHost());

                    if (url.getPort() != -1) {
                        newRef.append(':').append(url.getPort());
                    }

                    newRef.append(origRef.getPath());

                    if (origRef.getQuery() != null) {
                        newRef.append('?').append(origRef.getQuery());
                    }

                    if (logger.isDebugEnabled()) {
                        logger.debug("Final Ref : '" + newRef.toString() + "'");
                    }

                    val = newRef.toString();

                }

            }

            if (this.addHeader(name)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Header Added - '" + name + "'='" + val + "'");
                }
                method.addHeader(new BasicHeader(attrib.getName(), val));
            }
        }
    }

    HashMap<String, Attribute> fromResults = (HashMap<String, Attribute>) req
            .getAttribute(AzSys.AUTO_IDM_HTTP_HEADERS);
    if (fromResults != null) {
        names = fromResults.keySet().iterator();

        while (names.hasNext()) {
            String name = names.next();
            method.removeHeaders(name);

            Attribute attrib = fromResults.get(name);
            Iterator<String> attrVals = attrib.getValues().iterator();
            while (attrVals.hasNext()) {
                String val = attrVals.next();
                if (logger.isDebugEnabled()) {
                    logger.debug("Header Added - '" + name + "'='" + val + "'");
                }
                method.addHeader(new BasicHeader(name, val));
            }
        }
    }

    String sessionCookieName = "";

    if (holder.getApp().getCookieConfig() != null) {
        sessionCookieName = holder.getApp().getCookieConfig().getSessionCookieName();
    }

    HashSet<String> toRemove = new HashSet<String>();
    toRemove.add(sessionCookieName);
    toRemove.add("autoIdmSessionCookieName");
    toRemove.add("autoIdmAppName");
    toRemove.add("JSESSIONID");

    names = req.getCookieNames().iterator();
    StringBuffer cookieHeader = new StringBuffer();
    boolean isFirst = true;

    while (names.hasNext()) {
        String name = names.next();

        if (toRemove.contains(name)) {
            continue;
        }

        ArrayList<Cookie> cookies = req.getCookies(name);

        Iterator<Cookie> itc = cookies.iterator();
        while (itc.hasNext()) {
            Cookie cookie = itc.next();
            String cookieFinalName;
            if (cookie.getName().startsWith("JSESSIONID")) {
                String host = cookie.getName().substring(cookie.getName().indexOf('-') + 1);
                host = host.replaceAll("[|]", " ");
                if (!holder.getApp().getName().equalsIgnoreCase(host)) {
                    continue;
                }

                cookieFinalName = "JSESSIONID";
            } else {
                cookieFinalName = cookie.getName();
            }

            String val = cookie.getValue();
            if (logger.isDebugEnabled()) {
                logger.debug("Cookie Added - '" + name + "'='" + val + "'");
            }

            cookieHeader.append(cookieFinalName).append('=').append(val).append("; ");
        }
    }

    if (cookieHeader.length() > 0) {
        if (cookieName == null) {
            cookieName = "Cookie";
        }

        method.addHeader(new BasicHeader(cookieName, cookieHeader.toString()));
    }
}

From source file:com.novartis.opensource.yada.QueryManager.java

/**
 * Populates the data and parameter storage in the query object, using values passed in request object
 * @since 4.0.0//from w  ww .  j a va 2s .  com
 * @param yq
 *          the query object to be processed
 * @return {@code yq}, now endowed with metadata
 * @throws YADAFinderException
 *           when the name of the query in {@code yq} can't be found in the
 *           YADA index
 * @throws YADAQueryConfigurationException
 *           the the YADA request is malformed
 * @throws YADAUnsupportedAdaptorException when the adaptor attached to the query object can't be found or instantiated
 * @throws YADAResourceException when the query {@code q} can't be found in the index
 * @throws YADAConnectionException when a connection pool or string cannot be established
 */
YADAQuery endowQuery(YADAQuery yq) throws YADAQueryConfigurationException, YADAResourceException,
        YADAUnsupportedAdaptorException, YADAConnectionException {
    int index = 0;
    if (getJsonParams() != null)
        index = ArrayUtils.indexOf(getJsonParams().getKeys(), yq.getQname());
    yq.addRequestParams(this.yadaReq.getRequestParamsForQueries(), index);
    yq.setAdaptorClass(this.qutils.getAdaptorClass(yq.getApp()));
    if (RESTAdaptor.class.equals(yq.getAdaptorClass()) && this.yadaReq.hasCookies()) {
        for (String cookieName : this.yadaReq.getCookies()) {
            for (Cookie cookie : this.yadaReq.getRequest().getCookies()) {
                if (cookie.getName().equals(cookieName)) {
                    yq.addCookie(cookieName,
                            Base64.encodeBase64String(Base64.decodeBase64(cookie.getValue().getBytes())));
                }
            }
        }
    }

    //TODO handle missing params exceptions here, throw YADARequestException
    //TODO review instances where YADAQueryConfigurationException is thrown
    this.qutils.setProtocol(yq);
    yq.setAdaptor(this.qutils.getAdaptor(yq.getAdaptorClass(), this.yadaReq));
    yq.setConformedCode(this.qutils.getConformedCode(yq.getYADACode()));
    for (int row = 0; row < yq.getData().size(); row++) {
        // TODO perhaps move this functionality to the deparsing step? 
        yq.addDataTypes(row, this.qutils.getDataTypes(yq.getYADACode()));
        int paramCount = yq.getDataTypes().get(0).length;
        yq.addParamCount(row, paramCount);
    }
    return yq;
}

From source file:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTests.java

private void assertSingleSessionCookie(String expected) {
    com.gargoylesoftware.htmlunit.util.Cookie jsessionidCookie = webClient.getCookieManager()
            .getCookie("JSESSIONID");
    if (expected == null || expected.contains("Expires=Thu, 01-Jan-1970 00:00:01 GMT")) {
        assertThat(jsessionidCookie, nullValue());
        return;//from   w  w  w . j a v a 2 s .c  o m
    }
    String actual = jsessionidCookie.getValue();
    assertThat("JSESSIONID=" + actual + "; Path=/test; Domain=example.com", equalTo(expected));
}