Example usage for javax.servlet.http HttpServletRequest getUserPrincipal

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

Introduction

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

Prototype

public java.security.Principal getUserPrincipal();

Source Link

Document

Returns a java.security.Principal object containing the name of the current authenticated user.

Usage

From source file:org.rti.zcore.dar.struts.action.ListAction.java

protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    //      Extract attributes we will need
    HttpSession session = request.getSession();
    Principal user = request.getUserPrincipal();
    String username = user.getName();
    Form encounterForm;//from  w w w.java  2  s.co  m
    BaseEncounter encounter = null;
    Map encMap = null;
    Long formId = null;
    Long patientId = null;
    Long eventId = null;
    String constraintClause = null;
    Long constraintLong = null;
    String detailName = null;
    BaseSessionSubject sessionPatient = null;
    Integer maxRows = 0;
    Integer offset = 0;
    Integer prevRows = 0;
    Integer nextRows = 0;
    Connection conn = null;
    String className = null;
    try {
        conn = DatabaseUtils.getZEPRSConnection(username);
        if (request.getParameter("formId") != null) {
            formId = Long.decode(request.getParameter("formId"));
        } else if (request.getAttribute("formId") != null) {
            formId = Long.decode(request.getAttribute("formId").toString());
        }
        if (request.getParameter("className") != null) {
            className = request.getParameter("className");
            formId = (Long) DynaSiteObjects.getFormNameMap().get(className);
        } else if (request.getAttribute("className") != null) {
            className = (String) request.getAttribute("className");
            formId = (Long) DynaSiteObjects.getFormNameMap().get(className);
        }
        if (request.getParameter("constraintClause") != null) {
            constraintClause = request.getParameter("constraintClause");
        } else if (request.getAttribute("constraintClause") != null) {
            constraintClause = request.getAttribute("constraintClause").toString();
        }
        if (request.getParameter("constraintLong") != null) {
            constraintLong = Long.decode(request.getParameter("constraintLong"));
        } else if (request.getAttribute("constraintLong") != null) {
            constraintLong = Long.decode(request.getAttribute("constraintLong").toString());
        }
        if (request.getParameter("maxRows") != null) {
            maxRows = Integer.decode(request.getParameter("maxRows"));
        } else if (request.getAttribute("maxRows") != null) {
            maxRows = Integer.decode(request.getAttribute("maxRows").toString());
        } else {
            if (formId != null) {
                switch (formId.intValue()) {
                case 128:
                    maxRows = 0;
                    break;
                case 129:
                    maxRows = 0;
                    break;
                case 130:
                    maxRows = 0;
                    break;
                case 131:
                    maxRows = 0;
                    break;
                case 181:
                    maxRows = 0;
                    break;

                default:
                    maxRows = 20;
                    break;
                }
            } else {
                maxRows = 20;
            }
        }
        if (request.getParameter("offset") != null) {
            offset = Integer.decode(request.getParameter("offset"));
        } else if (request.getAttribute("offset") != null) {
            offset = Integer.decode(request.getAttribute("offset").toString());
        }
        if (request.getParameter("prevRows") != null) {
            prevRows = Integer.decode(request.getParameter("prevRows"));
            offset = prevRows;
        } else if (request.getAttribute("prevRows") != null) {
            prevRows = Integer.decode(request.getAttribute("prevRows").toString());
            offset = prevRows;
        }
        if (request.getParameter("nextRows") != null) {
            nextRows = Integer.decode(request.getParameter("nextRows"));
        } else if (request.getAttribute("nextRows") != null) {
            nextRows = Integer.decode(request.getAttribute("nextRows").toString());
        }
        if (mapping.getParameter() != null && !mapping.getParameter().equals("")) {
            String formName = mapping.getParameter();
            formId = (Long) DynaSiteObjects.getFormNameMap().get(formName);
        }
        // Admin pages usually do not have a sessionPatient. This is a hack to use code that uses sessionPatient.
        sessionPatient = new TimsSessionSubject();
        SessionUtil.getInstance(session).setSessionPatient(sessionPatient);

        encounterForm = ((Form) DynaSiteObjects.getForms().get(new Long(formId)));
        Long formTypeId = encounterForm.getFormTypeId();
        // populate the records for this class
        List items = null;
        if (className != null && className.equals("MenuItem")) {
            items = DynaSiteObjects.getMenuItemList(); //must be sorted
        } else {
            String classname = StringManipulation.fixClassname(encounterForm.getName());
            Class clazz = null;
            try {
                clazz = Class.forName(Constants.getDynasiteFormsPackage() + "." + classname);
            } catch (ClassNotFoundException e1) {
                if (classname.equals("UserInfo")) {
                    clazz = Class.forName("org.rti.zcore." + classname);
                }
            }

            try {
                String orderBy = "id DESC";
                switch (formTypeId.intValue()) {
                case 5: // admin
                    if (constraintLong != null) {
                        /*if (formId == 161) { // stock
                           // Get the item - form 131
                           Class clazz = Class.forName(DynaSiteObjects.getDynasiteFormsPackage() + ".Item");
                           Item stockItem = (Item) EncountersDAO.getOne(conn, constraintLong, "SQL_RETRIEVE_ONE_ADMIN131", clazz);
                           detailName = stockItem.getField2153();
                           request.setAttribute("detailName", detailName);
                        }*/
                        //String orderBy = "id DESC";
                        items = EncountersDAO.getAllConstraintOrderBy(conn, formId,
                                "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, constraintClause, constraintLong,
                                orderBy);
                    } else {
                        if (formId == 161) { // stock
                            //items = EncountersDAO.getAll(conn, formId, "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, maxRows, offset, "id DESC");
                            if (maxRows == 0) {
                                items = EncountersDAO.getAllOrderBy(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, orderBy);
                            } else {
                                items = EncountersDAO.getAll(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset,
                                        orderBy);
                            }
                        } else if (formId == 128) { // regimen groups
                            //items = EncountersDAO.getAll(conn, formId, "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset, "name ");
                            if (maxRows == 0) {
                                items = EncountersDAO.getAllOrderBy(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, "name ");
                            } else {
                                items = EncountersDAO.getAll(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset,
                                        "name ");
                            }
                        } else if (formId == 129) { // regimen
                            //items = EncountersDAO.getAll(conn, formId, "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset, "code ");
                            if (maxRows == 0) {
                                items = EncountersDAO.getAllOrderBy(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, "code ");
                            } else {
                                items = EncountersDAO.getAll(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset,
                                        "code ");
                            }
                        } else if (formId == 130) { // item groups
                            //items = EncountersDAO.getAll(conn, formId, "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset, "name ");
                            if (maxRows == 0) {
                                items = EncountersDAO.getAllOrderBy(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, "name ");
                            } else {
                                items = EncountersDAO.getAll(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset,
                                        "name ");
                            }
                        } else {
                            if (className != null && className.equals("MenuItem")) {
                                items = DynaSiteObjects.getMenuItemList(); //must be sorted
                            } else {
                                if (formId == 181) {
                                    orderBy = "regimen_id DESC";
                                    if (maxRows == 0) {
                                        //items = EncountersDAO.getAllOrderBy(conn, formId, "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, orderBy);
                                        String sql = "SELECT rb.id, rb.regimen_id AS regimen_id, item_id AS item_id, r.code "
                                                + "FROM regimen_item_bridge rb, regimen r "
                                                + "WHERE rb.regimen_id = r.id ORDER BY r.code ASC";
                                        ArrayList values = new ArrayList();
                                        items = DatabaseUtils.getList(conn, clazz, sql, values);
                                    } else {
                                        items = EncountersDAO.getAll(conn, formId,
                                                "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset,
                                                orderBy);
                                    }
                                } else {
                                    if (maxRows == 0) {
                                        items = EncountersDAO.getAllOrderBy(conn, formId,
                                                "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, orderBy);
                                    } else {
                                        items = EncountersDAO.getAll(conn, formId,
                                                "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset,
                                                orderBy);
                                    }
                                }
                            }
                        }
                    }
                    break;
                case 8: // list - for patients
                    items = EncountersDAO.getAll(conn, formId, "SQL_RETRIEVEALL" + formId, clazz, maxRows,
                            offset);
                    break;
                default:
                    items = EncountersDAO.getAll(conn, formId, "SQL_RETRIEVE_ALL" + formId, clazz, maxRows,
                            offset);
                    break;
                }
            } catch (IOException e) {
                request.setAttribute("exception", e);
                return mapping.findForward("error");
            } catch (ServletException e) {
                request.setAttribute("exception", e);
                return mapping.findForward("error");
            } catch (SQLException e) {
                request.setAttribute("exception", e);
                return mapping.findForward("error");
            }
        }

        if (maxRows == 0) {
            request.setAttribute("noNavigationWidget", "1");
        } else {
            request.setAttribute("maxRows", maxRows);
            nextRows = offset + maxRows;
            if (items.size() < maxRows) {
                if (offset == 0) {
                    request.setAttribute("noNavigationWidget", "1");
                }
            } else {
                request.setAttribute("offset", nextRows);
            }

            if (offset - maxRows >= 0) {
                prevRows = offset - maxRows;
                request.setAttribute("prevRows", prevRows);
            }
            request.setAttribute("nextRows", nextRows);
        }
        // Attach a map of encounter values that has enumerations already resolved.
        Form encForm = (Form) DynaSiteObjects.getForms().get(encounterForm.getId());
        for (int i = 0; i < items.size(); i++) {
            encounter = (EncounterData) items.get(i);
            // Form encForm = (Form) DynaSiteObjects.getForms().get(encounter.getFormId());
            encMap = PatientRecordUtils.getEncounterMap(encForm, encounter, "fieldId");

            encounter.setEncounterMap(encMap);
        }
        if (items.size() > 0) {
            request.setAttribute("chartItems", items);
            request.setAttribute("formId", encounterForm.getId());
            // loading of body onload DWRUtil.useLoadingMessage()
            request.setAttribute("dwr", 1);
        }

        // Process the dynamic dropdown lists.
        HashMap listMap = new HashMap();
        Form inlineForm = null;
        HashMap<Long, StockReport> balanceMap = null;
        if (DynaSiteObjects.getStatusMap().get("balanceMap") != null) {
            balanceMap = (HashMap<Long, StockReport>) DynaSiteObjects.getStatusMap().get("balanceMap");
        }
        for (Iterator iterator = encounterForm.getPageItems().iterator(); iterator.hasNext();) {
            PageItem pageItem = (PageItem) iterator.next();
            FormField formField = pageItem.getForm_field();
            String identifier = formField.getIdentifier();

            if (pageItem.getInputType().equals("dropdown") || pageItem.getInputType().equals("dropdown-add-one")
                    || pageItem.getInputType().equals("dropdown_site")) {
                String dropdownConstraint = null;
                String pageItemDropdownConstraint = pageItem.getDropdownConstraint();
                if (pageItemDropdownConstraint != null && pageItemDropdownConstraint.endsWith("'siteAbbrev'")) {
                    String siteAbbrev = SessionUtil.getInstance(session).getClientSettings().getSite()
                            .getAbbreviation();
                    dropdownConstraint = pageItemDropdownConstraint.replace("'siteAbbrev'",
                            "'" + siteAbbrev + "'");
                } else {
                    dropdownConstraint = pageItemDropdownConstraint;
                }
                List<DropdownItem> list = WidgetUtils.getList(conn, pageItem.getDropdownTable(),
                        pageItem.getDropdownColumn(), dropdownConstraint, pageItem.getDropdownOrderByClause(),
                        DropdownItem.class, pageItem.getFkIdentifier());
                String formName = encForm.getClassname();
                if (formName.equals("StockControl")) {
                    for (DropdownItem dropdownItem : list) {
                        if (balanceMap != null) {
                            String itemIdStr = dropdownItem.getDropdownId();
                            Long itemId = Long.valueOf(itemIdStr);
                            StockReport stockReport = balanceMap.get(itemId);
                            Integer balance = 0;
                            if (stockReport != null) {
                                balance = stockReport.getBalanceBF();
                                String label = dropdownItem.getDropdownValue();
                                if (balance <= 0) {
                                    String value = dropdownItem.getDropdownValue();
                                    dropdownItem
                                            .setDropdownValue(value + " ** Out of Stock ** Bal: " + balance);
                                } else {
                                    dropdownItem.setDropdownValue(label + " Bal: " + balance);
                                }
                            }
                        }
                    }
                }
                listMap.put(pageItem.getId(), list);
                if (pageItem.getInputType().equals("dropdown-add-one")) {
                    String classNameString = StringManipulation.fixClassname(pageItem.getDropdownTable());
                    Long inlineFormId = (Long) DynaSiteObjects.getFormNameMap().get(classNameString);
                    inlineForm = ((Form) DynaSiteObjects.getForms().get(new Long(inlineFormId)));
                    // Create a list of fieldnames for inline forms.
                    ArrayList<String> inlineFields = new ArrayList<String>();
                    for (Iterator iterator2 = inlineForm.getPageItems().iterator(); iterator2.hasNext();) {
                        PageItem pageItem2 = (PageItem) iterator2.next();
                        if (pageItem2.getForm_field().isEnabled() == true
                                && !pageItem2.getForm_field().getType().equals("Display")) {
                            inlineFields.add(pageItem2.getForm_field().getIdentifier());
                        }
                    }
                    request.setAttribute("inlineForm_" + identifier, inlineForm);
                    request.setAttribute("inlineFields_" + identifier, inlineFields);
                    // loading of body onload DWRUtil.useLoadingMessage()
                    request.setAttribute("dwr", 1);
                }
            }
        }

        request.setAttribute("listMap", listMap);

        request.setAttribute("encounterForm", encounterForm);

        List sites = DynaSiteObjects.getClinics();
        request.setAttribute("sites", sites);

        if (Constants.STOCK_PROBLEMS_ENABLED != null && Constants.STOCK_PROBLEMS_ENABLED.equals("true")) {
            //List<Task> stockAlertList = PatientRecordUtils.getStockAlerts();
            List<Task> stockAlertList = null;
            if (DynaSiteObjects.getStatusMap().get("stockAlertList") != null) {
                stockAlertList = (List<Task>) DynaSiteObjects.getStatusMap().get("stockAlertList");
            }
            request.setAttribute("activeProblems", stockAlertList);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }
    return mapping.findForward("success");
}

From source file:de.thorstenberger.examServer.webapp.action.PDFBulkExport.java

@Override
public ActionForward execute(final ActionMapping mapping, final ActionForm form,
        final HttpServletRequest request, final HttpServletResponse response) throws Exception {

    final ActionMessages errors = new ActionMessages();

    // locate the taskdef to use
    long taskId;/*  w  ww .ja va2 s.  c  om*/
    try {
        taskId = Long.parseLong(request.getParameter("taskId"));
    } catch (final NumberFormatException e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("invalid.parameter"));
        saveErrors(request, errors);
        return mapping.findForward("error");
    }

    final TaskManager tm = (TaskManager) getBean("TaskManager");
    final TaskDef td = tm.getTaskDef(taskId);
    final UserManager userManager = (UserManager) getBean("userManager");

    if (request.getUserPrincipal() == null) {
        throw new RuntimeException("Not logged in.");
    }
    // we only know how to handle complextasks yet
    if (td.getType().equals(TaskContants.TYPE_COMPLEX)) {
        // initialize web crawler
        final PDFExporter pdfExporter = new PDFExporter(userManager, tm);

        // show an error message if tomcat isn't configured appropriately
        if (!pdfExporter.isAvailableWithoutCertificate()) {
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("invalid.serverconfig"));
            saveErrors(request, errors);
            return mapping.findForward("error");
        }
        // set response headers to declare pdf content type
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=" + getBulkFilename(td));
        // locate the taskdef
        TaskDef_Complex ctd;
        try {
            ctd = (TaskDef_Complex) td;
        } catch (final ClassCastException e) {
            throw new RuntimeException("invalid type: \"" + td.getType() + "\", " + e.getMessage());
        }
        // write headers, start streaming to the client
        response.flushBuffer();

        // get all tasklets for the given taskdef
        final List<Tasklet> tasklets = tm.getTaskletContainer().getTasklets(taskId);
        log.info(String.format("Exporting %d pdfs for taskdef \"%s\"", tasklets.size(), ctd.getTitle()));

        renderAllPdfs(tasklets, response.getOutputStream(), pdfExporter);
        return null;
    } else {
        throw new RuntimeException("unsupported type: \"" + td.getType() + "\"");
    }

}

From source file:nl.b3p.kaartenbalie.struts.UserAction.java

protected User getUser(DynaValidatorForm dynaForm, HttpServletRequest request, boolean createNew)
        throws Exception {

    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();

    User sessUser = (User) request.getUserPrincipal();
    // Alleen beheeders mogen iemand anders bewerken
    if (!request.isUserInRole(Roles.ADMIN) && !createNew) {
        if (sessUser == null) {
            return null;
        }/*  ww  w.  j  a v a  2 s  .co  m*/
        return (User) em.createQuery("from User u where u.id = :id").setParameter("id", sessUser.getId())
                .getSingleResult();
    }

    User user = null;
    Integer id = getID(dynaForm);
    if (null == id && createNew) {
        user = new User();
    } else if (null != id) {
        user = (User) em.find(User.class, new Integer(id.intValue()));
    }

    if (user == null) {
        return sessUser;
    }
    return user;
}

From source file:org.rti.zcore.dar.struts.action.DeleteEncounterAction.java

/**
 * Special handling for form id 170 - user info form.
 *//*from  w  w  w.ja  v a  2  s.  co  m*/
protected ActionForward doExecute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession();
    Site site = SessionUtil.getInstance(session).getClientSettings().getSite();
    Principal user = request.getUserPrincipal();
    String username = user.getName();
    Connection conn = null;

    Long encounterId = null;
    String userrecord = null;
    Long patientId = null;
    Long formId = null;
    String formName = null;
    Integer deps = null;
    String forwardString = null; // Pass forward if you want to override the forward.
    if (request.getParameter("formId") != null) {
        formId = Long.valueOf(request.getParameter("formId"));
        formName = DynaSiteObjects.getFormIdClassNameMap().get(formId);
    }
    //formId = (Long) DynaSiteObjects.getFormNameMap().get(formName);
    if (request.getParameter("encounterId") != null) {
        //if (formName.equals("UserInfo")) {
        //   userrecord = String.valueOf(request.getParameter("encounterId"));
        //} else {
        encounterId = Long.valueOf(request.getParameter("encounterId"));
        //}
    }
    if (request.getParameter("patientId") != null) {
        patientId = Long.valueOf(request.getParameter("patientId"));
    }

    if (request.getParameter("deps") != null) {
        deps = Integer.valueOf(request.getParameter("deps"));
    }
    if (request.getParameter("forward") != null) {
        forwardString = String.valueOf(request.getParameter("forward"));
    }

    Form form = (Form) DynaSiteObjects.getForms().get(Long.valueOf(formId));

    try {
        conn = DatabaseUtils.getZEPRSConnection(Constants.DATABASE_ADMIN_USERNAME);
        //if ((encounterId != null && formId != null) || formId == 170) {
        if (encounterId != null) {
            EncounterData encounter = null;
            try {
                //if (formName.equals("UserInfo")) {
                //   PatientRecordUtils.deleteUser(conn, userrecord);
                //} else {
                // If this is a MenuItem, save the MenuItem list to xml and refresh DynasiteObjects
                formName = form.getClassname();
                if (!formName.equals("MenuItem")) {
                    try {
                        encounter = (EncounterData) EncountersDAO.getOneById(conn, encounterId);
                    } catch (ObjectNotFoundException e) {
                        // it's ok - may be an admin record.
                    }
                    String eventUuid = null;
                    if (encounter != null) {
                        if (patientId == null) {
                            patientId = encounter.getPatientId();
                        } else {
                            if (encounter.getPatientId() == null) {
                                // this is an admin form - probably a relationship.
                                encounter.setPatientId(patientId);
                            }
                        }

                        //Long eventId = encounter.getEventId();
                        eventUuid = encounter.getEventUuid();
                        formId = encounter.getFormId();
                        // this could be an admin record, which is will not have patientId or pregnancyId
                        if (patientId != null) {
                            //PatientStatusReport psr = PatientStatusDAO.getOne(conn, patientId);
                            Patient patient = PatientDAO.getOne(conn, patientId);
                            //Long currentFlowEncounterId = patient.getCurrentFlowEncounterId();
                            String currentFlowEncounterUuid = patient.getCurrentFlowEncounterUuid();
                            if (formId.longValue() == 1) {
                                String message = "You may not delete the patient registration record. "
                                        + "Delete the whole patient record instead by clicking the \"Delete Patient\" link\n"
                                        + "on the Demographics page.";
                                request.setAttribute("exception", message);
                                return mapping.findForward("error");
                            }
                            List outcomes = OutcomeDAO.getAllforEncounter(conn, encounterId);

                            if (outcomes.size() > 0) {
                                if (deps != null && deps.intValue() == 1) {
                                    for (int i = 0; i < outcomes.size(); i++) {
                                        OutcomeImpl outcome = (OutcomeImpl) outcomes.get(i);
                                        OutcomeDAO.deleteOne(conn, outcome.getId());
                                    }
                                } else {
                                    String url = "/" + Constants.APP_NAME
                                            + "/admin/deleteEncounter.do;jsessionid=" + session.getId()
                                            + "?encounterId=" + encounterId + "&formId=" + formName + "&deps=1";
                                    String message = "<p>This record has system-generated problems.  "
                                            + "Are you sure you want to delete it?.</p>" + "<p><a href=\"" + url
                                            + "\">Delete</a></p>";
                                    request.setAttribute("exception", message);
                                    return mapping.findForward("error");
                                }
                            }

                            // Test to see if you are deleting the most recent encounter.
                            //if (encounterId.longValue() == currentFlowEncounterId.longValue()) {
                            if (encounter.getUuid().equals(currentFlowEncounterUuid)) {
                                // Find the previous encounter
                                EncounterData encounterData = EncountersDAO.getPreviousEncounter(conn,
                                        patientId, eventUuid, encounterId);
                                Long prevEncId = encounterData.getId();
                                if (prevEncId != null) {
                                    // re-assign values in patient status
                                    Long currentFlowId = encounterData.getFlowId();
                                    Map queries = QueryLoader.instance()
                                            .load("/" + Constants.SQL_PATIENT_PROPERTIES);
                                    String sqlUpdateStatus = (String) queries.get("SQL_MODIFY_STATUS");
                                    EncounterData vo = new EncounterData(); // dummy EncounterData is OK.
                                    vo.setUuid(encounterData.getUuid());
                                    PatientStatusDAO.updatePatientStatus(conn, vo, currentFlowId, prevEncId,
                                            username, site.getId(), patientId, sqlUpdateStatus);
                                } else {
                                    String message = "Unable to delete this record - please contact the system administrator. ";
                                    request.setAttribute("exception", message);
                                    return mapping.findForward("error");
                                }
                            }
                        }
                    }

                    EncounterData vo = new EncounterData(); // dummy EncounterData is OK.
                    vo.setPatientId(patientId);
                    //vo.setEventId(eventId);
                    vo.setEventUuid(eventUuid);

                    // DAR-specific code for stock and regimen-related forms - deletes only its associated table record
                    if (formId == 128 || formId == 129 || formId == 130 || formId == 131 || formId == 181) {
                        deleteFromSingleTable(site, username, conn, encounterId, formId, encounter);
                    } else {
                        try {
                            PatientRecordUtils.deleteEncounter(conn, formId, encounterId, username, site, vo,
                                    null);
                        } catch (Exception e) {
                            request.setAttribute("exception", e);
                            return mapping.findForward("error");
                        }
                    }

                } else {
                    // If this is a MenuItem, save the MenuItem list to xml and refresh DynasiteObjects
                    ArrayList<MenuItem> menuItemList = DynaSiteObjects.getMenuItemList();
                    int index = 0;
                    for (MenuItem menuItem : menuItemList) {
                        if (encounterId.intValue() == menuItem.getId().intValue()) {
                            index = menuItemList.indexOf(menuItem);
                            //EncounterData encounterMenuItem = (EncounterData) EncountersDAO.getOne(conn, encounterId, "SQL_RETRIEVE_ONE_ADMIN" + formId, MenuItem.class);
                            //MenuItem menuItem = (MenuItem) encounterMenuItem;
                            String templateKey = menuItem.getTemplateKey();

                            //ignore property files for spacer deletion
                            if (templateKey != null) {
                                Boolean dev = DynaSiteObjects.getDev();
                                String pathName = null;
                                String deployPathname = null;

                                if (dev == true) {
                                    pathName = Constants.DEV_RESOURCES_PATH;
                                    deployPathname = Constants.DYNASITE_RESOURCES_PATH;
                                } else {
                                    pathName = Constants.DYNASITE_RESOURCES_PATH;
                                }

                                SortedProperties properties = null;
                                ApplicationDefinition applicationDefinition = DynaSiteObjects
                                        .getApplicationDefinition();
                                ArrayList<String> localeList = applicationDefinition.getLocalList();
                                ;
                                //loop through all property fields and delete this property
                                if (applicationDefinition != null) {
                                    localeList = applicationDefinition.getLocalList();
                                    properties = new SortedProperties();
                                    for (String locale : localeList) {
                                        try {
                                            properties.load(
                                                    new FileInputStream(pathName + Constants.MENU_ITEM_FILENAME
                                                            + "_" + locale + ".properties"));
                                            properties.remove(templateKey);
                                            properties.store(
                                                    new FileOutputStream(pathName + Constants.MENU_ITEM_FILENAME
                                                            + "_" + locale + ".properties"),
                                                    "Deletion by admin");
                                            properties.clear();
                                        } catch (Exception e) {
                                        }
                                    }
                                    properties.clear();
                                    String defaultLocale = applicationDefinition.getDefaultLocale();
                                    if (defaultLocale != null) {
                                        try {
                                            properties.load(
                                                    new FileInputStream(pathName + Constants.MENU_ITEM_FILENAME
                                                            + "_" + defaultLocale + ".properties"));
                                            properties.remove(templateKey);
                                            properties.store(
                                                    new FileOutputStream(pathName + Constants.MENU_ITEM_FILENAME
                                                            + "_" + defaultLocale + ".properties"),
                                                    "Deletion by admin");
                                            properties.clear();
                                        } catch (FileNotFoundException e) {
                                            // not created yet.
                                        }
                                    }
                                    properties.clear();
                                    properties.load(new FileInputStream(
                                            pathName + Constants.MENU_ITEM_FILENAME + ".properties"));
                                    properties.remove(templateKey);
                                    properties.store(
                                            new FileOutputStream(
                                                    pathName + Constants.MENU_ITEM_FILENAME + ".properties"),
                                            "Deletion by admin");
                                    properties.clear();
                                }

                                //Properties properties = new Properties();
                                String selectedLocale = (String) request.getAttribute("defaultLocale");

                                boolean isDefaultLocale = false;
                                try {
                                    properties.load(new FileInputStream(pathName + Constants.MENU_ITEM_FILENAME
                                            + "_" + selectedLocale + ".properties"));
                                    //isDefaultLocale = true;
                                } catch (FileNotFoundException e) {
                                    try {
                                        properties.load(new FileInputStream(
                                                pathName + Constants.MENU_ITEM_FILENAME + ".properties"));
                                    } catch (FileNotFoundException e1) {
                                        e.printStackTrace();
                                    }
                                }
                                properties.remove(templateKey);
                                properties.store(new FileOutputStream(pathName + Constants.MENU_ITEM_FILENAME
                                        + (isDefaultLocale ? "_" + selectedLocale : "") + ".properties"),
                                        "New Entry");

                                // copy to tomcat as well if in dev mode
                                if (dev) {
                                    for (String locale : localeList) {
                                        try {
                                            FileUtils.copyQuick(
                                                    pathName + Constants.MENU_ITEM_FILENAME + "_" + locale
                                                            + ".properties",
                                                    deployPathname + Constants.MENU_ITEM_FILENAME + "_" + locale
                                                            + ".properties");
                                        } catch (Exception e) {
                                        }
                                        try {
                                            FileUtils.copyQuick(
                                                    pathName + Constants.MENU_ITEM_FILENAME + ".properties",
                                                    deployPathname + Constants.MENU_ITEM_FILENAME
                                                            + ".properties");
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    menuItemList.remove(index);
                    DisplayOrderComparator doc = new DisplayOrderComparator();
                    Collections.sort(menuItemList, doc);
                    DynasiteUtils.refreshMenuItemList();
                }
                //}

                // part of reload prevention scheme:
                resetToken(request);
                StrutsUtils.removeFormBean(mapping, request);
                // return mapping.findForward("patientHome");
                ActionForward forwardForm = null;
                if (forwardString != null) {
                    forwardForm = new ActionForward(forwardString);
                    forwardForm.setRedirect(true);
                } else {
                    forwardForm = StrutsUtils.getActionForward("deleteEncounter", patientId, form);
                }
                return forwardForm;
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ObjectNotFoundException e) {
                // already deleted or missing - simply send back to home.
                return mapping.findForward("home");
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        request.setAttribute("exception", e);
        return mapping.findForward("error");
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }
    return mapping.findForward("success");
}

From source file:de.zib.gndms.kit.monitor.GroovyMoniServlet.java

/**
 * Stream incoming HTTP multiparts to a monitor previously opened by the current user.
 *
 * @param servletRequest//from   w ww  .  ja  va  2s.  c o m
 * @param servletResponse
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doPost(@NotNull HttpServletRequest servletRequest, @NotNull HttpServletResponse servletResponse)
        throws ServletException, IOException {
    @NotNull
    HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(servletRequest);

    try {
        verifyUserRole(servletRequest);

        String token = parseToken(requestWrapper);
        if (token.length() == 0)
            throw notAcceptable("Zero-length token");

        @NotNull
        HttpSession session = getSessionOrFail(servletRequest);
        final @NotNull GroovyMonitor monitor = lookupMonitorOrFail(servletRequest.getUserPrincipal(), session,
                token);

        monitor.evalParts(servletRequest, parseArgs(requestWrapper), shouldDecodeBase64(requestWrapper));
        servletResponse.setStatus(HttpServletResponse.SC_OK);
    } catch (ServletRuntimeException e) {
        e.sendToClient(servletResponse);
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.GetDelegationTokenServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final UserGroupInformation ugi;
    final ServletContext context = getServletContext();
    final Configuration conf = (Configuration) context.getAttribute(JspHelper.CURRENT_CONF);
    try {/*from w w w .  ja  va  2 s. c  o  m*/
        ugi = getUGI(req, conf);
    } catch (IOException ioe) {
        LOG.info("Request for token received with no authentication from " + req.getRemoteAddr(), ioe);
        resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unable to identify or authenticate user");
        return;
    }
    LOG.info("Sending token: {" + ugi.getUserName() + "," + req.getRemoteAddr() + "}");
    final NameNode nn = (NameNode) context.getAttribute("name.node");
    String renewer = req.getParameter(RENEWER);
    final String renewerFinal = (renewer == null) ? req.getUserPrincipal().getName() : renewer;

    DataOutputStream dos = null;
    try {
        dos = new DataOutputStream(resp.getOutputStream());
        final DataOutputStream dosFinal = dos; // for doAs block
        ugi.doAs(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws IOException {
                final Credentials ts = DelegationTokenSecretManager.createCredentials(nn, ugi, renewerFinal);
                ts.write(dosFinal);
                dosFinal.close();
                return null;
            }
        });

    } catch (Exception e) {
        LOG.info("Exception while sending token. Re-throwing. ", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        if (dos != null)
            dos.close();
    }
}

From source file:jipdbs.web.processors.ContactProcessor.java

@Override
public String doProcess(ResolverContext context) throws ProcessorException {

    if (context.isPost()) {
        HttpServletRequest req = context.getRequest();
        String mail = req.getParameter("m");
        String text = req.getParameter("text");

        if (StringUtils.isEmpty(mail) || StringUtils.isEmpty(text)) {
            Flash.error(req, MessageResource.getMessage("fields_required"));
            return null;
        }//  w w  w  .  j a  v a2s.  c om

        if (!Validator.isValidEmail(mail)) {
            Flash.error(req, MessageResource.getMessage("invalid_email"));
            return null;
        }

        IDDBService app = (IDDBService) context.getServletContext().getAttribute("jipdbs");

        if (!app.isRecaptchaValid(req.getRemoteAddr(), req.getParameter("recaptcha_challenge_field"),
                req.getParameter("recaptcha_response_field"))) {
            Flash.error(req, MessageResource.getMessage("invalid_captcha"));
            return null;

        }
        Principal user = req.getUserPrincipal();
        app.sendAdminMail(user != null ? user.getName() : null, mail, text);
        Flash.ok(req, MessageResource.getMessage("mail_sent"));
    }
    return null;
}

From source file:in.raster.oviyam.servlet.UserConfiguration.java

/** 
 * Handles the HTTP <code>GET</code> method.
 * @param request servlet request/*from   w w  w.  jav  a  2 s  . c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = null;
    try {
        String settings = request.getParameter("settings");
        String actionToDo = request.getParameter("todo");
        String settingsValue = request.getParameter("settingsValue");

        //Get user details
        /*InitialContext ctx = new InitialContext();
        Subject subject = (Subject) ctx.lookup("java:comp/env/security/subject");
        List<Principal> prinList = new ArrayList<Principal>(subject.getPrincipals());
        Principal p = prinList.get(0);
        String userName = p.getName();
        System.out.println("User name: " + userName);*/

        String userName = request.getUserPrincipal().getName();

        //File tempDir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
        UserHandler uh = new UserHandler();
        String str = null;
        out = response.getWriter();
        User user = uh.findUserByName(userName);

        if (user == null) {
            user = new User();
            user.setUserName(userName);
            Button btn = new Button();
            btn.setLabel("Today CT");
            btn.setDateCrit("t");
            btn.setModality("CT");
            btn.setAutoRefresh("0");
            uh.addNewUser(btn, userName);
        }

        if (user != null) {
            if (actionToDo.equalsIgnoreCase("READ")) {
                if (settings.equals("theme")) {
                    str = user.getTheme();
                } else if (settings.equals("sessTimeout")) {
                    str = user.getSessTimeout();
                } else if (settings.equals("userName")) {
                    str = user.getUserName();
                    String sessTimeout = user.getSessTimeout();
                    if (sessTimeout != null) {
                        HttpSession session = request.getSession(false);
                        session.setMaxInactiveInterval(Integer.parseInt(sessTimeout));
                    }
                } else if (settings.equals("viewerSlider")) {
                    str = user.getViewerSlider();
                } else if (settings.equals("roles")) {
                    //Principal pTmp = prinList.get(1);
                    //str = pTmp.toString();
                    if (request.isUserInRole("WebAdmin") || request.isUserInRole("admin")) {
                        str = "Admin";
                    } else {
                        str = "Other";
                    }
                } else if (settings.equals("buttons")) {
                    QueryParamHandler qph = new QueryParamHandler();
                    List<Button> butList = qph.getAllButtons(userName);
                    JSONArray jsonArray = new JSONArray(butList);
                    str = jsonArray.toString();
                }
                out.print(str);
            } else if (actionToDo.equalsIgnoreCase("UPDATE")) {
                if (settings.equals("theme")) {
                    user.setTheme(settingsValue);
                } else if (settings.equals("sessTimeout")) {
                    user.setSessTimeout(settingsValue);
                } else if (settings.equals("viewerSlider")) {
                    user.setViewerSlider(settingsValue);
                }
                uh.updateUser(user);
                out.println("Success");
            }
        }

    } catch (Exception ex) {
        log.error("Exception occured in User Configuration servlet", ex);
        //out.println("Failure");
    }
}

From source file:com.temenos.interaction.core.web.RequestContextFilter.java

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

    final HttpServletRequest servletRequest = (HttpServletRequest) request;

    String requestURI = servletRequest.getRequestURI();
    requestURI = StringUtils.removeStart(requestURI,
            servletRequest.getContextPath() + servletRequest.getServletPath());
    String baseURL = StringUtils.removeEnd(servletRequest.getRequestURL().toString(), requestURI);

    Map<String, List<String>> headersMap = new HashMap<>();
    Enumeration<String> headerNames = servletRequest.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            List<String> valuesList = Collections.list(servletRequest.getHeaders(headerName));
            headersMap.put(headerName, valuesList);
        }//from  w  w w. j a  v a 2 s.  co m
    }

    RequestContext ctx;
    Principal userPrincipal = servletRequest.getUserPrincipal();
    if (userPrincipal != null) {
        ctx = new RequestContext(baseURL, servletRequest.getRequestURI(),
                servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER), userPrincipal, headersMap);
    } else {
        ctx = new RequestContext(baseURL, servletRequest.getRequestURI(),
                servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER), headersMap);
    }

    RequestContext.setRequestContext(ctx);

    try {
        chain.doFilter(request, response);
    } finally {
        RequestContext.clearRequestContext();
    }
}

From source file:org.sakaiproject.nakamura.auth.trusted.TrustedTokenServiceTest.java

@Test
public void testGetCredentialsValidSession() {
    ComponentContext context = configureForSession();
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpSession session = createMock(HttpSession.class);
    EasyMock.expect(request.getRemoteAddr()).andReturn("127.0.0.1");
    EasyMock.expect(request.getHeader("x-sakai-token")).andReturn(null).anyTimes();
    EasyMock.expect(request.getSession(true)).andReturn(session);

    Principal principal = createMock(Principal.class);
    EasyMock.expect(request.getUserPrincipal()).andReturn(principal);
    EasyMock.expect(principal.getName()).andReturn(null);
    EasyMock.expect(request.getRemoteUser()).andReturn("ieb");
    Capture<SimpleCredentials> attributeValue = new Capture<SimpleCredentials>();
    Capture<String> attributeName = new Capture<String>();
    session.setAttribute(EasyMock.capture(attributeName), EasyMock.capture(attributeValue));

    HttpServletResponse response = createMock(HttpServletResponse.class);

    replay();//from   w  w w .jav a 2 s.  c  o m
    trustedTokenService.activate(context);
    trustedTokenService.injectToken(request, response, TrustedTokenTypes.AUTHENTICATED_TRUST, null);
    Assert.assertTrue(attributeName.hasCaptured());
    Assert.assertTrue(attributeValue.hasCaptured());
    Credentials credentials = attributeValue.getValue();

    verify();
    reset();

    EasyMock.expect(request.getHeader("x-sakai-token")).andReturn(null).anyTimes();
    EasyMock.expect(request.getSession(false)).andReturn(session);
    EasyMock.expect(session.getAttribute(TrustedTokenService.SA_AUTHENTICATION_CREDENTIALS))
            .andReturn(credentials);

    replay();
    Credentials ieb = trustedTokenService.getCredentials(request, response);
    Assert.assertTrue(ieb instanceof SimpleCredentials);
    SimpleCredentials sc = (SimpleCredentials) ieb;
    TrustedUser tu = (TrustedUser) sc.getAttribute(TrustedTokenService.CA_AUTHENTICATION_USER);
    Assert.assertNotNull(tu);
    Assert.assertEquals("ieb", tu.getUser());
    verify();
}