Example usage for javax.servlet.http Cookie getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the cookie.

Usage

From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java

private Cookies convertCookies(javax.servlet.http.Cookie[] servletCookies) {
    List<Cookie> cookies = new ArrayList<Cookie>();
    for (javax.servlet.http.Cookie servletCookie : servletCookies) {
        Cookie.Builder cookieBuilder = new Cookie.Builder(servletCookie.getName(), servletCookie.getValue());
        if (servletCookie.getComment() != null) {
            cookieBuilder.setComment(servletCookie.getComment());
        }/*from   w  w w  .ja va 2  s.  co m*/
        if (servletCookie.getDomain() != null) {
            cookieBuilder.setDomain(servletCookie.getDomain());
        }
        if (servletCookie.getPath() != null) {
            cookieBuilder.setPath(servletCookie.getPath());
        }
        cookieBuilder.setMaxAge(servletCookie.getMaxAge());
        cookieBuilder.setVersion(servletCookie.getVersion());
        cookieBuilder.setSecured(servletCookie.getSecure());
        cookies.add(cookieBuilder.build());
    }
    return new Cookies(cookies);
}

From source file:EditImage.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Security sec = new Security();

    PrintWriter out = response.getWriter();

    // Check to makes sure the user is logged in
    String userid = "";
    Cookie login_cookie = null;//from  w w w  .  j ava2s .  co  m
    Cookie cookie = null;
    Cookie[] cookies = null;
    // Get an array of cookies associated with this domain
    cookies = request.getCookies();
    // If any cookies were found, see if any of them contain a valid login.
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            // out.println(cookie.getName()+"<br>");
            // However, we only want one cookie, the one whose name matches
            // the
            // userid that has logged in on this browser.
            if (i != 0 && userid == "") {
                userid = cookie.getName();
            }
        }
    }
    // If no login was detected, redirect the user to the login page.
    if (userid == "") {
        out.println("<a href=login.jsp>Please login to access this site.</a>");
    }
    // Else, we have a valid session.
    else {
        // Gets the photo_id from the Query String
        String photo_id = request.getQueryString();

        // Variables
        String command = "";
        InputStream instream = null;
        Statement stmt = null;
        PreparedStatement updateSub = null;
        PreparedStatement updateLoc = null;
        PreparedStatement updateDate = null;
        PreparedStatement updateDesc = null;
        PreparedStatement updatePrivacy = null;

        // Default variables to add to table
        String subject = null;
        String place = null;
        String timing = null;
        String description = null;
        String permission = null;
        String groupName = null;

        try {

            // Gets the parameters for subject, place, timing, & description
            subject = request.getParameter("subject");
            place = request.getParameter("place");
            timing = request.getParameter("SnapHost_Calendar");
            description = request.getParameter("description");
            permission = request.getParameter("permission");
            groupName = request.getParameter("group");
            response_message = response_message + subject + place + timing + description + "PHOTO ID = "
                    + photo_id;

            // Connect to the database and create a statement
            Connection conn;
            conn = getConnected(drivername, dbstring, username, password);
            stmt = conn.createStatement();
            response_message = response_message + "connection good";

            // Only updates fields that had input
            if (!subject.isEmpty()) {
                updateSub = conn.prepareStatement(
                        "UPDATE images SET subject = \'" + subject + "\' WHERE photo_id = " + photo_id);
                updateSub.executeUpdate();
            }

            if (!place.isEmpty()) {
                updateLoc = conn.prepareStatement(
                        "UPDATE images SET place = \'" + place + "\' WHERE photo_id = " + photo_id);
                updateLoc.executeUpdate();
            }

            if (!timing.isEmpty()) {
                updateDate = conn.prepareStatement("UPDATE images SET timing = to_date('" + timing
                        + "', 'YYYY-MM-DD') WHERE photo_id = " + photo_id);
                updateDate.executeUpdate();
            }

            if (!description.isEmpty()) {
                updateDesc = conn.prepareStatement(
                        "UPDATE images SET description = \'" + description + "\' WHERE photo_id = " + photo_id);
                updateDesc.executeUpdate();
            }
            if (!permission.isEmpty()) {
                // Sets the permissions Value depending on what the user specified
                // Default is private 
                int permissionValue = 2;
                if (permission.equals("everyone")) {
                    permissionValue = 1;
                } else if (permission.equals("useronly")) {
                    permissionValue = 2;
                } else if (permission.equals("group")) {
                    // Set permission value to 0 to indicate no
                    // valid group in the case the user does not
                    // supply a valid group ID.
                    permissionValue = 0;
                    // What we actually want is the group ID
                    String groupid = sec.find_group_id(userid, groupName, conn);
                    // If a matching group ID is found, add it.
                    if (groupid != "") {
                        permissionValue = Integer.parseInt(groupid);
                    }

                }

                updateDesc = conn.prepareStatement("UPDATE images SET permitted = \'" + permissionValue
                        + "\' WHERE photo_id = " + photo_id);
                updateDesc.executeUpdate();
            }

            response_message = "Image Updated!";

        } catch (Exception e) {
            response_message = response_message + "uh oh";
        }
        try {
            // Output response to the client
            response.setContentType("text/html");
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n"
                    + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message
                    + "</H1>\n" + "</BODY></HTML>");
            out.println("<P><a href=\"GetBigPic?big" + photo_id + "\"> Back To Image </a>");
            out.println("</body>");
            out.println("</html>");
        } catch (Exception e) {
            response_message = response_message + "4";
        }
    }
}

From source file:net.lightbody.bmp.proxy.jetty.http.handler.DumpHandler.java

public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response)
        throws HttpException, IOException {
    if (!isStarted())
        return;//from  w w  w.  j  a va2 s .  c o  m

    // Only handle GET, HEAD and POST
    if (!HttpRequest.__GET.equals(request.getMethod()) && !HttpRequest.__HEAD.equals(request.getMethod())
            && !HttpRequest.__POST.equals(request.getMethod()))
        return;

    log.debug("Dump");

    response.setField(HttpFields.__ContentType, HttpFields.__TextHtml);
    OutputStream out = response.getOutputStream();
    ByteArrayOutputStream buf = new ByteArrayOutputStream(2048);
    Writer writer = new OutputStreamWriter(buf, StringUtil.__ISO_8859_1);
    writer.write("<HTML><H1>Dump HttpHandler</H1>");
    writer.write("<PRE>\npath=" + request.getPath() + "\ncontextPath=" + getHttpContext().getContextPath()
            + "\npathInContext=" + pathInContext + "\n</PRE>\n");
    writer.write("<H3>Header:</H3><PRE>");
    writer.write(request.toString());
    writer.write("</PRE>\n<H3>Parameters:</H3>\n<PRE>");
    Set names = request.getParameterNames();
    Iterator iter = names.iterator();
    while (iter.hasNext()) {
        String name = iter.next().toString();
        List values = request.getParameterValues(name);
        if (values == null || values.size() == 0) {
            writer.write(name);
            writer.write("=\n");
        } else if (values.size() == 1) {
            writer.write(name);
            writer.write("=");
            writer.write((String) values.get(0));
            writer.write("\n");
        } else {
            for (int i = 0; i < values.size(); i++) {
                writer.write(name);
                writer.write("[" + i + "]=");
                writer.write((String) values.get(i));
                writer.write("\n");
            }
        }
    }

    String cookie_name = request.getParameter("CookieName");
    if (cookie_name != null && cookie_name.trim().length() > 0) {
        String cookie_action = request.getParameter("Button");
        try {
            Cookie cookie = new Cookie(cookie_name.trim(), request.getParameter("CookieVal"));
            if ("Clear Cookie".equals(cookie_action))
                cookie.setMaxAge(0);
            response.addSetCookie(cookie);
        } catch (IllegalArgumentException e) {
            writer.write("</PRE>\n<H3>BAD Set-Cookie:</H3>\n<PRE>");
            writer.write(e.toString());
            LogSupport.ignore(log, e);
        }
    }

    writer.write("</PRE>\n<H3>Cookies:</H3>\n<PRE>");
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (int c = 0; c < cookies.length; c++) {
            Cookie cookie = cookies[c];
            writer.write(cookie.getName());
            writer.write("=");
            writer.write(cookie.getValue());
            writer.write("\n");
        }
    }

    writer.write("</PRE>\n<H3>Attributes:</H3>\n<PRE>");
    Enumeration attributes = request.getAttributeNames();
    if (attributes != null && attributes.hasMoreElements()) {
        while (attributes.hasMoreElements()) {
            String attr = attributes.nextElement().toString();
            writer.write(attr);
            writer.write("=");
            writer.write(request.getAttribute(attr).toString());
            writer.write("\n");
        }
    }

    writer.write("</PRE>\n<H3>Content:</H3>\n<PRE>");
    byte[] content = new byte[4096];
    int len;
    try {
        InputStream in = request.getInputStream();
        while ((len = in.read(content)) >= 0)
            writer.write(new String(content, 0, len));
    } catch (IOException e) {
        LogSupport.ignore(log, e);
        writer.write(e.toString());
    }

    // You wouldn't normally set a trailer like this, but
    // we don't want to commit the output to force trailers as
    // it makes test harness messy
    request.getAcceptableTransferCodings();

    // commit now
    writer.flush();
    response.setIntField(HttpFields.__ContentLength, buf.size() + 1000);
    buf.writeTo(out);
    out.flush();

    // Now add the response
    buf.reset();
    writer.write("</PRE>\n<H3>Response:</H3>\n<PRE>");
    writer.write(response.toString());
    writer.write("</PRE></HTML>");
    writer.flush();
    for (int pad = 998 - buf.size(); pad-- > 0;)
        writer.write(" ");
    writer.write("\015\012");
    writer.flush();
    buf.writeTo(out);

    request.setHandled(true);
}

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

/**
 * Deletes all cookies that start with "gsa"
 * //  w w  w  . ja  v  a  2  s.co  m
 * @param request HTTP request
 * @param response HTTP response
 */
public void deleteCookies(HttpServletRequest request, HttpServletResponse response) {

    // Retrieve cookies
    Cookie[] allCookies = request.getCookies();
    try {
        // Protection
        if (allCookies != null) {

            // Look for the authentication cookie
            for (int i = 0; i < allCookies.length; i++) {

                logger.debug("Cookie: " + allCookies[i].getName());

                //look for all the cookies start with "gsa" and delete them
                if ((allCookies[i].getName()).startsWith("gsa")) {

                    Cookie gsaCookie = new Cookie(allCookies[i].getName(), allCookies[i].getValue());

                    gsaCookie.setMaxAge(0);

                    response.addCookie(gsaCookie);

                    // Debug
                    if (logger.isDebugEnabled())
                        logger.debug("GSA cookie: [" + gsaCookie.getName() + " has been deleted ]");

                }

            }

        }
    } catch (Exception e) {
        logger.error("Error when deleting cookies: " + e.getMessage(), e);
    }
}

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

/**
 * Get cookie object by cookie name.//from  w w  w  . ja  v  a 2 s . c  o m
 */
public Cookie getCookieObject(String name) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null)
        for (Cookie cookie : cookies)
            if (cookie.getName().equals(name))
                return cookie;
    return null;
}

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// w  w w . j  av  a 2 s  .c  om
 * @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: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();//ww  w  .j  a v  a 2  s .  c o 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.mmj.app.web.controller.manage.ManageController.java

/**
 * Cookie?????//  w  ww .java2 s  . c o  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.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./* www  .j  a  v a  2s  . com*/
 */
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.konakart.actions.BaseAction.java

/**
 * Utility method to get the CustomerUuid from the browser cookie and create the cookie if it
 * doesn't exist./*from ww  w  .j ava 2 s.c o m*/
 * 
 * @param request
 * @return Returns the CustomerUuid
 */
private String getCustomerUuidFromBrowserCookie(HttpServletRequest request, HttpServletResponse response) {
    /*
     * Try to find the cookie we are looking for
     */
    Cookie[] cookies = request.getCookies();
    String uuid = null;
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            String cookieName = cookie.getName();
            if (cookieName.equals(CUSTOMER_UUID)) {
                /*
                 * If we find the cookie we get the value and update the max age.
                 */
                uuid = cookie.getValue();
                cookie.setMaxAge(COOKIE_MAX_AGE_IN_SECS);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
    }

    /*
     * If the browser cookie doesn't exist then we have to create it and store a newly created
     * UUID string
     */
    if (uuid == null) {
        UUID uuidObject = UUID.randomUUID();
        uuid = uuidObject.toString();
        /*
         * Create a browser cookie with the UUID
         */
        Cookie uuidCookie = new Cookie(CUSTOMER_UUID, uuid);
        uuidCookie.setMaxAge(COOKIE_MAX_AGE_IN_SECS);
        uuidCookie.setPath("/");
        response.addCookie(uuidCookie);
    }

    return uuid;
}