Example usage for javax.servlet.http HttpServletResponse sendRedirect

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

Introduction

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

Prototype

public void sendRedirect(String location) throws IOException;

Source Link

Document

Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer.

Usage

From source file:com.museum_web.controller.ChallengeController.java

@RequestMapping("actions/addAnswer/{Answer}")
public void addAnswer(@PathVariable("Answer") Long answer, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    List<Answer> aux = c.getAnswers();

    Answer a = new AnswerService().findById(answer);

    if (a.isCorrect() && c.getCorrectAnswer() != null)
        addError = true;/*from  www  .j a  va 2  s.  c  o m*/
    else {
        aux.add(a);

        c.setAnswers(aux);

        new ChallengeService().editChallenge(c);

        addError = false;
    }

    response.sendRedirect("../../challengeCreate?id=" + c.getChallengeId());

}

From source file:ke.co.tawi.babblesms.server.servlet.sms.send.SendSMS.java

/**
 * Method to handle form processing/*from  w  w w . ja  v  a  2s .c  o  m*/
 * 
 * @param request
 * @param response
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 * 
 * @throws IOException
 */
@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // Respond as soon as possible to the client request
    HttpSession session = request.getSession(true);
    session.setAttribute(SessionConstants.SENT_SUCCESS, "success");
    response.sendRedirect("sendsms.jsp");

    // Get the relevant account      
    Account account = new Account();

    String username = request.getParameter("username");

    Element element;
    if ((element = accountsCache.get(username)) != null) {
        account = (Account) element.getObjectValue();
    }

    TawiGateway smsGateway = gatewayDAO.get(account);

    // Retrieve the web parameters
    String[] groupselected = request.getParameterValues("groupselected");
    String[] phones = request.getParameterValues("phones");
    String source = request.getParameter("source");
    String message = request.getParameter("message");

    // Deal with the case where one or more Groups has been selected
    // Get phones of all the Contacts in the Group(s)
    SetUniqueList phoneList = SetUniqueList.decorate(new LinkedList<Phone>()); // Does not allow duplicates 

    Group group;
    List<Contact> contactList;
    List<OutgoingGrouplog> outgoingGroupList = new LinkedList<>();

    if (groupselected != null) {
        OutgoingGrouplog groupLog;

        for (String groupUuid : groupselected) {
            group = new Group();
            group.setUuid(groupUuid);
            contactList = ctgrpDAO.getContacts(group);

            for (Contact contact : contactList) {
                phoneList.addAll(phoneDAO.getPhones(contact));
            }

            // Save an outgoing log for the group 
            groupLog = new OutgoingGrouplog();
            groupLog.setMessagestatusUuid(MsgStatus.SENT);
            groupLog.setSender(account.getUuid());
            groupLog.setDestination(group.getUuid());
            groupLog.setMessage(message);
            outgoingGroupList.add(groupLog);

        } // end 'for(String groupUuid : groupselected)'
    } // end 'if(groupselected != null)'

    // This is the case where individual Contacts may have been selected      
    if (phones == null) {
        phones = new String[0];
    }
    phones = StringUtil.removeDuplicates(phones);

    for (String phone : phones) {
        phoneList.add(phoneDAO.getPhone(phone));
    }

    // Determine whether a shortcode or mask is the source
    SMSSource smsSource;
    Shortcode shortcode = shortcodeDAO.get(source);
    Mask mask = null;
    if (shortcode == null) {
        mask = maskDAO.get(source);
        smsSource = mask;

    } else {
        smsSource = shortcode;
    }

    // Set the network in the groups (if any) and save the log
    for (OutgoingGrouplog log : outgoingGroupList) {
        log.setNetworkUuid(smsSource.getNetworkuuid());
        log.setOrigin(smsSource.getUuid());
        groupLogDAO.put(log);
    }

    // Filter the phones to the Network of the source (mask or short code)
    List<Phone> validPhoneList = new LinkedList<>();
    validPhoneList.addAll(
            CollectionUtils.select(phoneList, new PhonesByNetworkPredicate(smsSource.getNetworkuuid())));

    // Break down the phone list to go out to manageable sizes, each sublist
    // being sent to the SMS Gateway in one URL POST
    List<List<Phone>> phonePartition = ListPartitioner.partition(validPhoneList, 10);

    // Send the lists one by one
    PostSMS postThread;

    for (List<Phone> list : phonePartition) {
        postThread = new PostSMS(smsGateway, list, smsSource, message, account, true);

        postThread.start();
    }

    // Deduct credit
    smsBalanceDAO.deductBalance(account, smsSource, validPhoneList.size());
}

From source file:com.mycompany.login.filter.AutenticacaoFilter.java

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        Authentication authResult) throws IOException, ServletException {
    SecurityContextHolder.getContext().setAuthentication(authResult);
    request.getSession().setAttribute("msg", mensagem);
    com.mycompany.login.bean.Usuario usuario = (Usuario) request.getSession().getAttribute("usuarioLogado");
    switch (usuario.getPermissao()) {
    case "ROLE_USER":
        response.sendRedirect("chamados/List.xhtml");
        break;/*w ww.ja  va  2s .c om*/
    case "ROLE_AT":
        response.sendRedirect("assisttec/List.xhtml");
        break;
    case "ROLE_ADM":
        response.sendRedirect("adm/List.xhtml");
        break;
    }
}

From source file:pivotal.au.se.gemfirexdweb.controller.CreateGatewaySenderController.java

@RequestMapping(value = "/creategatewaysender", method = RequestMethod.POST)
public String createGatewaySenderAction(
        @ModelAttribute("gatewaySenderAttribute") NewGatewaySender gatewaySenderAttribute, Model model,
        HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {//from   w  ww.j  av  a 2s  .c o m
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action an event for create Gateway Sender");

    DiskStoreDAO dsDAO = GemFireXDWebDAOFactory.getDiskStoreDAO();

    List<DiskStore> dsks = dsDAO.retrieveDiskStoreForCreateList((String) session.getAttribute("user_key"));

    model.addAttribute("diskstores", dsks);

    String gatewaySenderName = gatewaySenderAttribute.getGatewaySenderName();

    logger.debug("New Gateway Sender Name = " + gatewaySenderName);

    // perform some action here with what we have
    String submit = request.getParameter("pSubmit");
    boolean needCloseBracket = false;

    if (submit != null) {
        // build create HDFS Store SQL
        StringBuffer createGatewaySender = new StringBuffer();

        createGatewaySender.append("CREATE GATEWAYSENDER " + gatewaySenderName + " (\n");
        createGatewaySender.append("REMOTEDSID " + gatewaySenderAttribute.getRemoteSID() + " \n");

        if (!checkIfParameterEmpty(request, "socketBufferSize")) {
            createGatewaySender
                    .append("SOCKETBUFFERSIZE " + gatewaySenderAttribute.getSocketBufferSize() + " \n");
        }

        if (!checkIfParameterEmpty(request, "socketReadTimeout")) {
            createGatewaySender
                    .append("SOCKETREADTIMEOUT " + gatewaySenderAttribute.getSocketReadTimeout() + " \n");
        }

        if (!checkIfParameterEmpty(request, "manualStart")) {
            createGatewaySender.append("MANUALSTART " + gatewaySenderAttribute.getManualStart() + " \n");
        }

        if (!checkIfParameterEmpty(request, "enableBatchConflation")) {
            createGatewaySender.append(
                    "ENABLEBATCHCONFLATION " + gatewaySenderAttribute.getEnableBatchConflation() + " \n");
        }

        if (!checkIfParameterEmpty(request, "batchSize")) {
            createGatewaySender.append("BATCHSIZE " + gatewaySenderAttribute.getBatchSize() + " \n");
        }

        if (!checkIfParameterEmpty(request, "batchTimeInterval")) {
            createGatewaySender
                    .append("BATCHTIMEINTERVAL " + gatewaySenderAttribute.getBatchTimeInterval() + " \n");
        }

        if (!checkIfParameterEmpty(request, "enablePersistence")) {
            createGatewaySender
                    .append("ENABLEPERSISTENCE " + gatewaySenderAttribute.getEnablePersistence() + " \n");
            if (gatewaySenderAttribute.getEnablePersistence().equals("TRUE")) {
                if (!checkIfParameterEmpty(request, "diskStore")) {
                    createGatewaySender
                            .append("DISKSTORENAME " + gatewaySenderAttribute.getDiskStore() + " \n");
                }
            }
        }

        if (!checkIfParameterEmpty(request, "maxQueueMemory")) {
            createGatewaySender.append("MAXQUEUEMEMORY " + gatewaySenderAttribute.getMaxQueueMemory() + " \n");
        }

        if (!checkIfParameterEmpty(request, "alertThreshold")) {
            createGatewaySender.append("ALERTTHRESHOLD " + gatewaySenderAttribute.getAlertThreshold() + " \n");
        }

        createGatewaySender.append(") \n");

        if (!checkIfParameterEmpty(request, "serverGroups")) {
            createGatewaySender.append("SERVER GROUPS (" + gatewaySenderAttribute.getServerGroups() + ") \n");
        }

        if (submit.equalsIgnoreCase("create")) {
            Result result = new Result();

            logger.debug("Creating gateway sender as -> " + createGatewaySender.toString());

            result = GemFireXDWebDAOUtil.runCommand(createGatewaySender.toString(),
                    (String) session.getAttribute("user_key"));

            model.addAttribute("result", result);

        } else if (submit.equalsIgnoreCase("Show SQL")) {
            logger.debug("Create Gateway Sender SQL as follows as -> " + createGatewaySender.toString());
            model.addAttribute("sql", createGatewaySender.toString());
        } else if (submit.equalsIgnoreCase("Save to File")) {
            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + String.format(FILENAME, gatewaySenderName));

            ServletOutputStream out = response.getOutputStream();
            out.println(createGatewaySender.toString());
            out.close();
            return null;
        }

    }

    // This will resolve to /WEB-INF/jsp/create-gatewaysender.jsp
    return "create-gatewaysender";
}

From source file:info.raack.appliancelabeler.web.BaseController.java

@ExceptionHandler
public ModelAndView handleUncaughtException(Exception ex, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    if (ex instanceof AccessDeniedException) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } else if (ex instanceof OAuthUnauthorizedException) {
        /*if(request.getSession() != null) {
           request.getSession().invalidate();
        }/*w  ww . j  a va2 s.c  om*/
        SecurityContextHolder.getContext().setAuthentication(null);*/
        try {
            response.sendRedirect("/t/logout.do");
            logger.warn("Could not authorize oauth request", ex);
        } catch (IOException e1) {
            logger.error("Could not send redirect", e1);
        }
        return null;
    } else if (ex instanceof ClientAPIException) {
        if (ex.getCause() != null && ex.getCause() instanceof OAuthUnauthorizedException) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
        response.getOutputStream().write(ex.getMessage().getBytes());
        return null;
    } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        errorService.reportError("Error while processing user web page request", URGENCY.URGENT, ex);
        logger.error("An exception was caught while processing", ex);
    }
    return templateProvider.showPageInTemplate(1, "error/basic", new ModelMap());
}

From source file:de.hybris.platform.chinesepspalipaymockaddon.controllers.pages.AlipayMockController.java

protected void returnResponse(final HttpServletResponse response, final Map<String, String> params,
        final String tradeStatus) throws IOException {
    mockService.stripOffCSRFToken(params);
    final String returnUrl = getReturnShopUrl(params, tradeStatus);
    response.sendRedirect(returnUrl);
}

From source file:ge.taxistgela.servlet.AdminServlet.java

public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    Admin admin = new Admin();

    if (admin.checkLogin(username, password)) {
        request.getSession().setAttribute(Admin.class.getName(), admin);

        response.setStatus(HttpServletResponse.SC_OK);
        response.sendRedirect("/admin.jsp");

        return;//www  . j  a  v  a  2  s . co  m
    }

    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
}

From source file:com.swiftcorp.portal.common.login.web.LoginAction.java

public ActionForward loginSuccess(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    theLogger.info("loginSuccess()::");

    ActionForward actionForward = null;//w ww  .  ja  va2  s.  c o  m
    HttpSession session = request.getSession();
    if (session == null) {
        response.sendRedirect(promptLoginRequestString);
    }
    LoginDetailInfoDTO loginInfo = (LoginDetailInfoDTO) session.getAttribute(SESSION_KEYS.LOGIN_INFO);
    if (loginInfo == null) {
        response.sendRedirect(promptLoginRequestString);
    }
    try {
        loginInfo.getUser();
    } catch (Exception e) {
        return promptLogin(mapping, form, request, response);
        //response.sendRedirect(promptLoginRequestString);
    }

    session.setAttribute(SESSION_KEYS.USER, loginInfo.getUser());
    // GroupDTO group = (GroupDTO)
    // groupService.get(loginInfo.getUser().getGroupId());
    // session.setAttribute(SESSION_KEYS.GROUP, group);
    actionForward = mapping.findForward(ForwardNames.USER_HOME);

    // since this month list and year list is needed to all other components
    // that's why we need to add those into first long-in
    List<ViewValueDTO> monthList = ReportUtils.getMonths();
    List<ViewValueDTO> yearList = ReportUtils.getYears();
    request.getSession().setAttribute(SESSION_KEYS.MONTH_LIST, monthList);
    request.getSession().setAttribute(SESSION_KEYS.YEAR_LIST, yearList);

    if (actionForward != null) {
        return actionForward;
    }

    return promptLogin(mapping, form, request, response);
}

From source file:dk.dma.msinm.web.wms.WmsProxyServlet.java

/**
 * Main GET method//  www  .j  a v  a 2 s .  c  o m
 * @param request servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // Cache for a day
    WebUtils.cache(response, CACHE_TIMEOUT);

    // Check that the WMS provider has been defined using system properties
    if (StringUtils.isBlank(wmsServiceName) || StringUtils.isBlank(wmsProvider) || StringUtils.isBlank(wmsLogin)
            || StringUtils.isBlank(wmsPassword)) {
        response.sendRedirect(BLANK_IMAGE);
        return;
    }

    @SuppressWarnings("unchecked")
    Map<String, String[]> paramMap = request.getParameterMap();
    String params = paramMap.entrySet().stream().map(p -> String.format("%s=%s", p.getKey(), p.getValue()[0]))
            .collect(Collectors.joining("&"));
    params += String.format("&SERVICENAME=%s&LOGIN=%s&PASSWORD=%s", wmsServiceName, wmsLogin, wmsPassword);

    String url = wmsProvider + "?" + params;
    log.trace("Loading image " + url);

    try {
        BufferedImage image = ImageIO.read(new URL(url));
        if (image != null) {
            image = transformWhiteToTransparent(image);

            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "png", out);
            image.flush();
            out.close();
            return;
        }
    } catch (Exception e) {
        log.trace("Failed loading WMS image for URL " + url);
    }

    // Fall back to return a blank image
    response.sendRedirect(BLANK_IMAGE);
}

From source file:dk.dma.msiproxy.web.WmsProxyServlet.java

/**
 * Main GET method/*w  w w. j  a  va2s . c  om*/
 * @param request servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // Cache for a day
    WebUtils.cache(response, CACHE_TIMEOUT);

    // Check that the WMS provider has been defined using system properties
    if (StringUtils.isBlank(wmsServiceName) || StringUtils.isBlank(wmsProvider) || StringUtils.isBlank(wmsLogin)
            || StringUtils.isBlank(wmsPassword)) {
        response.sendRedirect(BLANK_IMAGE);
        return;
    }

    @SuppressWarnings("unchecked")
    Map<String, String[]> paramMap = (Map<String, String[]>) request.getParameterMap();
    String params = paramMap.entrySet().stream().map(p -> String.format("%s=%s", p.getKey(), p.getValue()[0]))
            .collect(Collectors.joining("&"));
    params += String.format("&SERVICENAME=%s&LOGIN=%s&PASSWORD=%s", wmsServiceName, wmsLogin, wmsPassword);

    String url = wmsProvider + "?" + params;
    log.trace("Loading image " + url);

    try {
        BufferedImage image = ImageIO.read(new URL(url));
        if (image != null) {
            image = transformWhiteToTransparent(image);

            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "png", out);
            image.flush();
            out.close();
            return;
        }
    } catch (Exception e) {
        log.trace("Failed loading WMS image for URL " + url);
    }

    // Fall back to return a blank image
    response.sendRedirect(BLANK_IMAGE);
}