Example usage for javax.servlet.http HttpSession getAttributeNames

List of usage examples for javax.servlet.http HttpSession getAttributeNames

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession getAttributeNames.

Prototype

public Enumeration<String> getAttributeNames();

Source Link

Document

Returns an Enumeration of String objects containing the names of all the objects bound to this session.

Usage

From source file:net.groupbuy.controller.shop.LoginController.java

/**
 * ??//  ww w. j a v  a  2  s .co m
 */
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public @ResponseBody Message submit(String captchaId, String captcha, String username,
        HttpServletRequest request, HttpServletResponse response, HttpSession session) {
    String password = rsaService.decryptParameter("enPassword", request);
    rsaService.removePrivateKey(request);

    if (!captchaService.isValid(CaptchaType.memberLogin, captchaId, captcha)) {
        return Message.error("shop.captcha.invalid");
    }
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
        return Message.error("shop.common.invalid");
    }
    Member member;
    Setting setting = SettingUtils.get();
    if (setting.getIsEmailLogin() && username.contains("@")) {
        List<Member> members = memberService.findListByEmail(username);
        if (members.isEmpty()) {
            member = null;
        } else if (members.size() == 1) {
            member = members.get(0);
        } else {
            return Message.error("shop.login.unsupportedAccount");
        }
    } else {
        member = memberService.findByUsername(username);
    }
    if (member == null) {
        return Message.error("shop.login.unknownAccount");
    }
    if (!member.getIsEnabled()) {
        return Message.error("shop.login.disabledAccount");
    }
    if (member.getIsLocked()) {
        if (ArrayUtils.contains(setting.getAccountLockTypes(), AccountLockType.member)) {
            int loginFailureLockTime = setting.getAccountLockTime();
            if (loginFailureLockTime == 0) {
                return Message.error("shop.login.lockedAccount");
            }
            Date lockedDate = member.getLockedDate();
            Date unlockDate = DateUtils.addMinutes(lockedDate, loginFailureLockTime);
            if (new Date().after(unlockDate)) {
                member.setLoginFailureCount(0);
                member.setIsLocked(false);
                member.setLockedDate(null);
                memberService.update(member);
            } else {
                return Message.error("shop.login.lockedAccount");
            }
        } else {
            member.setLoginFailureCount(0);
            member.setIsLocked(false);
            member.setLockedDate(null);
            memberService.update(member);
        }
    }

    if (!DigestUtils.md5Hex(password).equals(member.getPassword())) {
        int loginFailureCount = member.getLoginFailureCount() + 1;
        if (loginFailureCount >= setting.getAccountLockCount()) {
            member.setIsLocked(true);
            member.setLockedDate(new Date());
        }
        member.setLoginFailureCount(loginFailureCount);
        memberService.update(member);
        if (ArrayUtils.contains(setting.getAccountLockTypes(), AccountLockType.member)) {
            return Message.error("shop.login.accountLockCount", setting.getAccountLockCount());
        } else {
            return Message.error("shop.login.incorrectCredentials");
        }
    }
    member.setLoginIp(request.getRemoteAddr());
    member.setLoginDate(new Date());
    member.setLoginFailureCount(0);
    memberService.update(member);

    Cart cart = cartService.getCurrent();
    if (cart != null) {
        if (cart.getMember() == null) {
            cartService.merge(member, cart);
            WebUtils.removeCookie(request, response, Cart.ID_COOKIE_NAME);
            WebUtils.removeCookie(request, response, Cart.KEY_COOKIE_NAME);
        }
    }

    Map<String, Object> attributes = new HashMap<String, Object>();
    Enumeration<?> keys = session.getAttributeNames();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        attributes.put(key, session.getAttribute(key));
    }
    session.invalidate();
    session = request.getSession();
    for (Entry<String, Object> entry : attributes.entrySet()) {
        session.setAttribute(entry.getKey(), entry.getValue());
    }

    session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), username));
    WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, member.getUsername());

    return SUCCESS_MESSAGE;
}

From source file:net.shopxx.controller.shop.LoginController.java

/**
 * ??//from  w w w  . ja  v  a2s  .  c o m
 */
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public @ResponseBody Message submit(String captchaId, String captcha, String username,
        HttpServletRequest request, HttpServletResponse response, HttpSession session) {
    String password = rsaService.decryptParameter("enPassword", request);
    rsaService.removePrivateKey(request);

    if (!captchaService.isValid(CaptchaType.memberLogin, captchaId, captcha)) {
        return Message.error("shop.captcha.invalid");
    }
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
        return Message.error("shop.common.invalid");
    }
    Member member;
    Setting setting = SettingUtils.get();
    if (setting.getIsEmailLogin() && username.contains("@")) {
        List<Member> members = memberService.findListByEmail(username);
        if (members.isEmpty()) {
            member = null;
        } else if (members.size() == 1) {
            member = members.get(0);
        } else {
            return Message.error("shop.login.unsupportedAccount");
        }
    } else {
        member = memberService.findByUsername(username);
    }
    if (member == null) {
        return Message.error("shop.login.unknownAccount");
    }
    if (!member.getIsEnabled()) {
        return Message.error("shop.login.disabledAccount");
    }
    if (member.getIsLocked()) {
        if (ArrayUtils.contains(setting.getAccountLockTypes(), AccountLockType.member)) {
            int loginFailureLockTime = setting.getAccountLockTime();
            if (loginFailureLockTime == 0) {
                return Message.error("shop.login.lockedAccount");
            }
            Date lockedDate = member.getLockedDate();
            Date unlockDate = DateUtils.addMinutes(lockedDate, loginFailureLockTime);
            if (new Date().after(unlockDate)) {
                member.setLoginFailureCount(0);
                member.setIsLocked(false);
                member.setLockedDate(null);
                memberService.update(member);
            } else {
                return Message.error("shop.login.lockedAccount");
            }
        } else {
            member.setLoginFailureCount(0);
            member.setIsLocked(false);
            member.setLockedDate(null);
            memberService.update(member);
        }
    }
    if (member.getActivateEmail() == null || !member.getActivateEmail()) {
        return Message.error("??");
    }

    if (!DigestUtils.md5Hex(password).equals(member.getPassword())) {
        int loginFailureCount = member.getLoginFailureCount() + 1;
        if (loginFailureCount >= setting.getAccountLockCount()) {
            member.setIsLocked(true);
            member.setLockedDate(new Date());
        }
        member.setLoginFailureCount(loginFailureCount);
        memberService.update(member);
        if (ArrayUtils.contains(setting.getAccountLockTypes(), AccountLockType.member)) {
            return Message.error("shop.login.accountLockCount", setting.getAccountLockCount());
        } else {
            return Message.error("shop.login.incorrectCredentials");
        }
    }
    member.setLoginIp(request.getRemoteAddr());
    member.setLoginDate(new Date());
    member.setLoginFailureCount(0);
    memberService.update(member);

    Cart cart = cartService.getCurrent();
    if (cart != null) {
        if (cart.getMember() == null) {
            cartService.merge(member, cart);
            WebUtils.removeCookie(request, response, Cart.ID_COOKIE_NAME);
            WebUtils.removeCookie(request, response, Cart.KEY_COOKIE_NAME);
        }
    }

    Map<String, Object> attributes = new HashMap<String, Object>();
    Enumeration<?> keys = session.getAttributeNames();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        attributes.put(key, session.getAttribute(key));
    }
    session.invalidate();
    session = request.getSession();
    for (Entry<String, Object> entry : attributes.entrySet()) {
        session.setAttribute(entry.getKey(), entry.getValue());
    }

    session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), username));
    WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, member.getUsername());

    return SUCCESS_MESSAGE;
}

From source file:org.wyona.yanel.servlet.YanelServlet.java

/**
 * Generate response from view of resource
 * @param request TODO/*from   w w w . j  a v  a 2 s.  c  o  m*/
 * @param response TODO
 */
private void getContent(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // INFO: Generate "yanel" document in order to collect information in case something should go wrong or some meta information should be requested
    org.w3c.dom.Document doc = null;
    try {
        doc = getDocument(NAMESPACE, "yanel");
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }

    Element rootElement = doc.getDocumentElement();

    rootElement.setAttribute("servlet-context-real-path", servletContextRealPath);

    Element requestElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "request"));
    requestElement.setAttributeNS(NAMESPACE, "uri", request.getRequestURI());
    requestElement.setAttributeNS(NAMESPACE, "servlet-path", request.getServletPath());

    HttpSession session = request.getSession(true);
    Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session"));
    sessionElement.setAttribute("id", session.getId());
    Enumeration<?> attrNames = session.getAttributeNames();
    if (!attrNames.hasMoreElements()) {
        Element sessionNoAttributesElement = (Element) sessionElement
                .appendChild(doc.createElement("no-attributes"));
    }
    while (attrNames.hasMoreElements()) {
        String name = (String) attrNames.nextElement();
        String value = session.getAttribute(name).toString();
        Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute"));
        sessionAttributeElement.setAttribute("name", name);
        sessionAttributeElement.appendChild(doc.createTextNode(value));
    }

    String usecase = request.getParameter(YANEL_RESOURCE_USECASE);
    Resource res = null;
    TrackingInformationV1 trackInfo = null;
    long lastModified = -1;
    long size = -1;

    // START first try
    View view = null;
    try {
        Environment environment = getEnvironment(request, response);
        res = getResource(request, response);
        if (res != null) {
            if (isTrackable(res)) {
                //log.debug("Do track: " + res.getPath());
                trackInfo = new TrackingInformationV1();
                ((org.wyona.yanel.core.api.attributes.TrackableV1) res).doTrack(trackInfo);
                //} else {
                //    log.debug("Resource '" + res.getPath() + "' is not trackable.");
            }

            // START introspection generation
            if (usecase != null && usecase.equals("introspection")) {
                sendIntrospectionAsResponse(res, doc, rootElement, request, response);
                return;
            }
            // END introspection generation

            Element resourceElement = getResourceMetaData(res, doc, rootElement);
            Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view"));
            if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) {
                if (log.isDebugEnabled())
                    log.debug("Resource is viewable V1");
                viewElement.setAttributeNS(NAMESPACE, "version", "1");
                appendViewDescriptors(doc, viewElement, ((ViewableV1) res).getViewDescriptors());

                String viewId = getViewID(request);
                try {
                    view = ((ViewableV1) res).getView(request, viewId);
                } catch (org.wyona.yarep.core.NoSuchNodeException e) {
                    String message = e.getMessage();
                    log.error(message, e);
                    do404(request, response, doc, message);
                    return;
                } catch (Exception e) {
                    String message = e.getMessage();
                    log.error(message, e);
                    Element exceptionElement = (Element) rootElement
                            .appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME));
                    exceptionElement.appendChild(doc.createTextNode(message));
                    exceptionElement.setAttributeNS(NAMESPACE, "status", "500");
                    response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    setYanelOutput(request, response, doc);
                    return;
                }
            } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "2")) {
                if (log.isDebugEnabled())
                    log.debug("Resource '" + res.getPath() + "' is viewable V2");
                viewElement.setAttributeNS(NAMESPACE, "version", "2");
                appendViewDescriptors(doc, viewElement, ((ViewableV2) res).getViewDescriptors());

                if (!((ViewableV2) res).exists()) {
                    log.warn("ViewableV2 resource '" + res.getPath()
                            + "' does not seem to exist, whereas this resource might not implement exists() properly. Yanel does not generate a 404 response for backwards compatibility reasons, because there are various ViewableV2 resources which do not implement exists() properly. As a workaround one might want to use the exists() method within the getView(String) method and throw a ResourceNotFoundException instead.");
                    //do404(request, response, doc, res.getPath());
                    //return;
                }

                try {
                    size = ((ViewableV2) res).getSize();
                    Element sizeElement = (Element) resourceElement.appendChild(doc.createElement("size"));
                    sizeElement.appendChild(doc.createTextNode(String.valueOf(size)));
                } catch (ResourceNotFoundException e) {
                    log.error(e, e); // INFO: Let's be fault tolerant such that a 404 can be handled more gracefully further down
                }

                String viewId = getViewID(request);
                try {
                    String revisionName = request.getParameter(YANEL_RESOURCE_REVISION);
                    // NOTE: Check also if usecase is not roll-back, because roll-back is also using the yanel.resource.revision
                    if (revisionName != null && !isRollBack(request)) {
                        if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) {
                            view = ((VersionableV2) res).getView(viewId, revisionName);
                        } else {
                            log.warn("Resource '" + res.getPath()
                                    + "' has not VersionableV2 implemented, hence we cannot generate view for revision: "
                                    + revisionName);
                            view = ((ViewableV2) res).getView(viewId);
                        }
                    } else if (environment.getStateOfView().equals(StateOfView.LIVE)
                            && ResourceAttributeHelper.hasAttributeImplemented(res, "Workflowable", "1")
                            && WorkflowHelper.getWorkflow(res) != null) { // TODO: Instead using the WorkflowHelper the Workflowable interface should have a method to check if the resource actually has a workflow assigned, see http://lists.wyona.org/pipermail/yanel-development/2009-June/003709.html
                        // TODO: Check if resource actually exists (see the exist problem above), because even it doesn't exist, the workflowable interfaces can return something although it doesn't really make sense. For example if a resource type is workflowable, but it has no workflow associated with it, then WorkflowHelper.isLive will nevertheless return true, whereas WorkflowHelper.getLiveView will throw an exception!
                        if (!((ViewableV2) res).exists()) {
                            log.warn("No such ViewableV2 resource: " + res.getPath());
                            log.warn(
                                    "TODO: It seems like many ViewableV2 resources are not implementing exists() properly!");
                            do404(request, response, doc, res.getPath());
                            return;
                        }

                        WorkflowableV1 workflowable = (WorkflowableV1) res;
                        if (workflowable.isLive()) {
                            view = workflowable.getLiveView(viewId);
                        } else {
                            String message = "The viewable (V2) resource '" + res.getPath()
                                    + "' is WorkflowableV1, but has not been published yet.";
                            log.warn(message);
                            // TODO: Make this configurable per resource (or rather workflowable interface) or per realm?!
                            if (displayMostRecentVersion) {
                                // INFO: Because of backwards compatibility the default should display the most recent version
                                log.warn(
                                        "Instead a live/published version, the most recent version will be displayed!");
                                view = ((ViewableV2) res).getView(viewId);
                            } else {
                                log.warn("Instead a live/published version, a 404 will be displayed!");
                                // TODO: Instead a 404 one might want to show a different kind of screen
                                do404(request, response, doc, message);
                                return;
                            }
                        }
                    } else {
                        view = ((ViewableV2) res).getView(viewId);
                    }
                } catch (org.wyona.yarep.core.NoSuchNodeException e) {
                    String message = e.getMessage();
                    log.warn(message, e);
                    do404(request, response, doc, message);
                    return;
                } catch (ResourceNotFoundException e) {
                    String message = e.getMessage();
                    log.warn(message, e);
                    do404(request, response, doc, message);
                    return;
                } catch (Exception e) {
                    log.error(e, e);
                    handleException(request, response, e);
                    return;
                }
            } else { // NO Viewable interface implemented!
                String message = res.getClass().getName() + " is not viewable! (" + res.getPath() + ", "
                        + res.getRealm() + ")";
                log.error(message);
                Element noViewElement = (Element) resourceElement
                        .appendChild(doc.createElement("not-viewable"));
                noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!"));
                Element exceptionElement = (Element) rootElement
                        .appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME));
                exceptionElement.appendChild(doc.createTextNode(message));
                exceptionElement.setAttributeNS(NAMESPACE, "status", "501");
                response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED);
                setYanelOutput(request, response, doc);
                return;
            }

            if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) {
                lastModified = ((ModifiableV2) res).getLastModified();
                Element lastModifiedElement = (Element) resourceElement
                        .appendChild(doc.createElement("last-modified"));
                lastModifiedElement.appendChild(doc.createTextNode(new Date(lastModified).toString()));
            } else {
                Element noLastModifiedElement = (Element) resourceElement
                        .appendChild(doc.createElement("no-last-modified"));
            }

            // INFO: Get the revisions, but only in the meta usecase (because of performance reasons)
            if (request.getParameter(RESOURCE_META_ID_PARAM_NAME) != null) {
                appendRevisionsAndWorkflow(doc, resourceElement, res, request);
            }

            if (ResourceAttributeHelper.hasAttributeImplemented(res, "Translatable", "1")) {
                TranslatableV1 translatable = ((TranslatableV1) res);
                Element translationsElement = (Element) resourceElement
                        .appendChild(doc.createElement("translations"));
                String[] languages = translatable.getLanguages();
                for (int i = 0; i < languages.length; i++) {
                    Element translationElement = (Element) translationsElement
                            .appendChild(doc.createElement("translation"));
                    translationElement.setAttribute("language", languages[i]);
                    String path = translatable.getTranslation(languages[i]).getPath();
                    translationElement.setAttribute("path", path);
                }
            }

            if (usecase != null && usecase.equals("checkout")) {
                if (log.isDebugEnabled())
                    log.debug("Checkout data ...");

                if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) {
                    // NOTE: The code below will throw an exception if the document is checked out already by another user.
                    String userID = environment.getIdentity().getUsername();
                    VersionableV2 versionable = (VersionableV2) res;
                    if (versionable.isCheckedOut()) {
                        String checkoutUserID = versionable.getCheckoutUserID();
                        if (checkoutUserID.equals(userID)) {
                            log.warn("Resource " + res.getPath() + " is already checked out by this user: "
                                    + checkoutUserID);
                        } else {
                            if (isClientSupportingNeutron(request)) {
                                String eMessage = "Resource '" + res.getPath()
                                        + "' is already checked out by another user: " + checkoutUserID;
                                response.setContentType("application/xml");
                                response.setStatus(
                                        javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                                // TODO: Checkout date and break-lock (optional)
                                response.getWriter().print(XMLExceptionV1.getCheckoutException(eMessage,
                                        res.getPath(), checkoutUserID, null));
                                return;
                            } else {
                                throw new Exception("Resource '" + res.getPath()
                                        + "' is already checked out by another user: " + checkoutUserID);
                            }
                        }
                    } else {
                        versionable.checkout(userID);
                    }
                } else {
                    log.warn("Acquire lock has not been implemented yet ...!");
                    // acquireLock();
                }
            }
        } else {
            Element resourceIsNullElement = (Element) rootElement
                    .appendChild(doc.createElement("resource-is-null"));
        }
    } catch (org.wyona.yarep.core.NoSuchNodeException e) {
        String message = e.getMessage();
        log.warn(message, e);
        do404(request, response, doc, message);
        return;
    } catch (org.wyona.yanel.core.ResourceNotFoundException e) {
        String message = e.getMessage();
        log.warn(message, e);
        do404(request, response, doc, message);
        return;
    } catch (Exception e) {
        log.error(e, e);
        handleException(request, response, e);
        return;
    }
    // END first try

    String meta = request.getParameter(RESOURCE_META_ID_PARAM_NAME);
    if (meta != null) {
        if (meta.length() > 0) {
            if (meta.equals("annotations")) {
                log.debug("Remove everything from the page meta document except the annotations");
                cleanMetaDoc(doc);
                appendAnnotations(doc, res);
                appendTrackingInformation(doc, trackInfo);
            } else {
                log.warn("TODO: Stripping everything from page meta document but, '" + meta
                        + "' not supported!");
            }
        } else {
            log.debug("Show all meta");
            appendAnnotations(doc, res);
            appendTrackingInformation(doc, trackInfo);
        }
        response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
        setYanelOutput(request, response, doc);
        return;
    }

    if (view != null) {
        if (generateResponse(view, res, request, response, -1, doc, size, lastModified, trackInfo) != null) {
            //log.debug("Response has been generated successfully :-)");
            return;
        } else {
            log.warn("No response has been generated!");
        }
    } else {
        String message = "View is null!";
        Element exceptionElement = (Element) rootElement
                .appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME));
        exceptionElement.appendChild(doc.createTextNode(message));
    }

    response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    setYanelOutput(request, response, doc);
    return;
}

From source file:com.exilant.exility.core.HtmlRequestHandler.java

/**
 * Extract data from request object (form, data and session)
 * //from  w  w  w  .j  a  v a2 s.  co  m
 * @param req
 * @param formIsSubmitted
 * @param hasSerializedDc
 * @param outData
 * @return all input fields into a service data
 * @throws ExilityException
 */
@SuppressWarnings("resource")
public ServiceData createInData(HttpServletRequest req, boolean formIsSubmitted, boolean hasSerializedDc,
        ServiceData outData) throws ExilityException {

    ServiceData inData = new ServiceData();
    if (formIsSubmitted == false) {
        /**
         * most common call from client that uses serverAgent to send an
         * ajax request with serialized dc as data
         */
        this.extractSerializedData(req, hasSerializedDc, inData);
    } else {
        /**
         * form is submitted. this is NOT from serverAgent.js. This call
         * would be from other .jsp files
         */
        if (hasSerializedDc == false) {
            /**
             * client has submitted a form with form fields in that.
             * Traditional form submit
             **/
            this.extractParametersAndFiles(req, inData);
        } else {
            /**
             * Logic got evolved over a period of time. several calling jsps
             * actually inspect the stream for file, and in the process they
             * would have extracted form fields into session. So, we extract
             * form fields, as well as dip into session
             */
            HttpSession session = req.getSession();
            if (ServletFileUpload.isMultipartContent(req) == false) {
                /**
                 * Bit convoluted. the .jsp has already extracted files and
                 * form fields into session. field.
                 */
                String txt = session.getAttribute("dc").toString();
                this.extractSerializedDc(txt, inData);
                this.extractFilesToDc(req, inData);
            } else {
                /**
                 * jsp has not touched input stream, and it wants us to do
                 * everything.
                 */
                try {
                    ServletFileUpload fileUploader = new ServletFileUpload();
                    fileUploader.setHeaderEncoding("UTF-8");
                    FileItemIterator iterator = fileUploader.getItemIterator(req);
                    while (iterator.hasNext()) {
                        FileItemStream stream = iterator.next();
                        String fieldName = stream.getFieldName();
                        InputStream inStream = null;
                        inStream = stream.openStream();
                        try {
                            if (stream.isFormField()) {
                                String fieldValue = Streams.asString(inStream);
                                /**
                                 * dc is a special name that contains
                                 * serialized DC
                                 */
                                if (fieldName.equals("dc")) {
                                    this.extractSerializedDc(fieldValue, inData);
                                } else {
                                    inData.addValue(fieldName, fieldValue);
                                }
                            } else {
                                /**
                                 * it is a file. we assume that the files
                                 * are small, and hence we carry the content
                                 * in memory with a specific naming
                                 * convention
                                 */
                                String fileContents = IOUtils.toString(inStream);
                                inData.addValue(fieldName + HtmlRequestHandler.PATH_SUFFIX, fileContents);
                            }
                        } catch (Exception e) {
                            Spit.out("error whiel extracting data from request stream " + e.getMessage());
                        }
                        IOUtils.closeQuietly(inStream);
                    }
                } catch (Exception e) {
                    // nothing to do here
                }
                /**
                 * read session variables
                 */
                @SuppressWarnings("rawtypes")
                Enumeration e = session.getAttributeNames();
                while (e.hasMoreElements()) {
                    String name = (String) e.nextElement();
                    if (name.equals("dc")) {
                        this.extractSerializedDc(req.getSession().getAttribute(name).toString(), inData);
                    }
                    String value = req.getSession().getAttribute(name).toString();
                    inData.addValue(name, value);
                    System.out.println("name is: " + name + " value is: " + value);
                }
            }
        }
    }
    this.getStandardFields(req, inData);
    return inData;
}

From source file:com.sammyun.controller.shop.RegisterController.java

/**
 * ??//from w w w .j  a v  a2 s  .c  o m
 */
@RequestMapping(value = "/registSubmit", method = RequestMethod.POST)
public @ResponseBody Message registSubmit(String firstName, String givenName, String email, String mobile,
        RegMode regMode, Long areaId, boolean thirdPart, HttpServletRequest request,
        HttpServletResponse response, HttpSession session) {
    String password = rsaService.decryptParameter("enPassword", request);
    rsaService.removePrivateKey(request);

    Setting setting = SettingUtils.get();
    if (!setting.getIsRegisterEnabled()) {
        return Message.error("shop.register.disabled");
    }
    if (password.length() < setting.getPasswordMinLength()) {
        return Message.error("shop.login.password.length.lessThan", setting.getPasswordMinLength());
    }
    if (password.length() > setting.getPasswordMaxLength()) {
        return Message.error("shop.login.password.length.greater", setting.getPasswordMaxLength());
    }
    if (!setting.getIsDuplicateEmail() && memberService.emailExists(email)) {
        return Message.error("shop.register.emailExist");
    }

    Member member = new Member();
    List<MemberAttribute> memberAttributes = memberAttributeService.findList();
    for (MemberAttribute memberAttribute : memberAttributes) {
        String parameter = request.getParameter("memberAttribute_" + memberAttribute.getId());
        if (memberAttribute.getType() == Type.name || memberAttribute.getType() == Type.address
                || memberAttribute.getType() == Type.zipCode || memberAttribute.getType() == Type.phone
                || memberAttribute.getType() == Type.mobile || memberAttribute.getType() == Type.text
                || memberAttribute.getType() == Type.select) {
            if (memberAttribute.getIsRequired() && StringUtils.isEmpty(parameter)) {
                return Message.error("shop.common.invalid");
            }
            member.setAttributeValue(memberAttribute, parameter);
        } else if (memberAttribute.getType() == Type.gender) {
            Gender gender = StringUtils.isNotEmpty(parameter) ? Gender.valueOf(parameter) : null;
            if (memberAttribute.getIsRequired() && gender == null) {
                return Message.error("shop.common.invalid");
            }
            member.setGender(gender);
        } else if (memberAttribute.getType() == Type.birth) {
            try {
                Date birth = StringUtils.isNotEmpty(parameter)
                        ? DateUtils.parseDate(parameter, CommonAttributes.DATE_PATTERNS)
                        : null;
                if (memberAttribute.getIsRequired() && birth == null) {
                    return Message.error("shop.common.invalid");
                }
                member.setBirth(birth);
            } catch (ParseException e) {
                return Message.error("shop.common.invalid");
            }
        } else if (memberAttribute.getType() == Type.area) {
            Area area = StringUtils.isNotEmpty(parameter) ? areaService.find(Long.valueOf(parameter)) : null;
            if (area != null) {
                member.setArea(area);
            } else if (memberAttribute.getIsRequired()) {
                return Message.error("shop.common.invalid");
            }
        } else if (memberAttribute.getType() == Type.checkbox) {
            String[] parameterValues = request.getParameterValues("memberAttribute_" + memberAttribute.getId());
            List<String> options = parameterValues != null ? Arrays.asList(parameterValues) : null;
            if (memberAttribute.getIsRequired() && (options == null || options.isEmpty())) {
                return Message.error("shop.common.invalid");
            }
            member.setAttributeValue(memberAttribute, options);
        }
    }
    Area area = this.areaService.find(areaId);
    if (RegMode.email == regMode) {
        member.setUsername(email);
    } else if (RegMode.mobile == regMode) {
        member.setUsername(mobile);
    } else {
        member.setUsername(email);
    }
    member.setPassword(DigestUtils.md5Hex(password));
    member.setEmail(email);
    member.setMobile(mobile);
    member.setArea(area);
    member.setPoint(setting.getRegisterPoint());
    member.setIsEnabled(true);
    member.setIsLocked(false);
    member.setLoginFailureCount(0);
    member.setLockedDate(null);
    member.setRegisterIp(EduUtil.getAddr(request));
    member.setLoginIp(EduUtil.getAddr(request));
    member.setLoginDate(new Date());
    member.setSafeKey(null);
    member.setAddress(area.getFullName());
    memberService.save(member);

    Map<String, Object> attributes = new HashMap<String, Object>();
    Enumeration<?> keys = session.getAttributeNames();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        attributes.put(key, session.getAttribute(key));
    }
    session.invalidate();
    session = request.getSession();
    for (Entry<String, Object> entry : attributes.entrySet()) {
        session.setAttribute(entry.getKey(), entry.getValue());
    }

    session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), member.getUsername()));
    WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, member.getUsername());
    return Message.success("shop.register.success");
}

From source file:com.sammyun.controller.shop.RegisterController.java

/**
 * ??/*w w  w  .  ja  v  a 2  s. co  m*/
 */
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public @ResponseBody Message submit(String captchaId, String captcha, String username, String email,
        HttpServletRequest request, HttpServletResponse response, HttpSession session) {
    String password = rsaService.decryptParameter("enPassword", request);
    rsaService.removePrivateKey(request);

    if (!captchaService.isValid(CaptchaType.memberRegister, captchaId, captcha)) {
        return Message.error("shop.captcha.invalid");
    }
    Setting setting = SettingUtils.get();
    if (!setting.getIsRegisterEnabled()) {
        return Message.error("shop.register.disabled");
    }
    if (!isValid(Member.class, "username", username, Save.class)
            || !isValid(Member.class, "password", password, Save.class)
            || !isValid(Member.class, "email", email, Save.class)) {
        return Message.error("shop.common.invalid");
    }
    if (username.length() < setting.getUsernameMinLength()
            || username.length() > setting.getUsernameMaxLength()) {
        return Message.error("shop.common.invalid");
    }
    if (password.length() < setting.getPasswordMinLength()
            || password.length() > setting.getPasswordMaxLength()) {
        return Message.error("shop.common.invalid");
    }
    if (memberService.usernameDisabled(username) || memberService.usernameExists(username)) {
        return Message.error("shop.register.disabledExist");
    }
    if (!setting.getIsDuplicateEmail() && memberService.emailExists(email)) {
        return Message.error("shop.register.emailExist");
    }
    Member member = new Member();
    List<MemberAttribute> memberAttributes = memberAttributeService.findList();
    for (MemberAttribute memberAttribute : memberAttributes) {
        String parameter = request.getParameter("memberAttribute_" + memberAttribute.getId());
        if (memberAttribute.getType() == Type.name || memberAttribute.getType() == Type.address
                || memberAttribute.getType() == Type.zipCode || memberAttribute.getType() == Type.phone
                || memberAttribute.getType() == Type.mobile || memberAttribute.getType() == Type.text
                || memberAttribute.getType() == Type.select) {
            if (memberAttribute.getIsRequired() && StringUtils.isEmpty(parameter)) {
                return Message.error("shop.common.invalid");
            }
            member.setAttributeValue(memberAttribute, parameter);
        } else if (memberAttribute.getType() == Type.gender) {
            Gender gender = StringUtils.isNotEmpty(parameter) ? Gender.valueOf(parameter) : null;
            if (memberAttribute.getIsRequired() && gender == null) {
                return Message.error("shop.common.invalid");
            }
            member.setGender(gender);
        } else if (memberAttribute.getType() == Type.birth) {
            try {
                Date birth = StringUtils.isNotEmpty(parameter)
                        ? DateUtils.parseDate(parameter, CommonAttributes.DATE_PATTERNS)
                        : null;
                if (memberAttribute.getIsRequired() && birth == null) {
                    return Message.error("shop.common.invalid");
                }
                member.setBirth(birth);
            } catch (ParseException e) {
                return Message.error("shop.common.invalid");
            }
        } else if (memberAttribute.getType() == Type.area) {
            Area area = StringUtils.isNotEmpty(parameter) ? areaService.find(Long.valueOf(parameter)) : null;
            if (area != null) {
                member.setArea(area);
            } else if (memberAttribute.getIsRequired()) {
                return Message.error("shop.common.invalid");
            }
        } else if (memberAttribute.getType() == Type.checkbox) {
            String[] parameterValues = request.getParameterValues("memberAttribute_" + memberAttribute.getId());
            List<String> options = parameterValues != null ? Arrays.asList(parameterValues) : null;
            if (memberAttribute.getIsRequired() && (options == null || options.isEmpty())) {
                return Message.error("shop.common.invalid");
            }
            member.setAttributeValue(memberAttribute, options);
        }
    }
    member.setUsername(username.toLowerCase());
    member.setPassword(DigestUtils.md5Hex(password));
    member.setEmail(email);
    member.setPoint(setting.getRegisterPoint());
    member.setIsEnabled(true);
    member.setIsLocked(false);
    member.setLoginFailureCount(0);
    member.setLockedDate(null);
    member.setRegisterIp(EduUtil.getAddr(request));
    member.setLoginIp(EduUtil.getAddr(request));
    member.setLoginDate(new Date());
    member.setSafeKey(null);
    memberService.save(member);

    Map<String, Object> attributes = new HashMap<String, Object>();
    Enumeration<?> keys = session.getAttributeNames();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        attributes.put(key, session.getAttribute(key));
    }
    session.invalidate();
    session = request.getSession();
    for (Entry<String, Object> entry : attributes.entrySet()) {
        session.setAttribute(entry.getKey(), entry.getValue());
    }

    session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), member.getUsername()));
    WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, member.getUsername());

    return Message.success("shop.register.success");
}

From source file:net.groupbuy.controller.shop.RegisterController.java

/**
 * ??/*from   ww w. j  a v  a  2 s.c o  m*/
 */
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public @ResponseBody Message submit(String captchaId, String captcha, String username, String email,
        HttpServletRequest request, HttpServletResponse response, HttpSession session) {
    String password = rsaService.decryptParameter("enPassword", request);
    rsaService.removePrivateKey(request);

    if (!captchaService.isValid(CaptchaType.memberRegister, captchaId, captcha)) {
        return Message.error("shop.captcha.invalid");
    }
    Setting setting = SettingUtils.get();
    if (!setting.getIsRegisterEnabled()) {
        return Message.error("shop.register.disabled");
    }
    if (!isValid(Member.class, "username", username, Save.class)
            || !isValid(Member.class, "password", password, Save.class)
            || !isValid(Member.class, "email", email, Save.class)) {
        return Message.error("shop.common.invalid");
    }
    if (username.length() < setting.getUsernameMinLength()
            || username.length() > setting.getUsernameMaxLength()) {
        return Message.error("shop.common.invalid");
    }
    if (password.length() < setting.getPasswordMinLength()
            || password.length() > setting.getPasswordMaxLength()) {
        return Message.error("shop.common.invalid");
    }
    if (memberService.usernameDisabled(username) || memberService.usernameExists(username)) {
        return Message.error("shop.register.disabledExist");
    }
    if (!setting.getIsDuplicateEmail() && memberService.emailExists(email)) {
        return Message.error("shop.register.emailExist");
    }

    Member member = new Member();
    List<MemberAttribute> memberAttributes = memberAttributeService.findList();
    for (MemberAttribute memberAttribute : memberAttributes) {
        String parameter = request.getParameter("memberAttribute_" + memberAttribute.getId());
        if (memberAttribute.getType() == Type.name || memberAttribute.getType() == Type.address
                || memberAttribute.getType() == Type.zipCode || memberAttribute.getType() == Type.phone
                || memberAttribute.getType() == Type.mobile || memberAttribute.getType() == Type.text
                || memberAttribute.getType() == Type.select) {
            if (memberAttribute.getIsRequired() && StringUtils.isEmpty(parameter)) {
                return Message.error("shop.common.invalid");
            }
            member.setAttributeValue(memberAttribute, parameter);
        } else if (memberAttribute.getType() == Type.gender) {
            Gender gender = StringUtils.isNotEmpty(parameter) ? Gender.valueOf(parameter) : null;
            if (memberAttribute.getIsRequired() && gender == null) {
                return Message.error("shop.common.invalid");
            }
            member.setGender(gender);
        } else if (memberAttribute.getType() == Type.birth) {
            try {
                Date birth = StringUtils.isNotEmpty(parameter)
                        ? DateUtils.parseDate(parameter, CommonAttributes.DATE_PATTERNS)
                        : null;
                if (memberAttribute.getIsRequired() && birth == null) {
                    return Message.error("shop.common.invalid");
                }
                member.setBirth(birth);
            } catch (ParseException e) {
                return Message.error("shop.common.invalid");
            }
        } else if (memberAttribute.getType() == Type.area) {
            Area area = StringUtils.isNotEmpty(parameter) ? areaService.find(Long.valueOf(parameter)) : null;
            if (area != null) {
                member.setArea(area);
            } else if (memberAttribute.getIsRequired()) {
                return Message.error("shop.common.invalid");
            }
        } else if (memberAttribute.getType() == Type.checkbox) {
            String[] parameterValues = request.getParameterValues("memberAttribute_" + memberAttribute.getId());
            List<String> options = parameterValues != null ? Arrays.asList(parameterValues) : null;
            if (memberAttribute.getIsRequired() && (options == null || options.isEmpty())) {
                return Message.error("shop.common.invalid");
            }
            member.setAttributeValue(memberAttribute, options);
        }
    }
    member.setUsername(username.toLowerCase());
    member.setPassword(DigestUtils.md5Hex(password));
    member.setEmail(email);
    member.setPoint(setting.getRegisterPoint());
    member.setAmount(new BigDecimal(0));
    member.setBalance(new BigDecimal(0));
    member.setIsEnabled(true);
    member.setIsLocked(false);
    member.setLoginFailureCount(0);
    member.setLockedDate(null);
    member.setRegisterIp(request.getRemoteAddr());
    member.setLoginIp(request.getRemoteAddr());
    member.setLoginDate(new Date());
    member.setSafeKey(null);
    member.setMemberRank(memberRankService.findDefault());
    member.setFavoriteProducts(null);
    memberService.save(member);

    Cart cart = cartService.getCurrent();
    if (cart != null && cart.getMember() == null) {
        cartService.merge(member, cart);
        WebUtils.removeCookie(request, response, Cart.ID_COOKIE_NAME);
        WebUtils.removeCookie(request, response, Cart.KEY_COOKIE_NAME);
    }

    Map<String, Object> attributes = new HashMap<String, Object>();
    Enumeration<?> keys = session.getAttributeNames();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        attributes.put(key, session.getAttribute(key));
    }
    session.invalidate();
    session = request.getSession();
    for (Entry<String, Object> entry : attributes.entrySet()) {
        session.setAttribute(entry.getKey(), entry.getValue());
    }

    session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), member.getUsername()));
    WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, member.getUsername());

    return Message.success("shop.register.success");
}

From source file:net.shopxx.controller.shop.RegisterController.java

/**
 * ??//from   w  w w . j a  v a2 s .c om
 */
@RequestMapping(value = "/submit_email", method = RequestMethod.POST)
public @ResponseBody Message submitEmail(String captchaId, String captcha, String email, Long userId,
        String registStep, String userImg, String trueName, String idCardImg, HttpServletRequest request,
        HttpServletResponse response, HttpSession session, ModelMap model) {
    Setting setting = SettingUtils.get();
    Member member = new Member();
    if (userId != null) {// id?
        member = memberService.find(userId);
        if ("2".equals(registStep)) {// 
            member.setUserImg(userImg);
            List<MemberAttribute> memberAttributes = memberAttributeService.findList();
            for (MemberAttribute memberAttribute : memberAttributes) {
                String parameter = request.getParameter("memberAttribute_" + memberAttribute.getId());
                if (memberAttribute.getType() == Type.name || memberAttribute.getType() == Type.address
                        || memberAttribute.getType() == Type.zipCode || memberAttribute.getType() == Type.phone
                        || memberAttribute.getType() == Type.mobile || memberAttribute.getType() == Type.text
                        || memberAttribute.getType() == Type.select) {
                    if (memberAttribute.getIsRequired() && StringUtils.isEmpty(parameter)) {
                        return Message.error("shop.common.invalid");
                    }
                    member.setAttributeValue(memberAttribute, parameter);
                } else if (memberAttribute.getType() == Type.gender) {
                    Gender gender = StringUtils.isNotEmpty(parameter) ? Gender.valueOf(parameter) : null;
                    if (memberAttribute.getIsRequired() && gender == null) {
                        return Message.error("shop.common.invalid");
                    }
                    member.setGender(gender);
                } else if (memberAttribute.getType() == Type.birth) {
                    try {
                        Date birth = StringUtils.isNotEmpty(parameter)
                                ? DateUtils.parseDate(parameter, CommonAttributes.DATE_PATTERNS)
                                : null;
                        if (memberAttribute.getIsRequired() && birth == null) {
                            return Message.error("shop.common.invalid");
                        }
                        member.setBirth(birth);
                    } catch (ParseException e) {
                        return Message.error("shop.common.invalid");
                    }
                } else if (memberAttribute.getType() == Type.area) {
                    Area area = StringUtils.isNotEmpty(parameter) ? areaService.find(Long.valueOf(parameter))
                            : null;
                    if (area != null) {
                        member.setArea(area);
                    } else if (memberAttribute.getIsRequired()) {
                        return Message.error("shop.common.invalid");
                    }
                } else if (memberAttribute.getType() == Type.checkbox) {
                    String[] parameterValues = request
                            .getParameterValues("memberAttribute_" + memberAttribute.getId());
                    List<String> options = parameterValues != null ? Arrays.asList(parameterValues) : null;
                    if (memberAttribute.getIsRequired() && (options == null || options.isEmpty())) {
                        return Message.error("shop.common.invalid");
                    }
                    member.setAttributeValue(memberAttribute, options);
                }
            }
            net.shopxx.Template activateAccountMailTemplate = templateService.get("activateAccount");
            SafeKey safeKey = new SafeKey();
            safeKey.setValue(
                    UUID.randomUUID().toString() + DigestUtils.md5Hex(RandomStringUtils.randomAlphabetic(30)));
            safeKey.setExpire(setting.getSafeKeyExpiryTime() != 0
                    ? DateUtils.addMinutes(new Date(), setting.getSafeKeyExpiryTime())
                    : null);
            member.setSafeKey(safeKey);
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("member", member);
            param.put("domain", setting.getSiteUrl());// http

            mailService.send(member.getEmail(), "???",
                    activateAccountMailTemplate.getTemplatePath(), param);

        } else if ("3".equals(registStep)) {
            member.setTrueName(trueName);
            member.setIdCardImg(idCardImg);
        }

        member.setRegistStep(registStep);// ??
        memberService.update(member);
    } else {// id
        String password = rsaService.decryptParameter("enPassword", request);
        rsaService.removePrivateKey(request);

        if (!captchaService.isValid(CaptchaType.memberRegister, captchaId, captcha)) {
            return Message.error("shop.captcha.invalid");
        }

        if (!setting.getIsRegisterEnabled()) {
            return Message.error("shop.register.disabled");
        }
        if (!isValid(Member.class, "password", password, Save.class)) {
            return Message.error("shop.common.invalid");
        }
        if (password.length() < setting.getPasswordMinLength()
                || password.length() > setting.getPasswordMaxLength()) {
            return Message.error("shop.common.invalid");
        }
        member.setPassword(DigestUtils.md5Hex(password));
        member.setPoint(setting.getRegisterPoint());
        member.setAmount(new BigDecimal(0));
        member.setBalance(new BigDecimal(0));
        member.setIsEnabled(true);
        member.setIsLocked(false);
        member.setLoginFailureCount(0);
        member.setLockedDate(null);
        member.setRegisterIp(request.getRemoteAddr());
        member.setLoginIp(request.getRemoteAddr());
        member.setLoginDate(new Date());
        member.setSafeKey(null);
        member.setMemberRank(memberRankService.findDefault());
        member.setFavoriteProducts(null);

        member.setUsername(email);// ??
        member.setEmail(email);// 
        member.setRegistStep("1");// ??

        memberService.save(member);
    }
    Cart cart = cartService.getCurrent();
    if (cart != null && cart.getMember() == null) {
        cartService.merge(member, cart);
        WebUtils.removeCookie(request, response, Cart.ID_COOKIE_NAME);
        WebUtils.removeCookie(request, response, Cart.KEY_COOKIE_NAME);
    }

    Map<String, Object> attributes = new HashMap<String, Object>();
    Enumeration<?> keys = session.getAttributeNames();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        attributes.put(key, session.getAttribute(key));
    }
    session.invalidate();
    session = request.getSession();
    for (Entry<String, Object> entry : attributes.entrySet()) {
        session.setAttribute(entry.getKey(), entry.getValue());
    }
    member = memberService.find(member.getId());
    // Message message = new Message();
    // message.setType(Message.Type.success);
    // message.setContent("????");
    // message.setScript(member.getId().toString());
    request.getSession().setAttribute("currentMemberSession", member);
    return Message.success("????");
}