Example usage for javax.servlet.http HttpServletRequest isSecure

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

Introduction

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

Prototype

public boolean isSecure();

Source Link

Document

Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.

Usage

From source file:com.comcast.cdn.traffic_control.traffic_router.core.request.HTTPRequest.java

public void applyRequest(final HttpServletRequest request) {
    setClientIP(request.getRemoteAddr());
    setPath(request.getPathInfo());/*from  ww w.jav a 2  s.c om*/
    setQueryString(request.getQueryString());
    setHostname(request.getServerName());
    setRequestedUrl(request.getRequestURL().toString());
    setUri(request.getRequestURI());

    final String xmm = request.getHeader(X_MM_CLIENT_IP);
    final String fip = request.getParameter(FAKE_IP);

    if (xmm != null) {
        setClientIP(xmm);
    } else if (fip != null) {
        setClientIP(fip);
    }

    final Map<String, String> headers = new HashMap<String, String>();
    final Enumeration<?> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String name = (String) headerNames.nextElement();
        final String value = request.getHeader(name);
        headers.put(name, value);
    }
    setHeaders(headers);
    secure = request.isSecure();
}

From source file:com.zimbra.cs.service.AutoDiscoverServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String userAgent = req.getHeader("User-Agent");
    if (userAgent != null && (userAgent.contains("PocketPC") || userAgent.contains("SmartPhone"))) {
        if (log.isDebugEnabled()) {
            Enumeration<String> enm = req.getHeaderNames();
            while (enm.hasMoreElements()) {
                String header = enm.nextElement();
                log.debug("GET header: %s", header + ":" + req.getHeader(header));
            }//w ww .java  2  s  .  c o  m
        }
        if (req.isSecure()) {
            Account acct = authenticate(req, resp, NS_MOBILE);
            if (acct == null) {
                return;
            }
        } else {
            resp.sendRedirect(LC.zimbra_activesync_autodiscover_url.value());
        }
    }
}

From source file:com.liferay.portal.util.HttpImpl.java

public String getProtocol(HttpServletRequest request) {
    return getProtocol(request.isSecure());
}

From source file:com.liferay.portal.util.HttpImpl.java

public String protocolize(String url, HttpServletRequest request) {
    return protocolize(url, request.isSecure());
}

From source file:ru.org.linux.comment.EditCommentController.java

/**
 *  ?./*from  w  w w.  j  ava  2s.c o m*/
 *
 * @param commentRequest WEB-, ?? 
 * @param errors            ? 
 * @param request         ?  web-
 * @return  web-
 * @throws Exception
 */
@RequestMapping(value = "/edit_comment", method = RequestMethod.POST)
@CSRFNoAuto
public ModelAndView editCommentPostHandler(@ModelAttribute("edit") @Valid CommentRequest commentRequest,
        Errors errors, HttpServletRequest request, @ModelAttribute("ipBlockInfo") IPBlockInfo ipBlockInfo)
        throws Exception {
    Map<String, Object> formParams = new HashMap<>();

    User user = commentService.getCommentUser(commentRequest, request, errors);

    commentService.checkPostData(commentRequest, user, ipBlockInfo, request, errors);
    commentService.prepareReplyto(commentRequest, formParams, request);

    String msg = commentService.getCommentBody(commentRequest, user, errors);
    Comment comment = commentService.getComment(commentRequest, user, request);

    if (commentRequest.getTopic() != null) {
        formParams.put("postscoreInfo",
                TopicPermissionService.getPostScoreInfo(commentRequest.getTopic().getPostScore()));
        topicPermissionService.checkCommentsAllowed(commentRequest.getTopic(), user, errors);
        formParams.put("comment",
                commentPrepareService.prepareCommentForEdit(comment, msg, request.isSecure()));
    }

    boolean editable = topicPermissionService.isCommentsEditingAllowed(commentRequest.getOriginal(),
            commentRequest.getTopic(), request);

    if (!editable) {
        throw new AccessViolationException(
                " ?     ? ??");
    }

    if (commentRequest.isPreviewMode() || errors.hasErrors() && comment == null) {
        ModelAndView modelAndView = new ModelAndView("edit_comment", formParams);
        modelAndView.addObject("ipBlockInfo", ipBlockInfo);
        return modelAndView;
    }

    String originalMessageText = msgbaseDao.getMessageText(commentRequest.getOriginal().getId()).getText();

    commentService.edit(commentRequest.getOriginal(), comment, msg, request.getRemoteAddr(),
            request.getHeader("X-Forwarded-For"));
    searchQueueSender.updateComment(commentRequest.getOriginal().getId());

    commentService.addEditHistoryItem(user, commentRequest.getOriginal(), originalMessageText, comment, msg);
    commentService.updateLatestEditorInfo(user, commentRequest.getOriginal(), comment);

    String returnUrl = "/jump-message.jsp?msgid=" + commentRequest.getTopic().getId() + "&cid="
            + commentRequest.getOriginal().getId();

    return new ModelAndView(new RedirectView(returnUrl));
}

From source file:gov.nih.nci.security.upt.actions.LoginAction.java

public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();

    AuthenticationManager authenticationManager = null;
    AuthorizationManager authorizationManager = null;
    UserProvisioningManager userProvisioningManager = null;
    boolean loginSuccessful = false;
    boolean hasPermission = false;
    String uptContextName = DisplayConstants.UPT_CONTEXT_NAME;
    Application application = null;//  ww w .  j av a2 s.  c o  m

    String serverInfoPathPort = (request.isSecure() ? "https://" : "http://") + request.getServerName() + ":"
            + request.getServerPort();
    ObjectFactory.initialize("upt-beans.xml");
    UPTProperties uptProperties = null;
    String urlContextForLoginApp = "";
    String centralUPTConfiguration = "";
    try {
        uptProperties = (UPTProperties) ObjectFactory.getObject("UPTProperties");
        urlContextForLoginApp = uptProperties.getBackwardsCompatibilityInformation()
                .getLoginApplicationContextName();
        if (!StringUtils.isBlank(urlContextForLoginApp)) {
            serverInfoPathPort = serverInfoPathPort + "/" + urlContextForLoginApp + "/";
        } else {
            serverInfoPathPort = serverInfoPathPort + "/" + DisplayConstants.LOGIN_APPLICATION_CONTEXT_NAME
                    + "/";
        }
        uptContextName = DisplayConstants.UPT_AUTHENTICATION_CONTEXT_NAME;
    } catch (UPTConfigurationException e) {
        serverInfoPathPort = serverInfoPathPort + "/" + DisplayConstants.LOGIN_APPLICATION_CONTEXT_NAME + "/";

    }

    if (loginForm == null) {
        loginForm = new LoginForm();
        loginForm.setApplicationContextName(applicationContextName);
        loginForm.setLoginId(loginId);
        loginForm.setPassword(password);
    }

    if (StringUtils.isBlank(loginForm.getApplicationContextName())
            || StringUtils.isBlank(loginForm.getLoginId()) || StringUtils.isBlank(loginForm.getPassword())) {

        redirectAction = serverInfoPathPort;
        return "redirect";
    }

    UserInfoHelper.setUserInfo(loginForm.getLoginId(), request.getSession().getId());
    clearActionErrors();

    try {
        authorizationManager = SecurityServiceProvider.getAuthorizationManager(uptContextName);
        if (null == authorizationManager) {
            addActionError(
                    "Unable to initialize Authorization Manager for the given application context using new configuration");
            if (log.isDebugEnabled())
                log.debug("|" + loginForm.getLoginId()
                        + "||Login|Failure|Unable to instantiate Authorization Manager for UPT application using new configuration||");
            return ForwardConstants.LOGIN_FAILURE;
        }
    } catch (CSException cse) {

        authorizationManager = null;
    }

    if (null == authorizationManager) {

        try {

            if (null == uptContextName || uptContextName.equalsIgnoreCase("")) {
                addActionError("Unable to read the UPT Context Name from Security Config File");
                if (log.isDebugEnabled())
                    log.debug("|" + loginForm.getLoginId()
                            + "||Login|Failure|Unable to read the UPT Context Name from Security Config File");
                return ForwardConstants.LOGIN_FAILURE;
            }
        } catch (Exception ex) {
            addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(ex.getMessage()));
            if (log.isDebugEnabled())
                log.debug("|" + loginForm.getLoginId()
                        + "||Login|Failure|Unable to read the UPT Context Name from Security Config File||");
            return ForwardConstants.LOGIN_FAILURE;
        }
    }
    try {

        authenticationManager = SecurityServiceProvider
                .getAuthenticationManager(DisplayConstants.UPT_AUTHENTICATION_CONTEXT_NAME);
        if (null == authenticationManager) {
            addActionError("Unable to initialize Authentication Manager for the given application context");
            if (log.isDebugEnabled())
                log.debug("|" + loginForm.getLoginId()
                        + "||Login|Failure|Unable to instantiate AuthenticationManager for UPT application||");
            return ForwardConstants.LOGIN_FAILURE;
        }
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId()
                    + "||Login|Failure|Unable to instantiate AuthenticationManager for UPT application|"
                    + loginForm.toString() + "|" + cse.getMessage());
        return ForwardConstants.LOGIN_FAILURE;
    }
    try {
        loginSuccessful = authenticationManager.login(loginForm.getLoginId(), loginForm.getPassword());
    } catch (CSCredentialExpiredException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId() + "||Login|Failure|Password Expired for user name "
                    + loginForm.getLoginId() + " and" + loginForm.getApplicationContextName() + " application|"
                    + loginForm.toString() + "|" + cse.getMessage());
        return ForwardConstants.EXPIRED_PASSWORD;
    } catch (CSFirstTimeLoginException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId() + "||Login|Failure|Password Expired for user name "
                    + loginForm.getLoginId() + " and" + loginForm.getApplicationContextName() + " application|"
                    + loginForm.toString() + "|" + cse.getMessage());
        return ForwardConstants.EXPIRED_PASSWORD;
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId() + "||Login|Failure|Login Failed for user name "
                    + loginForm.getLoginId() + " and" + loginForm.getApplicationContextName() + " application|"
                    + loginForm.toString() + "|" + cse.getMessage());
        return ForwardConstants.LOGIN_FAILURE;
    }

    try {
        authorizationManager = SecurityServiceProvider.getAuthorizationManager(uptContextName);
        if (null == authorizationManager) {
            addActionError("Unable to initialize Authorization Manager for the given application context");
            if (log.isDebugEnabled())
                log.debug("|" + loginForm.getLoginId()
                        + "||Login|Failure|Unable to instantiate Authorization Manager for UPT application||");
            return ForwardConstants.LOGIN_FAILURE;
        }
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId()
                    + "||Login|Failure|Unable to instantiate AuthorizationManager for UPT application|"
                    + loginForm.toString() + "|" + cse.getMessage());
        return ForwardConstants.LOGIN_FAILURE;
    }
    try {
        hasPermission = authorizationManager.checkPermission(loginForm.getLoginId(),
                loginForm.getApplicationContextName(), null);
        if (!hasPermission) {
            try {
                userProvisioningManager = getUserProvisioningManager(authorizationManager,
                        loginForm.getApplicationContextName());
                if (null == userProvisioningManager) {
                    addActionError(
                            "Unable to initialize Authorization Manager for the given application context");
                    if (log.isDebugEnabled())
                        log.debug("|" + loginForm.getLoginId()
                                + "||Login|Failure|Unable to instantiate User Provisioning Manager for "
                                + loginForm.getApplicationContextName() + " application||");
                    return ForwardConstants.LOGIN_FAILURE;
                }
            } catch (CSException cse) {
                addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
                if (log.isDebugEnabled())
                    log.debug("|" + loginForm.getLoginId()
                            + "||Login|Failure|Unable to instantiate User Provisioning Manager for |"
                            + loginForm.toString() + "|" + cse.getMessage());
                return ForwardConstants.LOGIN_FAILURE;
            }
            sessionMap.put(DisplayConstants.USER_PROVISIONING_MANAGER, userProvisioningManager);
            sessionMap.put(DisplayConstants.LOGIN_OBJECT, loginForm);
            sessionMap.put(DisplayConstants.CURRENT_TABLE_ID, DisplayConstants.HOME_ID);

            sessionMap.put(Constants.UPT_USER_OPERATION + "_" + Constants.CSM_ACCESS_PRIVILEGE, "false");
            sessionMap.put(Constants.UPT_PROTECTION_ELEMENT_OPERATION + "_" + Constants.CSM_ACCESS_PRIVILEGE,
                    "false");
            sessionMap.put(Constants.UPT_PRIVILEGE_OPERATION + "_" + Constants.CSM_ACCESS_PRIVILEGE, "false");
            sessionMap.put(Constants.UPT_GROUP_OPERATION + "_" + Constants.CSM_ACCESS_PRIVILEGE, "false");
            sessionMap.put(Constants.UPT_PROTECTION_GROUP_OPERATION + "_" + Constants.CSM_ACCESS_PRIVILEGE,
                    "false");
            sessionMap.put(Constants.UPT_ROLE_OPERATION + "_" + Constants.CSM_ACCESS_PRIVILEGE, "false");
            sessionMap.put(Constants.UPT_INSTANCE_LEVEL_OPERATION + "_" + Constants.CSM_ACCESS_PRIVILEGE,
                    "false");

            return ForwardConstants.LOGIN_SUCCESS;
        }
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId() + "||Login|Failure|Error in checking permission|"
                    + loginForm.toString() + "|" + cse.getMessage());
        return ForwardConstants.LOGIN_FAILURE;
    }

    try {
        //UserProvisioningManager upm = (UserProvisioningManager)authorizationManager;
        application = authorizationManager.getApplication(loginForm.getApplicationContextName());
        userProvisioningManager = getUserProvisioningManager(authorizationManager,
                loginForm.getApplicationContextName());
        if (null == userProvisioningManager) {
            addActionError("Unable to initialize Authorization Manager for the given application context");
            if (log.isDebugEnabled())
                log.debug("|" + loginForm.getLoginId()
                        + "||Login|Failure|Unable to instantiate User Provisioning Manager for "
                        + loginForm.getApplicationContextName() + " application||");
            return ForwardConstants.LOGIN_FAILURE;
        }
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId()
                    + "||Login|Failure|Unable to instantiate User Provisioning Manager for |"
                    + loginForm.toString() + "|" + cse.getMessage());
        return ForwardConstants.LOGIN_FAILURE;
    }

    sessionMap.put(DisplayConstants.USER_PROVISIONING_MANAGER, userProvisioningManager);
    sessionMap.put(DisplayConstants.LOGIN_OBJECT, loginForm);
    sessionMap.put(DisplayConstants.CURRENT_TABLE_ID, DisplayConstants.HOME_ID);

    authenticationManager = null;
    authorizationManager = null;

    try {
        processUptOperation(userProvisioningManager, loginForm.getLoginId(), application.getApplicationName());
    } catch (CSTransactionException e) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(e.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId()
                    + "||Login|Failure|Unable to check permissions for the user operations |"
                    + loginForm.toString() + "|" + e.getMessage());
        return ForwardConstants.LOGIN_FAILURE;
    }

    if (loginForm.getApplicationContextName().equalsIgnoreCase(uptContextName)) {
        sessionMap.put(DisplayConstants.ADMIN_USER, DisplayConstants.ADMIN_USER);
        if (log.isDebugEnabled())
            log.debug(request.getSession().getId() + "|"
                    + ((LoginForm) sessionMap.get(DisplayConstants.LOGIN_OBJECT)).getLoginId()
                    + "||Login|Success|Login Successful for user " + loginForm.getLoginId() + " and "
                    + loginForm.getApplicationContextName()
                    + " application, Forwarding to the Super Admin Home Page||");
        return ForwardConstants.ADMIN_LOGIN_SUCCESS;
    } else {
        if (log.isDebugEnabled())
            log.debug(request.getSession().getId() + "|"
                    + ((LoginForm) sessionMap.get(DisplayConstants.LOGIN_OBJECT)).getLoginId()
                    + "||Login|Success|Login Successful for user " + loginForm.getLoginId() + " and "
                    + loginForm.getApplicationContextName() + " application, Forwarding to the Home Page||");
        return ForwardConstants.LOGIN_SUCCESS;
    }
}

From source file:org.codice.ddf.security.idp.server.IdpEndpoint.java

@GET
@Path("/login/sso")
public Response processLogin(@QueryParam(SAML_REQ) String samlRequest,
        @QueryParam(RELAY_STATE) String relayState, @QueryParam(AUTH_METHOD) String authMethod,
        @QueryParam(SSOConstants.SIG_ALG) String signatureAlgorithm,
        @QueryParam(SSOConstants.SIGNATURE) String signature,
        @QueryParam(ORIGINAL_BINDING) String originalBinding, @Context HttpServletRequest request) {
    LOGGER.debug("Processing login request: [ authMethod {} ], [ sigAlg {} ], [ relayState {} ]", authMethod,
            signatureAlgorithm, relayState);
    try {/*www .  j  ava  2  s .  c  o  m*/
        Binding binding;
        String template;
        if (!request.isSecure()) {
            throw new IllegalArgumentException("Authn Request must use TLS.");
        }
        //the authn request is always encoded as if it came in via redirect when coming from the web app
        Binding redirectBinding = new RedirectBinding(systemCrypto, serviceProviders);
        AuthnRequest authnRequest = redirectBinding.decoder().decodeRequest(samlRequest);
        String assertionConsumerServiceBinding = ResponseCreator
                .getAssertionConsumerServiceBinding(authnRequest, serviceProviders);
        if (HTTP_POST_BINDING.equals(originalBinding)) {
            binding = new PostBinding(systemCrypto, serviceProviders);
            template = submitForm;
        } else if (HTTP_REDIRECT_BINDING.equals(originalBinding)) {
            binding = redirectBinding;
            template = redirectPage;
        } else {
            throw new IdpException(
                    new UnsupportedOperationException("Must use HTTP POST or Redirect bindings."));
        }
        binding.validator().validateAuthnRequest(authnRequest, samlRequest, relayState, signatureAlgorithm,
                signature, strictSignature);

        if (HTTP_POST_BINDING.equals(assertionConsumerServiceBinding)) {
            if (!(binding instanceof PostBinding)) {
                binding = new PostBinding(systemCrypto, serviceProviders);
            }
        } else if (HTTP_REDIRECT_BINDING.equals(assertionConsumerServiceBinding)) {
            if (!(binding instanceof RedirectBinding)) {
                binding = new RedirectBinding(systemCrypto, serviceProviders);
            }
        }
        org.opensaml.saml.saml2.core.Response encodedSaml = handleLogin(authnRequest, authMethod, request,
                false, false);
        LOGGER.debug("Returning SAML Response for relayState: {}" + relayState);
        NewCookie newCookie = createCookie(request, encodedSaml);
        Response response = binding.creator().getSamlpResponse(relayState, authnRequest, encodedSaml, newCookie,
                template);
        if (newCookie != null) {
            cookieCache.addActiveSp(newCookie.getValue(), authnRequest.getIssuer().getValue());
            logAddedSp(authnRequest);
        }

        return response;
    } catch (SecurityServiceException e) {
        LOGGER.warn("Unable to retrieve subject for user.", e);
        return Response.status(Response.Status.UNAUTHORIZED).build();
    } catch (WSSecurityException e) {
        LOGGER.error("Unable to encode SAMLP response.", e);
    } catch (SimpleSign.SignatureException e) {
        LOGGER.error("Unable to sign SAML response.", e);
    } catch (IllegalArgumentException e) {
        LOGGER.error(e.getMessage(), e);
        return Response.status(Response.Status.BAD_REQUEST).build();
    } catch (ValidationException e) {
        LOGGER.error("AuthnRequest schema validation failed.", e);
        return Response.status(Response.Status.BAD_REQUEST).build();
    } catch (IOException e) {
        LOGGER.error("Unable to create SAML Response.", e);
    } catch (IdpException e) {
        LOGGER.error("", e);
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}

From source file:org.keycloak.example.OfflineAccessPortalServlet.java

private HttpFacade getFacade(final HttpServletRequest servletRequest) {
    return new HttpFacade() {

        @Override/* w  w  w .j a  v a2s  . c o m*/
        public Request getRequest() {
            return new Request() {

                private InputStream inputStream;

                @Override
                public String getMethod() {
                    return servletRequest.getMethod();
                }

                @Override
                public String getURI() {
                    return servletRequest.getRequestURL().toString();
                }

                @Override
                public String getRelativePath() {
                    return servletRequest.getServletPath();
                }

                @Override
                public boolean isSecure() {
                    return servletRequest.isSecure();
                }

                @Override
                public String getQueryParamValue(String param) {
                    return servletRequest.getParameter(param);
                }

                @Override
                public String getFirstParam(String param) {
                    return servletRequest.getParameter(param);
                }

                @Override
                public Cookie getCookie(String cookieName) {
                    // not needed
                    return null;
                }

                @Override
                public String getHeader(String name) {
                    return servletRequest.getHeader(name);
                }

                @Override
                public List<String> getHeaders(String name) {
                    // not needed
                    return null;
                }

                @Override
                public InputStream getInputStream() {
                    return getInputStream(false);
                }

                @Override
                public InputStream getInputStream(boolean buffered) {
                    if (inputStream != null) {
                        return inputStream;
                    }

                    if (buffered) {
                        try {
                            return inputStream = new BufferedInputStream(servletRequest.getInputStream());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    try {
                        return servletRequest.getInputStream();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public String getRemoteAddr() {
                    return servletRequest.getRemoteAddr();
                }

                @Override
                public void setError(AuthenticationError error) {
                    servletRequest.setAttribute(AuthenticationError.class.getName(), error);

                }

                @Override
                public void setError(LogoutError error) {
                    servletRequest.setAttribute(LogoutError.class.getName(), error);
                }

            };
        }

        @Override
        public Response getResponse() {
            throw new IllegalStateException("Not yet implemented");
        }

        @Override
        public X509Certificate[] getCertificateChain() {
            throw new IllegalStateException("Not yet implemented");
        }
    };
}

From source file:ru.org.linux.topic.EditTopicController.java

@RequestMapping(value = "/edit.jsp", method = RequestMethod.POST)
public ModelAndView edit(HttpServletRequest request, @RequestParam("msgid") int msgid,
        @RequestParam(value = "lastEdit", required = false) Long lastEdit,
        @RequestParam(value = "chgrp", required = false) Integer changeGroupId,
        @Valid @ModelAttribute("form") EditTopicRequest form, Errors errors) throws Exception {
    Template tmpl = Template.getTemplate(request);

    if (!tmpl.isSessionAuthorized()) {
        throw new AccessViolationException("Not authorized");
    }//from w  w w .  j  a v  a2  s  . co  m

    Map<String, Object> params = new HashMap<String, Object>();

    Topic message = messageDao.getById(msgid);
    PreparedTopic preparedMessage = messagePrepareService.prepareMessage(message, false, request.isSecure());
    Group group = preparedMessage.getGroup();

    params.put("message", message);
    params.put("preparedMessage", preparedMessage);
    params.put("group", group);

    if (group.isModerated()) {
        params.put("topTags", tagDao.getTopTags());
    }

    params.put("groups", groupDao.getGroups(preparedMessage.getSection()));

    User user = tmpl.getCurrentUser();

    if (!preparedMessage.isEditable(user)) {
        throw new AccessViolationException("? ? ? ");
    }

    if (!message.isExpired()) {
        String title = request.getParameter("title");
        if (title == null || title.trim().length() == 0) {
            throw new BadInputException(
                    " ??    ?");
        }
    }

    List<EditInfoDto> editInfoList = messageDao.getEditInfo(message.getId());

    boolean preview = request.getParameter("preview") != null;
    if (preview) {
        params.put("info", "?");
    }

    if (!editInfoList.isEmpty()) {
        EditInfoDto dbEditInfo = editInfoList.get(0);
        params.put("editInfo", dbEditInfo);

        if (lastEdit == null || dbEditInfo.getEditdate().getTime() != lastEdit) {
            errors.reject(null,
                    "   ?");
        }
    }

    boolean commit = request.getParameter("commit") != null;

    if (commit) {
        user.checkCommit();
        if (message.isCommited()) {
            throw new BadInputException("?  ");
        }
    }

    params.put("commit",
            !message.isCommited() && preparedMessage.getSection().isPremoderated() && user.isModerator());

    Topic newMsg = new Topic(group, message, form);

    boolean modified = false;

    if (!message.getTitle().equals(newMsg.getTitle())) {
        modified = true;
    }

    if (!message.getMessage().equals(newMsg.getMessage())) {
        modified = true;
    }

    if (message.getLinktext() == null) {
        if (newMsg.getLinktext() != null) {
            modified = true;
        }
    } else if (!message.getLinktext().equals(newMsg.getLinktext())) {
        modified = true;
    }

    if (message.isHaveLink()) {
        if (message.getUrl() == null) {
            if (newMsg.getUrl() != null) {
                modified = true;
            }
        } else if (!message.getUrl().equals(newMsg.getUrl())) {
            modified = true;
        }
    }

    if (message.isExpired() && modified) {
        throw new AccessViolationException(
                "?  ? ??");
    }

    if (form.getMinor() != null && !tmpl.isModeratorSession()) {
        throw new AccessViolationException("   ? ?? ?");
    }

    List<String> newTags = null;

    if (form.getTags() != null) {
        newTags = TagDao.parseSanitizeTags(form.getTags());
    }

    if (changeGroupId != null) {
        if (message.getGroupId() != changeGroupId) {
            Group changeGroup = groupDao.getGroup(changeGroupId);

            int section = message.getSectionId();

            if (changeGroup.getSectionId() != section) {
                throw new AccessViolationException("Can't move topics between sections");
            }
        }
    }

    PreparedPoll newPoll = null;

    if (message.isVotePoll() && form.getPoll() != null && tmpl.isModeratorSession()) {
        Poll poll = pollDao.getPollByTopicId(message.getId());

        PreparedPoll orig = pollPrepareService.preparePoll(poll);

        List<PollVariant> newVariants = new ArrayList<PollVariant>();

        for (PollVariant v : pollDao.getPollVariants(poll, Poll.ORDER_ID)) {
            String label = form.getPoll().get(v.getId());

            if (!Strings.isNullOrEmpty(label)) {
                newVariants.add(new PollVariant(v.getId(), label, v.getVotes(), v.getUserVoted()));
            }
        }

        for (String label : form.getNewPoll()) {
            if (!Strings.isNullOrEmpty(label)) {
                newVariants.add(new PollVariant(0, label, 0, false));
            }
        }

        newPoll = new PreparedPoll(poll, orig.getMaximumValue(), pollDao.getCountUsers(poll), newVariants);
    }

    if (!preview && !errors.hasErrors()) {
        boolean changed = messageDao.updateAndCommit(newMsg, message, user, newTags, commit, changeGroupId,
                form.getBonus(), newPoll != null ? newPoll.getVariants() : null, form.isMultiselect());

        if (changed || commit) {
            searchQueueSender.updateMessageOnly(newMsg.getId());

            if (commit) {
                feedPinger.pingFeedburner();
            }

            return new ModelAndView(new RedirectView(message.getLinkLastmod()));
        } else {
            errors.reject(null, "? ");
        }
    }

    params.put("newMsg", newMsg);

    params.put("newPreparedMessage",
            messagePrepareService.prepareMessage(newMsg, newTags, newPoll, request.isSecure()));

    return new ModelAndView("edit", params);
}

From source file:com.tasktop.c2c.server.web.proxy.ajp.AjpProtocol.java

public void forward(HttpServletRequest request, HttpServletResponse response) throws IOException {
    debug(request, "forward");

    Packet packet = new Packet();
    packet.reset();/*from w  w w.j  a v  a 2  s  .  com*/
    // AJP13_FORWARD_REQUEST
    packet.write(Type.REQUEST_FORWARD.code);
    packet.write(computeMethod(request.getMethod()).code);
    packet.write(request.getProtocol());
    packet.write(request.getRequestURI());
    packet.write(request.getRemoteAddr());
    packet.write(request.getRemoteAddr());
    packet.write(request.getServerName());
    packet.write(request.getServerPort());
    packet.write(request.isSecure());

    // request headers
    Map<String, String> headers = new HashMap<String, String>();
    @SuppressWarnings("rawtypes")
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement().toString();
        String headerValue = request.getHeader(headerName);
        headerValue = headerFilter.processRequestHeader(headerName, headerValue);
        if (headerValue != null) {
            headers.put(headerName, headerValue);
        }
    }
    packet.write(headers.size());
    for (Map.Entry<String, String> header : headers.entrySet()) {
        HttpRequestHeader headerType = HttpRequestHeader.fromHeaderName(header.getKey());
        if (headerType != null) {
            packet.write(headerType.code);
        } else {
            packet.write(header.getKey());
        }
        String headerValue = header.getValue();
        packet.write(headerValue == null ? "" : headerValue);
    }

    // request attributes
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        packet.write(Attribute.REMOTE_USER.code);
        packet.write(authentication.getName());
    }

    String queryString = request.getQueryString();
    if (queryString != null) {
        packet.write(Attribute.QUERY_STRING.code);
        packet.write(queryString);
    }

    // packet terminator
    packet.write((byte) 0xff);

    final Object socketKey = new AjpPoolableConnectionFactory.Key(proxyHost, proxyPort);
    Socket connection;

    try {
        connection = allocateSocket(socketKey);
        debug("allocated", connection);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    }

    boolean invalidate = true;
    try {
        OutputStream outputStream = connection.getOutputStream();
        InputStream inputStream = connection.getInputStream();
        packet.write(outputStream);
        packet.reset();

        int bytesWritten = 0;

        int contentLength = request.getContentLength();
        if (contentLength == -1) { // Unknown content length
            contentLength = Integer.MAX_VALUE;
        }
        ServletInputStream requestInput = request.getInputStream();

        OutputStream responseOutput = null;
        boolean reuse = false;

        if (request.getHeader("Content-Length") != null) {
            bytesWritten += processRequestBody(packet, outputStream, bytesWritten, contentLength, requestInput,
                    contentLength);
            debug("sent [" + bytesWritten + "] initial body bytes", connection);
        }

        for (;; packet.reset()) {
            debug("reading packet", connection);
            packet.read(inputStream);

            Type packetType = Type.fromCode(packet.readByte());
            debug("received " + packetType, connection);
            if (packetType == Type.END_RESPONSE) {
                reuse = packet.readBoolean();
                break;
            }
            switch (packetType) {
            case GET_BODY_CHUNK:
                int requestedSize = packet.readInt();
                packet.reset();
                int chunkSize = processRequestBody(packet, outputStream, bytesWritten, contentLength,
                        requestInput, requestedSize);
                bytesWritten += chunkSize;
                debug("sent [" + chunkSize + "] bytes of body chunk", connection);
                break;
            case SEND_HEADERS: {
                response.reset();
                int httpStatusCode = packet.readInt();
                packet.readString(); // status message, not used
                response.setStatus(httpStatusCode);
                int headerCount = packet.readInt();
                for (int x = 0; x < headerCount; ++x) {
                    byte b = packet.readByte();
                    packet.unreadByte();
                    String headerName;
                    if (b == ((byte) 0xA0)) {
                        int headerCode = packet.readInt();
                        headerName = HttpResponseHeader.fromCode(headerCode).headerName;
                    } else {
                        headerName = packet.readString();
                    }
                    String headerValue = packet.readString();
                    headerValue = headerFilter.processResponseHeader(headerName, headerValue);
                    if (headerValue != null) {
                        response.setHeader(headerName, headerValue);
                    }
                }
            }
                break;
            case SEND_BODY_CHUNK:
                if (responseOutput == null) {
                    responseOutput = response.getOutputStream();
                }
                packet.copy(responseOutput);
                break;
            }
        }

        // ORDER DEPENDENCY: this should come last
        invalidate = !reuse;

        if (responseOutput != null) {
            responseOutput.close();
        }
    } finally {
        if (!shareConnections) {
            invalidate = true;
        }
        deallocateSocket(socketKey, connection, invalidate);
        debug("released " + (invalidate ? "invalidate" : "reuse"), connection);
    }
}