Example usage for javax.servlet.http HttpServletResponse addCookie

List of usage examples for javax.servlet.http HttpServletResponse addCookie

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse addCookie.

Prototype

public void addCookie(Cookie cookie);

Source Link

Document

Adds the specified cookie to the response.

Usage

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

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

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

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

    if (httpReq.getSession(false) == null) {
        chain.doFilter(request, response);
        return;/*  w  ww  . ja  va 2 s  .  c  o  m*/
    }

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

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

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

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

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

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

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

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

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

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

        si.setRefererHost(refHeader);
    }

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

    csrfPreventionSaltCache.put(si, si);

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

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

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

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

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

    chain.doFilter(request, response);
}

From source file:com.salesmanager.core.util.LocaleUtil.java

public static void setLocaleForRequest(HttpServletRequest request, HttpServletResponse response,
        ActionContext ctx, MerchantStore store) throws Exception {

    /**//from   ww w.jav  a 2 s .  c o m
     * LOCALE
     */

    Map sessions = ctx.getSession();

    if (ctx == null) {
        throw new Exception("This request was not made inside Struts request, ActionContext is null");
    }

    Locale locale = null;

    // check in http request
    String req_locale = (String) request.getParameter("request_locale");
    if (!StringUtils.isBlank(req_locale)) {

        String l = null;
        String c = null;

        if (req_locale.length() == 2) {//assume it is the language
            l = req_locale;
            c = CountryUtil.getCountryIsoCodeById(store.getCountry());
        }

        if (req_locale.length() == 5) {

            try {
                l = req_locale.substring(0, 2);
                c = req_locale.substring(3);
            } catch (Exception e) {
                log.warn("Invalid locale format " + req_locale);
                l = null;
                c = null;
            }

        }

        if (l != null && c != null) {

            String storeLang = null;
            Map languages = store.getGetSupportedLanguages();
            if (languages != null && languages.size() > 0) {
                Iterator i = languages.keySet().iterator();
                while (i.hasNext()) {
                    Integer langKey = (Integer) i.next();
                    Language lang = (Language) languages.get(langKey);
                    if (lang.getCode().equals(l)) {
                        storeLang = l;
                        break;
                    }
                }
            }

            if (storeLang == null) {
                l = store.getDefaultLang();
                if (StringUtils.isBlank(l)) {
                    l = LanguageUtil.getDefaultLanguage();
                }
            }

            locale = new Locale(l, c);
            if (StringUtils.isBlank(locale.getLanguage()) || StringUtils.isBlank(locale.getCountry())) {
                log.error("Language or Country is not set in the new locale " + req_locale);
                return;
            }
            sessions.put("WW_TRANS_I18N_LOCALE", locale);

        }
    }

    locale = (Locale) sessions.get("WW_TRANS_I18N_LOCALE");
    request.getSession().setAttribute("WW_TRANS_I18N_LOCALE", locale);

    if (locale == null) {

        String c = CountryUtil.getCountryIsoCodeById(store.getCountry());
        String lang = store.getDefaultLang();
        if (!StringUtils.isBlank(c) && !StringUtils.isBlank(lang)) {
            locale = new Locale(lang, c);
        } else {
            locale = LocaleUtil.getDefaultLocale();
            String langs = store.getSupportedlanguages();
            if (!StringUtils.isBlank(langs)) {
                Map languages = store.getGetSupportedLanguages();
                String defaultLang = locale.getLanguage();
                if (languages != null && languages.size() > 0) {
                    Iterator i = languages.keySet().iterator();
                    String storeLang = "";
                    while (i.hasNext()) {
                        Integer langKey = (Integer) i.next();
                        Language l = (Language) languages.get(langKey);
                        if (l.getCode().equals(defaultLang)) {
                            storeLang = defaultLang;
                            break;
                        }
                    }
                    if (!storeLang.equals(defaultLang)) {
                        defaultLang = storeLang;
                    }
                }

                if (!StringUtils.isBlank(defaultLang) && !StringUtils.isBlank(c)) {
                    locale = new Locale(defaultLang, c);
                }

            }
        }

        sessions.put("WW_TRANS_I18N_LOCALE", locale);
    }

    if (locale != null) {
        LabelUtil label = LabelUtil.getInstance();
        label.setLocale(locale);
        String lang = label.getText("label.language." + locale.getLanguage());
        request.setAttribute("LANGUAGE", lang);
    }

    if (store.getLanguages() == null || store.getLanguages().size() == 0) {

        // languages
        if (!StringUtils.isBlank(store.getSupportedlanguages())) {
            List languages = new ArrayList();
            List langs = LanguageUtil.parseLanguages(store.getSupportedlanguages());
            for (Object o : langs) {
                String lang = (String) o;
                Language l = LanguageUtil.getLanguageByCode(lang);
                if (l != null) {
                    l.setLocale(locale, store.getCurrency());
                    languages.add(l);
                }
            }
            store.setLanguages(languages);
        }
    }

    request.setAttribute("LOCALE", locale);
    Cookie c = new Cookie("LOCALE", locale.getLanguage() + "_" + locale.getCountry());
    c.setPath("/");
    c.setMaxAge(2 * 24 * 24);
    response.addCookie(c);

}

From source file:com.funambol.transport.http.server.Sync4jServlet.java

/**
 * Processes the request/*from  w  w  w .  java 2  s  .c o  m*/
 * @param httpRequest the request
 * @param httpResponse the response
 * @throws javax.servlet.ServletException if an error occurs
 * @throws java.io.IOException if an error occurs
 */
@Override
public void doPost(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    if (log.isInfoEnabled()) {
        log.info("Handling incoming request");
    }

    String requestURL = getRequestURL(httpRequest);
    String sessionId = getSessionId(httpRequest);
    String requestedSessionId = httpRequest.getRequestedSessionId();
    if (log.isInfoEnabled()) {
        log.info("Request URL: " + requestURL);
        log.info("Requested sessionId: " + requestedSessionId);
    }

    if (log.isTraceEnabled()) {
        showHeaders(httpRequest);
    }

    httpResponse.setHeader(HEADER_X_FUNAMBOL_DS_SERVER, getServerHeader());

    if (httpRequest.getSession().isNew()) {
        httpRequest.getSession().setMaxInactiveInterval(sessionTimeout);
        if (requestedSessionId != null && !requestedSessionId.equals("")) {
            if (!sessionId.equalsIgnoreCase(requestedSessionId)) {
                //
                // The client requires a session that maybe is already expired...
                // returing a 408
                //
                if (log.isInfoEnabled()) {
                    log.info("Session '" + requestedSessionId + "' not found");
                }
                httpResponse.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT);
                return;
            }
        }
    }

    long requestTime = System.currentTimeMillis();

    //
    // Setting the header 'Set-Cookie' in order to avoid the session tracking
    // using cookies.
    //
    // The web container adds a cookie JSESSIONID in order to
    // track the session, and to do that, it adds (transparently) in the response
    // header:
    // Set-Cookie: JSESSIONID=xxxxxxxxxx
    // In order not to use the cookie, the header "Set-Cookie" is set to an empty value
    // In this way, the session tracking is based on the jsessionid parameter
    // specified in the url (url rewriting).
    // The cookie is dangerous because a client could use:
    // http://xxxxxx:yyy/funambol/ds
    // but with a jsessionid specified as cookie. In this way, the server
    // search a previous session with the same id. And if a previous session
    // was interrupted and not expired, the server reuses this one and this
    // can cause an exception because the client sends the msg 1 and maybe
    // the previous session was in the mapping state.
    //
    // Unfortunatelly on Nokia S60 3Ed feature pack 1, the JAM is not able to
    // handle the response from the server if it contains an empty header Set-Cookie.
    // This means that to make the JAM working, we must avoid:
    //     httpResponse.setHeader("Set-Cookie", "");
    // and add a dummy cookie.
    // In order to do this in a generic way, we avoid empty Set-Cookie if in
    // the request is specified x-funambol-force-cookies header with value
    // 1 or yes or true
    //
    String x_funambol_force_cookies = httpRequest.getHeader(HEADER_X_FUNAMBOL_FORCE_COOKIES);
    if (!getBooleanValue(x_funambol_force_cookies)) {
        httpResponse.setHeader("Set-Cookie", "");
    } else {
        //
        // Setting a dummy cookie
        //
        Cookie cookie = new Cookie("funambol-dummy-cookie", "");
        httpResponse.addCookie(cookie);
    }

    final String contentType = httpRequest.getContentType().split(";")[0];

    final String contentEncoding = (String) httpRequest.getHeader(HEADER_CONTENT_ENCODING);
    final String sizeThreshold = (String) httpRequest.getHeader(HEADER_SIZE_THRESHOLD);

    String acceptEncoding = (String) httpRequest.getHeader(HEADER_ACCEPT_ENCODING);

    if (!enableCompression) {
        //
        // In this way it's like the client doesn't support any encoding
        //
        if (acceptEncoding != null && acceptEncoding.length() != 0) {
            if (log.isTraceEnabled()) {
                log.trace("Forcing no compression (enable-compression is set to false)");
            }
            acceptEncoding = null;
        }
    }

    Map params = getRequestParameters(httpRequest);
    Map headers = getRequestHeaders(httpRequest);

    byte[] requestData = null;
    try {
        requestData = getRequestContent(httpRequest, contentEncoding, requestTime, sessionId);

        if (requestData == null || requestData.length == 0) {
            handleError(httpRequest, httpResponse,
                    "Received empty content. Returning a BAD REQUEST code to the client.", null);
            return;
        }
    } catch (Exception e) {
        handleError(httpRequest, httpResponse, "Error reading the request", e);
        return;
    }

    //
    // If the session id is not specified in the URL, a new remote object
    // will be created. Otherwise the session id specifies which remote
    // object shall handles the request.
    //
    SyncHolder holder = null;

    try {
        holder = createHolder(httpRequest.getSession());

    } catch (Exception e) {
        handleError(httpRequest, httpResponse, "Error creating SyncBean", e);
        return;
    }

    String remoteAddress = httpRequest.getRemoteAddr();
    //
    // We put the remote address in the header map so that we can pass it to
    // the adapted.
    //
    headers.put(HEADER_X_FUNAMBOL_CLIENT_REMOTE_ADDRESS, remoteAddress);

    SyncResponse resp = null;
    try {
        if (com.funambol.framework.core.Constants.MIMETYPE_SYNCMLDS_WBXML.equals(contentType)) {
            resp = holder.processWBXMLMessage(requestURL, requestData, params, headers);
        } else if (com.funambol.framework.core.Constants.MIMETYPE_SYNCMLDS_XML.equals(contentType)) {
            resp = holder.processXMLMessage(requestURL, requestData, params, headers);
        } else {
            throw new ProtocolException("Mime type " + contentType + " not supported or unknown");
        }
    } catch (Exception e) {
        log.error("Error processing the request", e);

        Throwable cause = e.getCause();

        if ((cause != null) && ((cause instanceof ProtocolException) || (cause instanceof Sync4jException))) {

            handleError(httpRequest, httpResponse, "Protocol error", cause);
            return;
        } else {
            throw new ServletException(e);
        }
    }

    httpResponse.setContentType(contentType);
    setResponseContent(httpResponse, acceptEncoding, sizeThreshold, resp, requestTime, sessionId);

    if (log.isInfoEnabled()) {
        log.info("Request processed.");
    }

    //
    // If the message completed the SyncML communication, the session
    // must be closed and discarded.
    //
    if (resp.isCompleted()) {
        httpRequest.setAttribute(ATTRIBUTE_LAST_REQUEST, "true");
        closeSession(httpRequest.getSession());
    }

}

From source file:nl.nn.adapterframework.http.rest.ApiListenerServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    /**//ww  w. j a  v a 2 s .  c o  m
     * Initiate and populate messageContext
     */
    PipeLineSessionBase messageContext = new PipeLineSessionBase();
    messageContext.put(IPipeLineSession.HTTP_REQUEST_KEY, request);
    messageContext.put(IPipeLineSession.HTTP_RESPONSE_KEY, response);
    messageContext.put(IPipeLineSession.SERVLET_CONTEXT_KEY, getServletContext());
    messageContext.setSecurityHandler(new HttpSecurityHandler(request));

    try {
        String uri = request.getPathInfo();
        String method = request.getMethod().toUpperCase();
        log.trace("ApiListenerServlet dispatching uri [" + uri + "] and method [" + method + "]");

        if (uri == null) {
            response.setStatus(400);
            log.warn("Aborting request with status [400], empty uri");
            return;
        }

        if (uri.startsWith("/"))
            uri = uri.substring(1);
        if (uri.endsWith("/"))
            uri = uri.substring(0, uri.length() - 1);

        ApiDispatchConfig config = dispatcher.findConfigForUri(uri);
        if (config == null) {
            response.setStatus(404);
            log.trace("Aborting request with status [404], no ApiListener configured for [" + uri + "]");
            return;
        }

        /**
         * Handle Cross-Origin Resource Sharing
         * TODO make this work behind loadbalancers/reverse proxies
         * TODO check if request ip/origin header matches allowOrigin property
         */
        String origin = request.getHeader("Origin");
        if (method.equals("OPTIONS") || origin != null) {
            response.setHeader("Access-Control-Allow-Origin", CorsAllowOrigin);
            String headers = request.getHeader("Access-Control-Request-Headers");
            if (headers != null)
                response.setHeader("Access-Control-Allow-Headers", headers);
            response.setHeader("Access-Control-Expose-Headers", CorsExposeHeaders);

            StringBuilder methods = new StringBuilder();
            for (String mtd : config.getMethods()) {
                methods.append(", ").append(mtd);
            }
            response.setHeader("Access-Control-Allow-Methods", methods.toString());

            //Only cut off OPTIONS (aka preflight) requests
            if (method.equals("OPTIONS")) {
                response.setStatus(200);
                log.trace("Aborting preflight request with status [200], method [" + method + "]");
                return;
            }
        }

        /**
         * Get serviceClient
         */
        ApiListener listener = config.getApiListener(method);
        if (listener == null) {
            response.setStatus(405);
            log.trace("Aborting request with status [405], method [" + method + "] not allowed");
            return;
        }

        log.trace("ApiListenerServlet calling service [" + listener.getName() + "]");

        /**
         * Check authentication
         */
        ApiPrincipal userPrincipal = null;

        if (listener.getAuthenticationMethod() != null) {

            String authorizationToken = null;
            Cookie authorizationCookie = null;
            if (listener.getAuthenticationMethod().equals("COOKIE")) {

                Cookie[] cookies = request.getCookies();
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("authenticationToken")) {
                        authorizationToken = cookie.getValue();
                        authorizationCookie = cookie;
                        authorizationCookie.setPath("/");
                    }
                }
            } else if (listener.getAuthenticationMethod().equals("HEADER")) {
                authorizationToken = request.getHeader("Authorization");
            }

            if (authorizationToken != null && cache.containsKey(authorizationToken))
                userPrincipal = (ApiPrincipal) cache.get(authorizationToken);

            if (userPrincipal == null || !userPrincipal.isLoggedIn()) {
                cache.remove(authorizationToken);
                if (authorizationCookie != null) {
                    authorizationCookie.setMaxAge(0);
                    response.addCookie(authorizationCookie);
                }

                response.setStatus(401);
                log.trace("Aborting request with status [401], no (valid) credentials supplied");
                return;
            }

            if (authorizationCookie != null) {
                authorizationCookie.setMaxAge(authTTL);
                response.addCookie(authorizationCookie);
            }
            userPrincipal.updateExpiry();
            userPrincipal.setToken(authorizationToken);
            cache.put(authorizationToken, userPrincipal, authTTL);
            messageContext.put("authorizationToken", authorizationToken);
        }
        messageContext.put("remoteAddr", request.getRemoteAddr());
        messageContext.put(IPipeLineSession.API_PRINCIPAL_KEY, userPrincipal);
        messageContext.put("uri", uri);

        /**
         * Evaluate preconditions
         */
        String accept = request.getHeader("Accept");
        if (accept != null && !accept.isEmpty() && !accept.equals("*/*")) {
            if (!listener.getProduces().equals("ANY") && !accept.contains(listener.getContentType())) {
                response.setStatus(406);
                response.getWriter().print("It appears you expected the MediaType [" + accept
                        + "] but I only support the MediaType [" + listener.getContentType() + "] :)");
                log.trace("Aborting request with status [406], client expects [" + accept + "] got ["
                        + listener.getContentType() + "] instead");
                return;
            }
        }

        if (request.getContentType() != null && !listener.isConsumable(request.getContentType())) {
            response.setStatus(415);
            log.trace("Aborting request with status [415], did not match consumes [" + listener.getConsumes()
                    + "] got [" + request.getContentType() + "] instead");
            return;
        }

        String etagCacheKey = ApiCacheManager.buildCacheKey(uri);
        log.debug("Evaluating preconditions for listener[" + listener.getName() + "] etagKey[" + etagCacheKey
                + "]");
        if (cache.containsKey(etagCacheKey)) {
            String cachedEtag = (String) cache.get(etagCacheKey);
            log.debug("found etag value[" + cachedEtag + "] for key[" + etagCacheKey + "]");

            if (method.equals("GET")) {
                String ifNoneMatch = request.getHeader("If-None-Match");
                if (ifNoneMatch != null && ifNoneMatch.equals(cachedEtag)) {
                    response.setStatus(304);
                    log.trace(
                            "Aborting request with status [304], matched if-none-match [" + ifNoneMatch + "]");
                    return;
                }
            } else {
                String ifMatch = request.getHeader("If-Match");
                if (ifMatch != null && !ifMatch.equals(cachedEtag)) {
                    response.setStatus(412);
                    log.trace("Aborting request with status [412], matched if-match [" + ifMatch + "] method ["
                            + method + "]");
                    return;
                }
            }
        }
        messageContext.put("updateEtag", listener.getUpdateEtag());

        /**
         * Check authorization
         */
        //TODO: authentication implementation

        /**
         * Map uriIdentifiers into messageContext 
         */
        String patternSegments[] = listener.getUriPattern().split("/");
        String uriSegments[] = uri.split("/");
        int uriIdentifier = 0;
        for (int i = 0; i < patternSegments.length; i++) {
            String segment = patternSegments[i];
            if (segment.startsWith("{") && segment.endsWith("}")) {
                String name;
                if (segment.equals("*"))
                    name = "uriIdentifier_" + uriIdentifier;
                else
                    name = segment.substring(1, segment.length() - 1);

                uriIdentifier++;
                log.trace("setting uriSegment [" + name + "] to [" + uriSegments[i] + "]");
                messageContext.put(name, uriSegments[i]);
            }
        }

        /**
         * Map queryParameters into messageContext
         */
        Enumeration<?> paramnames = request.getParameterNames();
        while (paramnames.hasMoreElements()) {
            String paramname = (String) paramnames.nextElement();
            String paramvalue = request.getParameter(paramname);

            log.trace("setting queryParameter [" + paramname + "] to [" + paramvalue + "]");
            messageContext.put(paramname, paramvalue);
        }

        /**
         * Map multipart parts into messageContext
         */
        if (ServletFileUpload.isMultipartContent(request)) {
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            List<FileItem> items = servletFileUpload.parseRequest(request);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();
                    log.trace("setting multipart formField [" + fieldName + "] to [" + fieldValue + "]");
                    messageContext.put(fieldName, fieldValue);
                } else {
                    // Process form file field (input type="file").
                    String fieldName = item.getFieldName();
                    String fieldNameName = fieldName + "Name";
                    String fileName = FilenameUtils.getName(item.getName());
                    log.trace("setting multipart formFile [" + fieldNameName + "] to [" + fileName + "]");
                    messageContext.put(fieldNameName, fileName);
                    log.trace(
                            "setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]");
                    messageContext.put(fieldName, item.getInputStream());
                }
            }
        }

        /**
         * Compile Allow header
         */
        StringBuilder methods = new StringBuilder();
        methods.append("OPTIONS, ");
        for (String mtd : config.getMethods()) {
            methods.append(mtd + ", ");
        }
        messageContext.put("allowedMethods", methods.substring(0, methods.length() - 2));

        /**
         * Process the request through the pipeline
         */

        String body = "";
        if (!ServletFileUpload.isMultipartContent(request)) {
            body = Misc.streamToString(request.getInputStream(), "\n", false);
        }
        String result = listener.processRequest(null, body, messageContext);

        /**
         * Calculate an eTag over the processed result and store in cache
         */
        if (messageContext.get("updateEtag", true)) {
            log.debug("calculating etags over processed result");
            String cleanPattern = listener.getCleanPattern();
            if (result != null && method.equals("GET")) {
                String eTag = ApiCacheManager.buildEtag(cleanPattern, result.hashCode());
                log.debug("adding/overwriting etag with key[" + etagCacheKey + "] value[" + eTag + "]");
                cache.put(etagCacheKey, eTag);
                response.addHeader("etag", eTag);
            } else {
                log.debug("removing etag with key[" + etagCacheKey + "]");
                cache.remove(etagCacheKey);

                // Not only remove the eTag for the selected resources but also the collection
                String key = ApiCacheManager.getParentCacheKey(listener, uri);
                if (key != null) {
                    log.debug("removing parent etag with key[" + key + "]");
                    cache.remove(key);
                }
            }
        }

        /**
         * Add headers
         */
        response.addHeader("Allow", (String) messageContext.get("allowedMethods"));

        String contentType = listener.getContentType() + "; charset=utf-8";
        if (listener.getProduces().equals("ANY")) {
            contentType = messageContext.get("contentType", contentType);
        }
        response.setHeader("Content-Type", contentType);

        /**
         * Check if an exitcode has been defined or if a statuscode has been added to the messageContext.
         */
        int statusCode = messageContext.get("exitcode", 0);
        if (statusCode > 0)
            response.setStatus(statusCode);

        /**
         * Finalize the pipeline and write the result to the response
         */
        if (result != null)
            response.getWriter().print(result);
        log.trace("ApiListenerServlet finished with statusCode [" + statusCode + "] result [" + result + "]");
    } catch (Exception e) {
        log.warn("ApiListenerServlet caught exception, will rethrow as ServletException", e);
        try {
            response.flushBuffer();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (IllegalStateException ex) {
            //We're only informing the end user(s), no need to catch this error...
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:contestWebsite.MainPage.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets, html/templates");
    ve.init();/*from  w w w  .j a  v a2  s. co m*/
    VelocityContext context = new VelocityContext();
    Pair<Entity, UserCookie> infoAndCookie = init(context, req);

    UserCookie userCookie = infoAndCookie.y;
    Entity user = userCookie != null ? userCookie.authenticateUser() : null;
    boolean loggedIn = (boolean) context.get("loggedIn");

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    if (loggedIn && !userCookie.isAdmin()) {
        Entity contestInfo = infoAndCookie.x;
        String endDateStr = (String) contestInfo.getProperty("editEndDate");
        String startDateStr = (String) contestInfo.getProperty("editStartDate");

        Date endDate = new Date();
        Date startDate = new Date();
        try {
            endDate = new SimpleDateFormat("MM/dd/yyyy").parse(endDateStr);
            startDate = new SimpleDateFormat("MM/dd/yyyy").parse(startDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Incorrect date format");
        }

        if (new Date().after(endDate) || new Date().before(startDate)) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Registration editing deadline passed.");
        } else {
            Query query = new Query("registration")
                    .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, user.getProperty("user-id")));
            Entity registration = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)).get(0);

            String studentData = req.getParameter("studentData");

            JSONArray regData = null;
            try {
                regData = new JSONArray(studentData);
            } catch (JSONException e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                return;
            }

            long price = (Long) infoAndCookie.x.getProperty("price");
            int cost = (int) (0 * price);

            for (int i = 0; i < regData.length(); i++) {
                try {
                    JSONObject studentRegData = regData.getJSONObject(i);
                    for (Subject subject : Subject.values()) {
                        cost += price * (studentRegData.getBoolean(subject.toString()) ? 1 : 0);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                    return;
                }
            }

            registration.setProperty("cost", cost);
            registration.setProperty("studentData", new Text(studentData));

            Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
            try {
                datastore.put(registration);
                txn.commit();
            } catch (Exception e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            } finally {
                if (txn.isActive()) {
                    txn.rollback();
                }
            }

            resp.sendRedirect("/?updated=1");
        }
    } else if (loggedIn && userCookie.isAdmin()) {
        String username = req.getParameter("email").toLowerCase();
        Query query = new Query("user")
                .setFilter(new FilterPredicate("user-id", FilterOperator.EQUAL, username));
        List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1));
        if (users.size() >= 1) {
            Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
            try {
                query = new Query("authToken").setKeysOnly();
                Filter tokenFilter = new FilterPredicate("token", FilterOperator.EQUAL,
                        URLDecoder.decode(userCookie.getValue(), "UTF-8"));
                Filter expiredFilter = new FilterPredicate("expires", FilterOperator.LESS_THAN, new Date());
                query.setFilter(CompositeFilterOperator.or(tokenFilter, expiredFilter));
                datastore.delete(
                        datastore.prepare(query).asList(FetchOptions.Builder.withDefaults()).get(0).getKey());

                userCookie.setMaxAge(0);
                userCookie.setValue("");
                resp.addCookie(userCookie);

                SecureRandom random = new SecureRandom();
                String authToken = new BigInteger(130, random).toString(32);
                Entity token = new Entity("authToken");
                token.setProperty("user-id", username);
                token.setProperty("token", authToken);

                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MINUTE, 60);
                token.setProperty("expires", new Date(calendar.getTimeInMillis()));

                Cookie cookie = new Cookie("authToken", authToken);
                cookie.setValue(authToken);
                resp.addCookie(cookie);

                datastore.put(token);
                datastore.put(user);
                resp.sendRedirect("/");

                txn.commit();
            } catch (Exception e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            } finally {
                if (txn.isActive()) {
                    txn.rollback();
                }
            }
        } else {
            resp.sendRedirect("/?error=1");
        }
    } else {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User account required for that operation");
    }
}

From source file:de.tu_dortmund.ub.api.paia.core.PaiaCoreEndpoint.java

/**
 *
 * @param httpServletRequest//from  w ww.j  av a2s  . com
 * @param httpServletResponse
 * @throws IOException
 */
private void authorize(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String format, DocumentList documents) throws IOException {

    httpServletResponse.setHeader("Access-Control-Allow-Origin",
            config.getProperty("Access-Control-Allow-Origin"));
    httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control"));

    ObjectMapper mapper = new ObjectMapper();

    // Error handling mit suppress_response_codes=true
    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    }
    // Error handling mit suppress_response_codes=false (=default)
    else {
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }

    // Json fr Response body
    RequestError requestError = new RequestError();
    requestError.setError(
            this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED)));
    requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED);
    requestError.setDescription(this.config
            .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description"));
    requestError.setErrorUri(
            this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri"));

    // XML-Ausgabe mit JAXB
    if (format.equals("xml")) {

        try {

            JAXBContext context = JAXBContext.newInstance(RequestError.class);
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            // Write to HttpResponse
            httpServletResponse.setContentType("application/xml;charset=UTF-8");
            m.marshal(requestError, httpServletResponse.getWriter());

        } catch (JAXBException e) {
            this.logger.error(e.getMessage(), e.getCause());
            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Internal Server Error: Error while rendering the results.");
        }
    }

    // JSON-Ausgabe mit Jackson
    if (format.equals("json")) {

        httpServletResponse.setContentType("application/json;charset=UTF-8");
        mapper.writeValue(httpServletResponse.getWriter(), requestError);
    }

    // html > redirect zu "PAIA auth - login" mit redirect_url = "PAIA core - service"
    if (format.equals("html")) {

        httpServletResponse.setContentType("text/html;charset=UTF-8");

        if (documents != null) {
            // set Cookie with urlencoded DocumentList-JSON
            StringWriter stringWriter = new StringWriter();
            mapper.writeValue(stringWriter, documents);
            Cookie cookie = new Cookie("PaiaServiceDocumentList",
                    URLEncoder.encode(stringWriter.toString(), "UTF-8"));
            if (this.config.getProperty("service.cookie.domain") != null
                    && !this.config.getProperty("service.cookie.domain").equals("")) {
                cookie.setDomain(this.config.getProperty("service.cookie.domain"));
            }
            cookie.setMaxAge(-1);
            cookie.setPath("/");
            httpServletResponse.addCookie(cookie);
        }

        //String redirect_url = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.core") + httpServletRequest.getPathInfo();
        String redirect_url = this.config.getProperty("service.base_url")
                + this.config.getProperty("service.endpoint.core") + httpServletRequest.getPathInfo();
        if (httpServletRequest.getQueryString() != null && !httpServletRequest.getQueryString().equals("")) {
            redirect_url += "?" + httpServletRequest.getQueryString();
        }
        this.logger.info("redirect_url = " + redirect_url);

        //String login_url = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.auth") + "/login?redirect_url=" + redirect_url;
        String login_url = this.config.getProperty("service.base_url")
                + this.config.getProperty("service.endpoint.auth") + "/login?redirect_url=" + redirect_url;
        this.logger.info("login_url = " + login_url);

        httpServletResponse.sendRedirect(login_url);
    }
}

From source file:ai.susi.server.api.aaa.LoginService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JsonObjectWithDefault permissions) throws APIException {

    // login check for app
    if (post.get("checkLogin", false)) {
        JSONObject result = new JSONObject();
        if (authorization.getIdentity().isEmail()) {
            result.put("loggedIn", true);
            result.put("message", "You are logged in as " + authorization.getIdentity().getName());
        } else {// ww w . j a  va  2s  .co m
            result.put("loggedIn", false);
            result.put("message", "Not logged in");
        }
        return result;
    }

    // do logout if requested
    boolean logout = post.get("logout", false);
    boolean delete = post.get("delete", false);
    if (logout || delete) { // logout if requested

        // invalidate session
        post.getRequest().getSession().invalidate();

        // delete cookie if set
        deleteLoginCookie(response);

        if (delete) {
            ClientCredential pwcredential = new ClientCredential(authorization.getIdentity());
            delete = DAO.authentication.has(pwcredential.toString());
            if (delete)
                DAO.authentication.remove(pwcredential.toString());
        }

        JSONObject result = new JSONObject();
        result.put("message", delete ? "Account deletion successful" : "Logout successful");
        return result;
    }

    // check login type by checking which parameters are set
    boolean passwordLogin = false;
    boolean pubkeyHello = false;
    boolean pubkeyLogin = false;

    if (post.get("login", null) != null && post.get("password", null) != null
            && post.get("type", null) != null) {
        passwordLogin = true;
    } else if (post.get("login", null) != null && post.get("keyhash", null) != null) {
        pubkeyHello = true;
    } else if (post.get("sessionID", null) != null && post.get("response", null) != null) {
        pubkeyLogin = true;
    } else {
        throw new APIException(400, "Bad login parameters.");
    }

    // check if user is blocked because of too many invalid login attempts
    checkInvalidLogins(post, authorization, permissions);

    if (passwordLogin) { // do login via password

        String login = post.get("login", null);
        String password = post.get("password", null);
        String type = post.get("type", null);
        ClientCredential pwcredential = new ClientCredential(ClientCredential.Type.passwd_login, login);
        Authentication authentication = getAuthentication(post, authorization, pwcredential);
        ClientIdentity identity = authentication.getIdentity();

        // check if the password is valid
        String passwordHash;
        String salt;
        try {
            passwordHash = authentication.getString("passwordHash");
            salt = authentication.getString("salt");
        } catch (Throwable e) {
            Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: "
                    + post.getClientHost() + " : password or salt missing in database");
            throw new APIException(422, "Invalid credentials");
        }

        if (!passwordHash.equals(getHash(password, salt))) {

            // save invalid login in accounting object
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");

            Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: "
                    + post.getClientHost());
            throw new APIException(422, "Invalid credentials");
        }

        JSONObject result = new JSONObject();

        switch (type) {
        case "session": // create a browser session
            post.getRequest().getSession().setAttribute("identity", identity);
            break;
        case "cookie": // set a long living cookie
            // create random string as token
            String loginToken = createRandomString(30);

            // create cookie
            Cookie loginCookie = new Cookie("login", loginToken);
            loginCookie.setPath("/");
            loginCookie.setMaxAge(defaultCookieTime.intValue());

            // write cookie to database
            ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken);
            JSONObject user_obj = new JSONObject();
            user_obj.put("id", identity.toString());
            user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime);
            DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent());

            response.addCookie(loginCookie);
            break;
        case "access-token": // create and display an access token

            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);

            break;
        default:
            throw new APIException(400, "Invalid type");
        }

        Log.getLog().info(
                "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost());

        result.put("message", "You are logged in as " + identity.getName());
        return result;
    } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge

        String login = post.get("login", null);
        String keyHash = post.get("keyhash", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.passwd_login, login));
        ClientIdentity identity = authentication.getIdentity();

        if (!DAO.login_keys.has(identity.toString())
                || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash))
            throw new APIException(400, "Unknown key");

        String challengeString = createRandomString(30);
        String newSessionID = createRandomString(30);

        ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange,
                newSessionID);
        Authentication challenge_auth = new Authentication(credential, DAO.authentication);
        challenge_auth.setIdentity(identity);
        challenge_auth.put("activated", true);

        challenge_auth.put("challenge", challengeString);
        challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash));
        challenge_auth.setExpireTime(60 * 10);

        JSONObject result = new JSONObject();
        result.put("challenge", challengeString);
        result.put("sessionID", newSessionID);
        result.put("message",
                "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID");
        return result;
    } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid

        String sessionID = post.get("sessionID", null);
        String challangeResponse = post.get("response", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID));
        ClientIdentity identity = authentication.getIdentity();

        String challenge = authentication.getString("challenge");
        PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA");

        Signature sig;
        boolean verified;
        try {
            sig = Signature.getInstance("SHA256withRSA");
            sig.initVerify(key);
            sig.update(challenge.getBytes());
            verified = sig.verify(Base64.getDecoder().decode(challangeResponse));
        } catch (NoSuchAlgorithmException e) {
            throw new APIException(400, "No such algorithm");
        } catch (InvalidKeyException e) {
            throw new APIException(400, "Invalid key");
        } catch (Throwable e) {
            throw new APIException(400, "Bad signature");
        }

        if (verified) {
            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            JSONObject result = new JSONObject();

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);
            return result;
        } else {
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");
            throw new APIException(400, "Bad Signature");
        }
    }
    throw new APIException(500, "Server error");
}

From source file:egovframework.example.sample.web.EgovSampleController.java

@RequestMapping(value = "/login.do", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {

    String id = request.getParameter("id");
    String pw = request.getParameter("pw");

    Account ac = new Account();
    ac.setA_id(id);/*www. ja v  a  2 s .c o  m*/
    int IDCheck = sampleService.joinIdCheck(ac);

    if (IDCheck == 0) {//?  
        request.setAttribute("color", "red");
        request.setAttribute("Result", " ID.");
        model.addAttribute("login", "login.jsp");
    } else {
        Account ac2 = sampleService.getAccount(ac);
        String dBpass = ac2.getA_pw();

        System.out.println(pw + "<<  DB>>" + dBpass);
        if (pw.equals(dBpass)) {//? ?
            System.out.println(" ?");
            HttpSession hs = request.getSession();
            hs.setAttribute("userInfo", ac2);
            hs.setMaxInactiveInterval(1 * 60 * 60); //?   (1)

            // ?? ID 
            Cookie c = new Cookie("lastLoginID", id);
            c.setMaxAge(1 * 60 * 60);//  (1)
            response.addCookie(c);

            model.addAttribute("login", "loginOK.jsp");

        } else {//  
            System.out.println(" ");
            request.setAttribute("color", "red");
            request.setAttribute("Result", " .");
            model.addAttribute("login", "login.jsp");
        }

    }

    //model.addAttribute("main", "defaultMain.jsp");
    return "forward:/home.do";
}