Example usage for javax.servlet.http HttpSession getServletContext

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

Introduction

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

Prototype

public ServletContext getServletContext();

Source Link

Document

Returns the ServletContext to which this session belongs.

Usage

From source file:org.jbpm.formbuilder.server.RESTFormServiceTest.java

public void testSaveFormItemEncodingProblem() throws Exception {
    RESTFormService restService = new RESTFormService();
    FormRepresentationDecoder decoder = EasyMock.createMock(FormRepresentationDecoder.class);
    FormEncodingFactory.register(FormEncodingServerFactory.getEncoder(), decoder);
    FormDefinitionService formService = EasyMock.createMock(FormDefinitionService.class);
    FormItemRepresentation item = RESTAbstractTest.createMockForm("formToBeSaved", "param1").getFormItems()
            .iterator().next();//from  w  w  w  . ja  v  a  2s . c  o m
    FormEncodingException exception = new FormEncodingException("Something going wrong");
    EasyMock.expect(decoder.decodeItem(EasyMock.anyObject(String.class))).andThrow(exception).once();
    restService.setFormService(formService);
    ServletContext context = EasyMock.createMock(ServletContext.class);
    HttpSession session = EasyMock.createMock(HttpSession.class);
    HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(request.getSession()).andReturn(session);
    EasyMock.expect(session.getServletContext()).andReturn(context);

    EasyMock.replay(formService, context, decoder, session, request);
    Response resp = restService.saveFormItem(FormEncodingFactory.getEncoder().encode(item), "somePackage",
            "MY_FORM_ITEM_ID", request);
    EasyMock.verify(formService, context, decoder, session, request);

    assertNotNull("resp shouldn't be null", resp);
    assertStatus(resp.getStatus(), Status.INTERNAL_SERVER_ERROR);
}

From source file:com.orchestra.portale.controller.EditEventController.java

@RequestMapping(value = "/updateevent", method = RequestMethod.POST)
public ModelAndView updateEvent(HttpServletRequest request, @RequestParam Map<String, String> params,
        @RequestParam(value = "file", required = false) MultipartFile[] files,
        @RequestParam(value = "cover", required = false) MultipartFile cover,
        @RequestParam(value = "fileprec", required = false) String[] fileprec,
        @RequestParam(value = "imgdel", required = false) String[] imgdel) throws InterruptedException {

    CompletePOI poi = pm.getCompletePoiById(params.get("id"));
    CoverImgComponent coverimg = new CoverImgComponent();
    ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();
    for (AbstractPoiComponent comp : poi.getComponents()) {

        //associazione delle componenti al model tramite lo slug
        String slug = comp.slug();
        int index = slug.lastIndexOf(".");
        String cname = slug.substring(index + 1).replace("Component", "").toLowerCase();
        if (cname.equals("coverimg")) {
            coverimg = (CoverImgComponent) comp;
        }/*from www. ja  v a  2  s. c  o m*/
    }
    ModelAndView model = new ModelAndView("editedpoi");

    poi.setId(params.get("id"));

    ModelAndView model2 = new ModelAndView("errorViewPoi");

    poi.setName(params.get("name"));
    poi.setVisibility("1");
    poi.setAddress(params.get("address"));
    double lat = Double.parseDouble(params.get("latitude"));
    double longi = Double.parseDouble(params.get("longitude"));
    poi.setLocation(new double[] { lat, longi });
    poi.setStart_date(params.get("datai"));
    poi.setEnd_date(params.get("dataf"));
    poi.setShortDescription(params.get("shortd"));
    int i = 1;
    ArrayList<String> categories = new ArrayList<String>();
    while (params.containsKey("category" + i)) {

        categories.add(params.get("category" + i));

        model.addObject("nome", categories.get(i - 1));
        i = i + 1;
    }
    poi.setCategories(categories);

    //componente cover
    if (!cover.isEmpty()) {

        coverimg.setLink("cover.jpg");

    }
    listComponent.add(coverimg);
    //componente galleria immagini
    ImgGalleryComponent img_gallery = new ImgGalleryComponent();
    ArrayList<ImgGallery> links = new ArrayList<ImgGallery>();
    i = 0;

    if (files != null && files.length > 0) {
        while (i < files.length) {
            ImgGallery img = new ImgGallery();
            Thread.sleep(100);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhmmssSSa");
            String currentTimestamp = sdf.format(date);
            img.setLink("img_" + currentTimestamp + ".jpg");
            if (params.containsKey("newcredit" + (i + 1))) {
                img.setCredit(params.get("newcredit" + (i + 1)));
            }
            i = i + 1;
            links.add(img);
        }
    }
    int iximg = 0;
    if (fileprec != null && fileprec.length > 0) {
        while (iximg < fileprec.length) {
            ImgGallery img = new ImgGallery();
            img.setLink(fileprec[iximg]);
            if (params.containsKey("credit" + (iximg + 1))) {
                img.setCredit(params.get("credit" + (iximg + 1)));
            }
            iximg = iximg + 1;
            links.add(img);
        }
    }
    if ((fileprec != null && fileprec.length > 0) || (files != null && files.length > 0)) {
        img_gallery.setLinks(links);
        listComponent.add(img_gallery);
    }
    //componente contatti
    ContactsComponent contacts_component = new ContactsComponent();
    //Recapiti telefonici
    i = 1;
    boolean contacts = false;
    if (params.containsKey("tel" + i)) {
        ArrayList<PhoneContact> phoneList = new ArrayList<PhoneContact>();

        while (params.containsKey("tel" + i)) {
            PhoneContact phone = new PhoneContact();
            if (params.containsKey("tel" + i)) {
                phone.setLabel(params.get("desctel" + i));
            }
            phone.setNumber(params.get("tel" + i));
            phoneList.add(phone);
            i = i + 1;
        }
        contacts = true;
        contacts_component.setPhoneList(phoneList);
    }
    //Recapiti mail
    i = 1;
    if (params.containsKey("email" + i)) {
        ArrayList<EmailContact> emailList = new ArrayList<EmailContact>();

        while (params.containsKey("email" + i)) {
            EmailContact email = new EmailContact();
            if (params.containsKey("email" + i)) {
                email.setLabel(params.get("descemail" + i));
            }
            email.setEmail(params.get("email" + i));
            emailList.add(email);
            i = i + 1;
        }
        contacts = true;
        contacts_component.setEmailsList(emailList);
    }
    //Recapiti fax
    i = 1;
    if (params.containsKey("fax" + i)) {
        ArrayList<FaxContact> faxList = new ArrayList<FaxContact>();

        while (params.containsKey("fax" + i)) {
            FaxContact fax = new FaxContact();
            if (params.containsKey("fax" + i)) {
                fax.setLabel(params.get("descfax" + i));
            }
            fax.setFax(params.get("fax" + i));
            faxList.add(fax);
            i = i + 1;
        }
        contacts = true;
        contacts_component.setFaxList(faxList);
    }
    //Social predefiniti
    i = 1;
    if (params.containsKey("SN" + i)) {

        while (params.containsKey("SN" + i)) {
            if (params.get("SN" + i).equals("facebook")) {
                contacts = true;
                contacts_component.setFacebook(params.get("LSN" + i));
            }
            if (params.get("SN" + i).equals("twitter")) {
                contacts = true;
                contacts_component.setTwitter(params.get("LSN" + i));
            }
            if (params.get("SN" + i).equals("google")) {
                contacts = true;
                contacts_component.setGoogle(params.get("LSN" + i));
            }
            if (params.get("SN" + i).equals("skype")) {
                contacts = true;
                contacts_component.setSkype(params.get("LSN" + i));
            }
            i = i + 1;
        }
    }
    //Social personalizzati
    i = 1;
    if (params.containsKey("CSN" + i)) {
        ArrayList<GenericSocial> customsocial = new ArrayList<GenericSocial>();

        while (params.containsKey("CSN" + i)) {
            GenericSocial social = new GenericSocial();
            contacts = true;
            social.setLabel(params.get("CSN" + i));
            social.setSocial(params.get("LCSN" + i));
            customsocial.add(social);
            i = i + 1;
        }
        contacts_component.setSocialList(customsocial);
    }
    if (contacts == true) {
        listComponent.add(contacts_component);
    }
    //DESCRIPTION COMPONENT
    i = 1;
    if (params.containsKey("par" + i)) {
        ArrayList<Section> list = new ArrayList<Section>();

        while (params.containsKey("par" + i)) {
            Section section = new Section();
            if (params.containsKey("titolo" + i)) {
                section.setTitle(params.get("titolo" + i));
            }
            section.setDescription(params.get("par" + i));
            list.add(section);
            i = i + 1;

        }
        DescriptionComponent description_component = new DescriptionComponent();
        description_component.setSectionsList(list);
        listComponent.add(description_component);
    }
    //Orari
    i = 1;
    int k = 1;
    boolean ok = false;
    String gg = "";
    boolean[] aperto = new boolean[8];

    EventsDateComponent workingtime = new EventsDateComponent();
    if (params.containsKey("WD" + i + "start" + k + "H")) {
        ArrayList<EventsDates> workingdays = new ArrayList<EventsDates>();

        while (params.containsKey("WD" + i)) {
            ArrayList<EventsHours> Listwh = new ArrayList<EventsHours>();
            k = 1;
            while (params.containsKey("WD" + i + "start" + k + "H")) {
                EventsHours wh = new EventsHours();
                wh.setStart(params.get("WD" + i + "start" + k + "H") + ":"
                        + params.get("WD" + i + "start" + k + "M"));
                wh.setEnd(
                        params.get("WD" + i + "end" + k + "H") + ":" + params.get("WD" + i + "end" + k + "M"));
                Listwh.add(wh);
                k = k + 1;
            }
            EventsDates cwd = new EventsDates();
            cwd.setDate(params.get("WD" + i));
            cwd.setHours(Listwh);
            workingdays.add(cwd);
            i = i + 1;
        }

        workingtime.setDates(workingdays);
        listComponent.add(workingtime);
    }

    i = 1;
    if (params.containsKey("type" + i)) {

        PricesComponent pc = new PricesComponent();
        ArrayList<TicketPrice> tpList = new ArrayList<TicketPrice>();
        while (params.containsKey("type" + i)) {
            TicketPrice tp = new TicketPrice();
            tp.setType(params.get("type" + i));
            double dp = Double.parseDouble(params.get("price" + i));
            tp.setPrice(dp);
            tp.setType_description(params.get("typedesc" + i));
            tpList.add(tp);
            i = i + 1;
        }
        pc.setPrices(tpList);
        listComponent.add(pc);
    }

    i = 1;
    if (params.containsKey("SERV" + i)) {
        ArrayList<String> servList = new ArrayList<String>();
        while (params.containsKey("SERV" + i)) {
            servList.add(params.get("SERV" + i));
            i = i + 1;
        }
        ServicesComponent servicescomponent = new ServicesComponent();
        servicescomponent.setServicesList(servList);
        listComponent.add(servicescomponent);
    }
    poi.setComponents(listComponent);

    pm.savePoi(poi);

    CompletePOI poi2 = (CompletePOI) pm.findOneCompletePoiByName(poi.getName());

    // POI INGLESE 
    if (params.get("inglese").equals("true")) {
        addeng(params, poi2.getId(), coverimg, img_gallery);
    } else {
        EnCompletePOI enpoi = new EnCompletePOI();
        enpoi.setAddress(poi.getAddress());
        enpoi.setCategories(poi.getCategories());
        enpoi.setId(poi.getId());
        enpoi.setName(poi.getName());
        enpoi.setShortDescription(poi.getShortDescription());
        enpoi.setStart_date(poi.getStart_date());
        enpoi.setEnd_date(poi.getEnd_date());
        double enlat = Double.parseDouble(params.get("latitude"));
        double enlongi = Double.parseDouble(params.get("longitude"));
        poi.setLocation(new double[] { enlat, enlongi });
        enpoi.setComponents(listComponent);

        pm.saveEnPoi(enpoi);
    }
    for (int z = 0; z < files.length; z++) {
        MultipartFile file = files[z];

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "poi" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + links.get(z).getLink());
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {
            return model;
        }
    }
    if (!cover.isEmpty()) {
        MultipartFile file = cover;

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "poi" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + "cover.jpg");
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {
            return model;
        }
    }

    // DELETE IMMAGINI DA CANCELLARE
    if (imgdel != null && imgdel.length > 0) {
        for (int kdel = 0; kdel < imgdel.length; kdel++) {
            delimg(request, poi.getId(), imgdel[kdel]);
        }
    }
    return model;
}

From source file:org.jbpm.formbuilder.server.RESTFormServiceTest.java

public void testSaveFormOK() throws Exception {
    FormEncodingFactory.register(FormEncodingServerFactory.getEncoder(),
            FormEncodingServerFactory.getDecoder());
    RESTFormService restService = new RESTFormService();
    FormDefinitionService formService = EasyMock.createMock(FormDefinitionService.class);
    FormRepresentation form = RESTAbstractTest.createMockForm("formToBeSaved", "param1", "param2", "param3");
    EasyMock.expect(formService.saveForm(EasyMock.eq("somePackage"), EasyMock.eq(form))).andReturn("MY_FORM_ID")
            .once();/*  w w w  . ja  v a 2 s . c o m*/
    restService.setFormService(formService);
    ServletContext context = EasyMock.createMock(ServletContext.class);
    HttpSession session = EasyMock.createMock(HttpSession.class);
    HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(request.getSession()).andReturn(session);
    EasyMock.expect(session.getServletContext()).andReturn(context);

    EasyMock.replay(formService, context, session, request);
    Response resp = restService.saveForm(FormEncodingFactory.getEncoder().encode(form), "somePackage", request);
    EasyMock.verify(formService, context, session, request);

    assertNotNull("resp shouldn't be null", resp);
    assertStatus(resp.getStatus(), Status.CREATED);
    assertNotNull("resp.entity shouldn't be null", resp.getEntity());
    Object entity = resp.getEntity();
    assertNotNull("resp.metadata shouldn't be null", resp.getMetadata());
    Object contentType = resp.getMetadata().getFirst(HttpHeaderNames.CONTENT_TYPE);
    assertNotNull("resp.entity shouldn't be null", contentType);
    assertEquals("contentType should be application/xml but is" + contentType, contentType,
            MediaType.APPLICATION_XML);
    String xml = entity.toString();
    String expected = "<formId>MY_FORM_ID</formId>";
    assertEquals("xml should be " + expected + " but it is " + xml, xml, expected);
}

From source file:org.jbpm.formbuilder.server.RESTFormServiceTest.java

public void testSaveFormItemOK() throws Exception {
    RESTFormService restService = new RESTFormService();
    FormDefinitionService formService = EasyMock.createMock(FormDefinitionService.class);
    FormItemRepresentation item = RESTAbstractTest.createMockForm("formToBeSaved", "param1").getFormItems()
            .iterator().next();/*w  w w. j a v a  2  s .co  m*/
    EasyMock.expect(formService.saveFormItem(EasyMock.eq("somePackage"), EasyMock.eq("MY_FORM_ITEM_ID"),
            EasyMock.eq(item))).andReturn("MY_FORM_ITEM_ID").once();
    restService.setFormService(formService);
    ServletContext context = EasyMock.createMock(ServletContext.class);
    HttpSession session = EasyMock.createMock(HttpSession.class);
    HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(request.getSession()).andReturn(session);
    EasyMock.expect(session.getServletContext()).andReturn(context);

    EasyMock.replay(formService, context, session, request);
    Response resp = restService.saveFormItem(FormEncodingFactory.getEncoder().encode(item), "somePackage",
            "MY_FORM_ITEM_ID", request);
    EasyMock.verify(formService, context, session, request);

    assertNotNull("resp shouldn't be null", resp);
    assertStatus(resp.getStatus(), Status.CREATED);
    assertNotNull("resp.entity shouldn't be null", resp.getEntity());
    Object entity = resp.getEntity();
    assertNotNull("resp.metadata shouldn't be null", resp.getMetadata());
    Object contentType = resp.getMetadata().getFirst(HttpHeaderNames.CONTENT_TYPE);
    assertNotNull("resp.entity shouldn't be null", contentType);
    assertEquals("contentType should be application/xml but is" + contentType, contentType,
            MediaType.APPLICATION_XML);
    String xml = entity.toString();
    String expected = "<formItemId>MY_FORM_ITEM_ID</formItemId>";
    assertEquals("xml should be " + expected + " but it is " + xml, xml, expected);
}

From source file:org.oscarehr.document.web.ManageDocumentAction.java

private void saveDocNote(final HttpServletRequest request, String docDesc, String demog, String documentId) {

    Date now = EDocUtil.getDmsDateTimeAsDate();
    // String docDesc=d.getDocdesc();
    CaseManagementNote cmn = new CaseManagementNote();
    cmn.setUpdate_date(now);/*from  www .  jav  a  2s .  c  o m*/
    cmn.setObservation_date(now);
    cmn.setDemographic_no(demog);
    HttpSession se = request.getSession();
    String user_no = (String) se.getAttribute("user");
    String prog_no = new EctProgram(se).getProgram(user_no);
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(se.getServletContext());
    CaseManagementManager cmm = (CaseManagementManager) ctx.getBean("caseManagementManager");
    cmn.setProviderNo("-1");// set the provider no to be -1 so the editor appear as 'System'.
    Provider provider = EDocUtil.getProvider(user_no);
    String provFirstName = "";
    String provLastName = "";
    if (provider != null) {
        provFirstName = provider.getFirstName();
        provLastName = provider.getLastName();
    }
    String strNote = "Document" + " " + docDesc + " " + "created at " + now + " by " + provFirstName + " "
            + provLastName + ".";

    cmn.setNote(strNote);
    cmn.setSigned(true);
    cmn.setSigning_provider_no("-1");
    cmn.setProgram_no(prog_no);

    SecRoleDao secRoleDao = (SecRoleDao) SpringUtils.getBean("secRoleDao");
    SecRole doctorRole = secRoleDao.findByName("doctor");
    cmn.setReporter_caisi_role(doctorRole.getId().toString());

    cmn.setReporter_program_team("0");
    cmn.setPassword("NULL");
    cmn.setLocked(false);
    cmn.setHistory(strNote);
    cmn.setPosition(0);
    cmm.saveNoteSimple(cmn);
    // Add a noteLink to casemgmt_note_link
    CaseManagementNoteLink cmnl = new CaseManagementNoteLink();
    cmnl.setTableName(CaseManagementNoteLink.DOCUMENT);
    cmnl.setTableId(Long.parseLong(documentId));
    cmnl.setNoteId(Long.parseLong(EDocUtil.getLastNoteId()));
    EDocUtil.addCaseMgmtNoteLink(cmnl);
}

From source file:org.codehaus.wadi.web.TestHttpSession.java

public void testRest(Manager manager) {
    long start = System.currentTimeMillis();
    HttpSession session = ((WADIHttpSession) manager.create(null)).getWrapper();
    long end = System.currentTimeMillis();
    assertTrue(session.getSessionContext().getSession(null) == null);
    assertTrue(session.getSessionContext().getIds() != null);
    session.getServletContext(); // cannot really test unless inside a container... - TODO
    assertTrue(session.getCreationTime() >= start && session.getCreationTime() <= end);
    assertTrue(session.getCreationTime() == session.getLastAccessedTime());
}

From source file:com.pliu.powerbiembed.ReportController.java

@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
public String getReport(ModelMap model, HttpServletRequest httpRequest) {
    HttpSession session = httpRequest.getSession();
    AuthenticationResult result = (AuthenticationResult) session
            .getAttribute(AuthHelper.PRINCIPAL_SESSION_NAME);
    if (result == null) {
        model.addAttribute("//error", new Exception("AuthenticationResult not found in session."));
        return "/error";
    } else {// ww w. ja va 2s . c  om
        try {
            String userid = result.getUserInfo().getDisplayableId();
            // a simple demo of row level security
            String username = "anyone"; //username can't be empty if RLS is enabled on data source
            String roles = "foo"; //empty role means you are authorized to see all data, more secure to default to block all
            if (userid.startsWith("me")) {
                roles = ""; //see everything
            } else if (userid.charAt(0) == 'p') {
                roles = "NWManager";
            } else if (userid.charAt(0) == 'a') {
                username = "adventure-works\\\\pamela0";
                roles = "Sales";
            }
            ServletContext cxt = session.getServletContext();
            String workspaceCollection = cxt.getInitParameter("workspaceCollection");
            String workspaceId = cxt.getInitParameter("workspaceId");
            String accessKey = cxt.getInitParameter("accessKey");
            String resourceId = cxt.getInitParameter("resourceId");
            String reporturl = httpRequest.getParameter("reporturl");
            String accessToken = ComputeJWTToken(workspaceCollection, workspaceId, resourceId, accessKey,
                    reporturl, username, roles);
            model.addAttribute("accessToken", accessToken);
            model.addAttribute("embedUrl", reporturl);
        } catch (Exception e) {
            model.addAttribute("error", e);
            return "/error";
        }
    }
    return "/secure/report";
}

From source file:com.jing.ebike.controller.UserController.java

@RequestMapping(value = "getLocation.do", method = RequestMethod.POST)
@ResponseBody//from ww w .j ava  2s.  c  o m
@Transactional
public GeneralResponse getLocation(String carNum, HttpSession sess, HttpServletRequest request,
        HttpServletResponse response) {
    GeneralResponse message = new GeneralResponse();
    User loginUser = (User) sess.getAttribute("loginUser");
    if (loginUser == null) {
        message.setCode(0);
        return message;
    }
    boolean test = false;
    if (test || "test".equals(loginUser.getUserName())) {
        message.setCode(1);
        Point point = new Point();
        point.setLongitude(120.187766);
        point.setLatitude(30.286877);
        message.setRes(point);
        return message;
    }
    try {
        if (sess.getServletContext().getAttribute("location" + carNum) != null) {
            message.setCode(1);
            Point point = (Point) sess.getServletContext().getAttribute("location" + carNum);
            message.setRes(point);
        } else {
            message.setCode(0);
        }
    } catch (Exception e) {
        message.setCode(0);
        message.setMsg(e.getMessage());
    }
    return message;
}

From source file:org.apache.wookie.WidgetAdminServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    Messages localizedMessages = LocaleHandler.localizeMessages(request);

    IWidgetAdminManager manager = (IWidgetAdminManager) session
            .getAttribute(WidgetAdminManager.class.getName());
    if (manager == null) {
        manager = new WidgetAdminManager(localizedMessages);
        session.setAttribute(WidgetAdminManager.class.getName(), manager);
    }//from  w  ww . j  a v  a  2  s .co m
    Configuration properties = (Configuration) session.getServletContext().getAttribute("properties"); //$NON-NLS-1$

    request.setAttribute("version", properties.getString("widget.version")); //$NON-NLS-1$ //$NON-NLS-2$
    String task = request.getParameter("operation"); //$NON-NLS-1$
    Operation op = null;
    // sanity check...
    if (task != null) {
        // if this is called with a string not contained within the
        // enumerated list an exception is thrown
        try {
            op = Operation.valueOf(task);
        } catch (IllegalArgumentException e) {
            op = null;
            request.setAttribute("error_value", localizedMessages.getString("WidgetAdminServlet.4")); //$NON-NLS-1$ //$NON-NLS-2$            
        }
    }
    if (op != null) {
        switch (op) {
        case ADDNEWWHITELISTENTRY: {
            addWhiteListEntry(request);
            listWhiteListOperation(request);
            doForward(request, response, faddToWhiteListPage);
            break;
        }
        case VIEWWHITELIST: {
            listWhiteListOperation(request);
            if (request.getParameter("param").equalsIgnoreCase("list")) { //$NON-NLS-1$ //$NON-NLS-2$
                doForward(request, response, fViewWhiteListPage);
            } else if (request.getParameter("param").equalsIgnoreCase("add")) { //$NON-NLS-1$ //$NON-NLS-2$
                doForward(request, response, faddToWhiteListPage);
            } else if (request.getParameter("param").equalsIgnoreCase("remove")) { //$NON-NLS-1$ //$NON-NLS-2$
                doForward(request, response, fremoveWhiteListPage);
            }
            break;
        }
        case REMOVEWIDGET: {
            removeWidget(request, properties, manager);
            listOperation(request, false);
            doForward(request, response, fListWidgetsForDeletePage);
            break;
        }
        case REVISETYPES: {
            reviseTypes(request, manager);
            doForward(request, response, fUpLoadResultsPage);
            break;
        }
        case ADDNEWSERVICE: {
            addNewService(request);
            retrieveServices(request);
            doForward(request, response, fAddNewServicesPage);
            break;
        }
        case UPLOADWIDGET: {
            uploadOperation(request, properties, manager);
            doForward(request, response, fUpLoadResultsPage);
            break;
        }
        case LISTWIDGETS: {
            if (request.getParameter("param").equalsIgnoreCase("remove")) { //$NON-NLS-1$ //$NON-NLS-2$
                listOperation(request, false);
                doForward(request, response, fListWidgetsForDeletePage);
            } else {
                listOperation(request, true);
                doForward(request, response, fListWidgetsPage);
            }
            break;
        }
        case LISTSERVICES: {
            retrieveServices(request);
            if (request.getParameter("param").equalsIgnoreCase("list")) { //$NON-NLS-1$ //$NON-NLS-2$
                doForward(request, response, fListServicesPage);
            } else if (request.getParameter("param").equalsIgnoreCase("add")) { //$NON-NLS-1$ //$NON-NLS-2$
                doForward(request, response, fAddNewServicesPage);
            } else if (request.getParameter("param").equalsIgnoreCase("remove")) { //$NON-NLS-1$ //$NON-NLS-2$
                doForward(request, response, fRemoveServicesPage);
            }
            break;
        }
        case SETWIDGETTYPES: {
            updateWidgetTypes(request, manager);
            listOperation(request, true);
            doForward(request, response, fListWidgetsPage);
            break;
        }
        case REMOVESERVICE: {
            removeServiceOperation(request);
            doForward(request, response, fRemoveServicesPage);
            break;
        }
        case REMOVEWHITELISTENTRY: {
            removeWhiteListEntry(request);
            listWhiteListOperation(request);
            doForward(request, response, fremoveWhiteListPage);
            break;
        }
        case REMOVESINGLEWIDGETTYPE: {
            removeSingleWidgetTypeOperation(request, manager);
            listOperation(request, true);
            doForward(request, response, fListWidgetsPage);
            break;
        }
        case SETDEFAULTWIDGET: {
            setDefaultWidgetOperation(request, manager);
            doForward(request, response, fListWidgetsPage);
            break;
        }
        case REGISTERGADGET: {
            registerOperation(request, properties);
            doForward(request, response, fMainPage);
            break;
        }
        case LISTAPIKEYS: {
            listAPIKeysOperation(request);
            doForward(request, response, fListAPIKeysPage);
            break;
        }
        case REVOKEAPIKEY: {
            revokeAPIKeyOperation(request);
            doForward(request, response, fListAPIKeysPage);
            break;
        }
        case DOWNLOADWIDGET: {
            downloadWidget(request, response, properties);
            // doForward(request,response,fDownloadWidgetPage);
            break;
        }

        default: {
            request.setAttribute("error_value", localizedMessages.getString("WidgetAdminServlet.5"));// need to i18n this //$NON-NLS-1$ //$NON-NLS-2$ 
            doForward(request, response, fMainPage);
        }
        }
    } else {
        doForward(request, response, fMainPage);
    }
}

From source file:oscar.oscarEncounter.oscarMeasurements.pageUtil.EctMeasurementsAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    EctMeasurementsForm frm = (EctMeasurementsForm) form;

    HttpSession session = request.getSession();
    //request.getSession().setAttribute("EctMeasurementsForm", frm);

    EctSessionBean bean = (EctSessionBean) request.getSession().getAttribute("EctSessionBean");

    String demographicNo = null;/*  w w  w .  j a va 2s.c o  m*/
    String providerNo = (String) session.getAttribute("user");

    //if form has demo use it since session bean could have been overwritten
    if ((demographicNo = (String) frm.getValue("demographicNo")) == null) {
        if (bean != null)
            demographicNo = bean.getDemographicNo();
    }

    String template = request.getParameter("template");
    MeasurementFlowSheet mFlowsheet = null;
    if (template != null) {
        WebApplicationContext ctx = WebApplicationContextUtils
                .getRequiredWebApplicationContext(session.getServletContext());
        FlowSheetCustomizationDao flowSheetCustomizationDao = (FlowSheetCustomizationDao) ctx
                .getBean("flowSheetCustomizationDao");
        MeasurementTemplateFlowSheetConfig templateConfig = MeasurementTemplateFlowSheetConfig.getInstance();

        List<FlowSheetCustomization> custList = flowSheetCustomizationDao.getFlowSheetCustomizations(template,
                (String) session.getAttribute("user"), demographicNo);
        mFlowsheet = templateConfig.getFlowSheet(template, custList);
    }

    //request.getSession().setAttribute("EctSessionBean", bean);
    //TODO replace with a date format call.  Actually revamp to use hibernate
    java.util.Calendar calender = java.util.Calendar.getInstance();
    String day = Integer.toString(calender.get(java.util.Calendar.DAY_OF_MONTH));
    String month = Integer.toString(calender.get(java.util.Calendar.MONTH) + 1);
    String year = Integer.toString(calender.get(java.util.Calendar.YEAR));
    String hour = Integer.toString(calender.get(java.util.Calendar.HOUR_OF_DAY));
    String min = Integer.toString(calender.get(java.util.Calendar.MINUTE));
    String second = Integer.toString(calender.get(java.util.Calendar.SECOND));
    String dateEntered = year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + second;

    String numType = (String) frm.getValue("numType");
    int iType = Integer.parseInt(numType);

    MsgStringQuote str = new MsgStringQuote();

    Properties p = (Properties) session.getAttribute("providerBean");
    String by = "";
    if (p != null) {
        by = p.getProperty(providerNo, "");
    }

    String textOnEncounter = ""; //"**"+StringUtils.rightPad(by,80,"*")+"\\n";

    //if parent window content has changed then we need to propagate change so
    //we do not write to parent
    String parentChanged = (String) frm.getValue("parentChanged");
    request.setAttribute("parentChanged", parentChanged);

    boolean valid = true;
    try {

        EctValidation ectValidation = new EctValidation();
        ActionMessages errors = new ActionMessages();

        String inputValueName, inputTypeName, inputTypeDisplayName, mInstrcName, commentsName;
        String dateName, validationName, inputValue, inputType, inputTypeDisplay, mInstrc;
        String comments, dateObserved, validation;

        String regExp = null;
        double dMax = 0;
        double dMin = 0;
        int iMax = 0;
        int iMin = 0;

        ResultSet rs;
        String regCharExp;
        //goes through each type to check if the input value is valid
        for (int i = 0; i < iType; i++) {
            inputValueName = "inputValue-" + i;
            inputTypeName = "inputType-" + i;
            inputTypeDisplayName = "inputTypeDisplayName-" + i;
            mInstrcName = "inputMInstrc-" + i;
            commentsName = "comments-" + i;
            dateName = "date-" + i;
            inputValue = (String) frm.getValue(inputValueName);
            inputType = (String) frm.getValue(inputTypeName);
            inputTypeDisplay = (String) frm.getValue(inputTypeDisplayName);
            mInstrc = (String) frm.getValue(mInstrcName);
            comments = (String) frm.getValue(commentsName);
            dateObserved = (String) frm.getValue(dateName);

            regExp = null;
            dMax = 0;
            dMin = 0;
            iMax = 0;
            iMin = 0;

            rs = ectValidation.getValidationType(inputType, mInstrc);
            regCharExp = ectValidation.getRegCharacterExp();

            if (rs.next()) {
                dMax = rs.getDouble("maxValue");
                dMin = rs.getDouble("minValue");
                iMax = rs.getInt("maxLength");
                iMin = rs.getInt("minLength");
                regExp = oscar.Misc.getString(rs, "regularExp");
            }
            rs.close();

            if (!ectValidation.isInRange(dMax, dMin, inputValue)) {
                errors.add(inputValueName, new ActionMessage("errors.range", inputTypeDisplay,
                        Double.toString(dMin), Double.toString(dMax)));
                saveErrors(request, errors);
                valid = false;
            }
            if (!ectValidation.maxLength(iMax, inputValue)) {
                errors.add(inputValueName,
                        new ActionMessage("errors.maxlength", inputTypeDisplay, Integer.toString(iMax)));
                saveErrors(request, errors);
                valid = false;
            }
            if (!ectValidation.minLength(iMin, inputValue)) {
                errors.add(inputValueName,
                        new ActionMessage("errors.minlength", inputTypeDisplay, Integer.toString(iMin)));
                saveErrors(request, errors);
                valid = false;
            }

            if (!ectValidation.matchRegExp(regExp, inputValue)) {
                errors.add(inputValueName, new ActionMessage("errors.invalid", inputTypeDisplay));
                saveErrors(request, errors);
                valid = false;
            }
            if (!ectValidation.isValidBloodPressure(regExp, inputValue)) {
                errors.add(inputValueName, new ActionMessage("error.bloodPressure"));
                saveErrors(request, errors);
                valid = false;
            }
            if (!ectValidation.isDate(dateObserved) && inputValue.compareTo("") != 0) {
                errors.add(dateName, new ActionMessage("errors.invalidDate", inputTypeDisplay));
                saveErrors(request, errors);
                valid = false;
            }
        }

        //Write to database and to encounter form if all the input values are valid
        if (valid) {
            for (int i = 0; i < iType; i++) {

                inputValueName = "inputValue-" + i;
                inputTypeName = "inputType-" + i;
                mInstrcName = "inputMInstrc-" + i;
                commentsName = "comments-" + i;
                validationName = "validation-" + i;
                dateName = "date-" + i;

                inputValue = (String) frm.getValue(inputValueName);
                inputType = (String) frm.getValue(inputTypeName);
                mInstrc = (String) frm.getValue(mInstrcName);
                comments = (String) frm.getValue(commentsName);
                comments = org.apache.commons.lang.StringEscapeUtils.escapeSql(comments);
                validation = (String) frm.getValue(validationName);
                dateObserved = (String) frm.getValue(dateName);

                org.apache.commons.validator.GenericValidator gValidator = new org.apache.commons.validator.GenericValidator();
                if (!GenericValidator.isBlankOrNull(inputValue)) {
                    //Find if the same data has already been entered into the system
                    String sql = "SELECT * FROM measurements WHERE demographicNo='" + demographicNo
                            + "' AND dataField='" + inputValue + "' AND measuringInstruction='" + mInstrc
                            + "' AND comments='" + comments + "' AND dateObserved='" + dateObserved
                            + "' and type = '" + inputType + "'";

                    rs = DBHandler.GetSQL(sql);
                    if (!rs.next()) {
                        //Write to the Dababase if all input values are valid
                        sql = "INSERT INTO measurements"
                                + "(type, demographicNo, providerNo, dataField, measuringInstruction, comments, dateObserved, dateEntered)"
                                + " VALUES ('" + str.q(inputType) + "','" + str.q(demographicNo) + "','"
                                + str.q(providerNo) + "','" + str.q(inputValue) + "','" + str.q(mInstrc) + "','"
                                + str.q(comments) + "','" + str.q(dateObserved) + "','" + str.q(dateEntered)
                                + "')";

                        DBHandler.RunSQL(sql);
                        //prepare input values for writing to the encounter form
                        if (mFlowsheet == null) {
                            textOnEncounter = textOnEncounter + inputType + "    " + inputValue + " " + mInstrc
                                    + " " + comments + "\\n";
                        } else {
                            textOnEncounter += mFlowsheet.getFlowSheetItem(inputType).getDisplayName() + "    "
                                    + inputValue + " " + comments + "\\n";
                        }
                    }
                    rs.close();
                }

            }
            // textOnEncounter = textOnEncounter + "**********************************************************************************\\n";

        } else {
            String groupName = (String) frm.getValue("groupName");
            String css = (String) frm.getValue("css");
            request.setAttribute("groupName", groupName);
            request.setAttribute("css", css);
            return (new ActionForward(mapping.getInput()));
        }
        /* select the correct db specific command */
        String db_type = OscarProperties.getInstance().getProperty("db_type").trim();
        String dbSpecificCommand;
        if (db_type.equalsIgnoreCase("mysql")) {
            dbSpecificCommand = "SELECT LAST_INSERT_ID()";
        } else if (db_type.equalsIgnoreCase("postgresql")) {
            dbSpecificCommand = "SELECT CURRVAL('consultationrequests_numeric')";
        } else
            throw new SQLException("ERROR: Database " + db_type + " unrecognized.");
    } catch (SQLException e) {
        MiscUtils.getLogger().error("Error", e);
    }

    //put the inputvalue to the encounter form
    session.setAttribute("textOnEncounter", textOnEncounter);

    return mapping.findForward("success");
}