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:de.thorstenberger.examServer.webapp.action.StudentMainAction.java

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

    final TaskManager taskManager = (TaskManager) getBean("TaskManager");

    final List<TaskDef> taskDefs = taskManager.getTaskDefs();

    final List<TaskDefVO> tdvos = new ArrayList<TaskDefVO>();

    for (final TaskDef taskDef : taskDefs) {

        if (!taskDef.isVisible()) {
            continue;
        }/*w ww . j  a v  a 2 s. c om*/

        final TaskDefVO tdvo = new TaskDefVO();
        tdvo.setId("" + taskDef.getId());
        tdvo.setTitle(taskDef.getTitle());
        tdvo.setShortDescription(taskDef.getShortDescription());
        tdvo.setType(taskDef.getType());
        // if( taskDef.getDeadline() != null )
        // tdvo.setDeadline( DateUtil.getStringFromMillis( taskDef.getDeadline() ) );
        tdvo.setStopped(taskDef.isStopped());
        tdvo.setActive(taskDef.isActive());
        tdvos.add(tdvo);
    }

    request.setAttribute("TaskDefs", tdvos);

    // redirect if needed (incomplete student details)
    final ConfigManager config = (ConfigManager) getBean("configManager");
    if (config.isSetFlag("askForSemester")) {
        final UserManager userManager = (UserManager) getBean("userManager");
        final User user = userManager.getUserByUsername(request.getUserPrincipal().getName());

        final boolean noFirstname = isEmpty(user.getFirstName());
        final boolean noLastname = isEmpty(user.getLastName());
        final boolean noSemester = isEmpty(user.getSemester()) || !isNumeric(user.getSemester());
        final boolean noMatrikel = isEmpty(user.getMatrikel()) || !isNumeric(user.getMatrikel());

        if (noFirstname || noLastname || noSemester || noMatrikel) {
            return mapping.findForward("askForSemester");
        }
    }
    return mapping.findForward("success");
}

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

/**
 * Create record from form.//from w ww . j av  a2  s .c om
 *
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return ActionForward
 * @throws Exception
 */
public 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();
    DynaValidatorForm dynaForm = null;
    int formId = 0;
    String formName = mapping.getParameter().trim();
    Long formIdL = (Long) DynaSiteObjects.getFormNameMap().get(formName);
    formId = formIdL.intValue();
    ActionMessages errors = new ActionMessages();

    SessionSubject sessionPatient = null;
    Long patientId = null;
    String eventUuid = null;

    dynaForm = (DynaValidatorForm) form;
    Site site = SessionUtil.getInstance(session).getClientSettings().getSite();
    Long siteId = site.getId();

    // Get a form and flow from the formDef; add them to the encounter
    Form formDef = (Form) DynaSiteObjects.getForms().get(new Long(formId));
    Long formTypeId = formDef.getFormTypeId();
    //FormType formType = formDef.getFormType();
    EncounterData vo = null;
    Connection conn = null;
    try {
        conn = DatabaseUtils.getZEPRSConnection(username);
        if (formDef.isRequireReauth()) {
            try {
                AuthManager.confirmIdentity(conn, request, user.getName(), request.getParameter("password"));
            } catch (UserUnauthorizedException e) {
                errors.add("errors", new ActionMessage("errors.userunauthorized"));
                saveErrors(request, errors);
                try {
                    String forwardName = (String) DynaSiteObjects.getFormNames().get(formName);
                    if (forwardName == null) {
                        return mapping.getInputForward();
                    } else {
                        if (forwardName.equals("demographics")) {
                            return mapping.getInputForward();
                        } else {
                            return mapping.findForward(forwardName + "Error");
                        }
                    }
                } catch (Exception e1) {
                    return mapping.getInputForward();
                }
            }
        }

        if (formName.equals("PatientRegistration")) {
            //ActionMessages errors = new ActionMessages();
            // check if there is a duplicate id
            Object item = dynaForm.get("patient_id_number");
            if (item != null) {
                String zeprsId = (String) item;
                Boolean status = PatientDAO.checkPatientId(conn, zeprsId);
                if (status == Boolean.FALSE) {
                    errors.add("errors", new ActionMessage("errors.duplicateId", zeprsId));
                }
            }
        }

        if (formName.equals("UserInfo")) {
            //ActionMessages errors = new ActionMessages();
            // check if password at least 8 chars
            Object item = dynaForm.get("password");
            if (item != null) {
                String password = (String) item;
                if (password.length() < 8) {
                    errors.add("errors", new ActionMessage("errors.password"));
                }
            }

            // Check for duplicate username
            if (dynaForm.get("username") != null) {
                String searchUsername = (String) dynaForm.get("username");
                Object userObject;
                try {
                    userObject = UserDAO.getUser(conn, searchUsername);
                    errors.add("errors", new ActionMessage("errors.duplicate.username", searchUsername));
                } catch (ObjectNotFoundException e) {
                    // It's ok - there should not be a user.
                }
            }
        }

        //resolve the patientId - it has been either pushed via the request or gathered from the sessionPatient
        if (!formName.equals("PatientRegistration") && formTypeId != 5 && formTypeId != 9) {
            sessionPatient = (SessionSubject) SessionUtil.getInstance(session).getSessionPatient();
            patientId = sessionPatient.getId();
        }

        Long encounterId = null;
        try {
            encounterId = (Long) dynaForm.get("id");
        } catch (IllegalArgumentException e) {
            if (request.getParameter("id") != null) {
                if (!request.getParameter("id").equals("")) {
                    encounterId = Long.valueOf(request.getParameter("id"));
                }
            }
        }

        Map dynaMap = dynaForm.getMap();
        Set encSet = dynaMap.entrySet();
        boolean emptyForm = true;
        //boolean futureDateVisit = false;
        for (Iterator iterator = encSet.iterator(); iterator.hasNext();) {
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = (String) entry.getKey();
            String value = null;
            try {
                value = (String) entry.getValue();
            } catch (ClassCastException e) {
                if (entry.getValue().getClass().equals("Integer.class")) {
                    Integer valueInt = (Integer) entry.getValue();
                    value = valueInt.toString();
                }
            }

            if ((key.equals("date_visit")) || (key.equals("date_of_record"))) {
                Date dateVisit = Date.valueOf(value);
                Date now = DateUtils.getNow();
                if (dateVisit.getTime() > now.getTime()) {
                    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
                            Constants.DATE_FORMAT_EXCEL_SHORT);
                    sdf.setTimeZone(TimeZone.getDefault());
                    Date valueDate = Date.valueOf(value);
                    String formattedDate = sdf.format(valueDate.getTime());
                    errors.add("errors", new ActionMessage("errors.invalid.dateVisit.future", formattedDate));
                    saveErrors(request, errors);
                }
            } else {
                if (!value.equals("")) {
                    emptyForm = false;
                }
            }
        }

        if (emptyForm) {
            if (formId == 132) {
                errors.add("errors", new ActionMessage("errors.dispensing.emptyForm"));
            } else {
                errors.add("errors", new ActionMessage("errors.emptyForm"));
            }
            saveErrors(request, errors);
        }

        if (errors.size() > 0) {
            saveErrors(request, errors);
            try {
                String specialFormName = (String) DynaSiteObjects.getFormNames().get("form" + formId);
                if (specialFormName == null) {
                    return mapping.getInputForward();
                } else {
                    if (specialFormName.equals("demographics")) {
                        return mapping.getInputForward();
                    } else {
                        return mapping.findForward(formName + "Error");
                    }
                }
            } catch (Exception e1) {
                return mapping.getInputForward();
            }
        }

        if (formId == 132) { // Patient Dispensary
            //ActionMessages errors = new ActionMessages();
            // loop through the bridge table records
            int recordsPerEncounter = formDef.getRecordsPerEncounter();
            for (int j = 1; j < recordsPerEncounter; j++) {
                String itemIdFieldName = "PBF" + j + "_item_id";
                String quantityDispensedFieldName = "PBF" + j + "_dispensed";
                // get the item_id
                Long itemId = null;
                Integer quantityDispensed = 0;
                if (!dynaForm.getMap().get(itemIdFieldName).equals("")) {
                    itemId = Long.valueOf((String) dynaForm.getMap().get(itemIdFieldName));
                }
                if (!dynaForm.getMap().get(quantityDispensedFieldName).equals("")) {
                    quantityDispensed = Integer
                            .valueOf((String) dynaForm.getMap().get(quantityDispensedFieldName));
                }
                Integer currentBalance = 0;
                Integer possiblebalance = 0;
                if (itemId != null) {
                    if (DynaSiteObjects.getStatusMap().get("balanceMap") != null) {
                        HashMap<Long, StockReport> balanceMap = (HashMap<Long, StockReport>) DynaSiteObjects
                                .getStatusMap().get("balanceMap");
                        StockReport stockReport = balanceMap.get(itemId);
                        //tempStockControl = InventoryDAO.getCurrentStockBalance(conn, itemId, siteId.intValue());
                        if (stockReport != null) {
                            currentBalance = stockReport.getBalanceBF();
                        }
                        possiblebalance = currentBalance - quantityDispensed;
                        dynaForm.getMap().put("balance", possiblebalance);
                    }
                    processBalanceMessages(conn, errors, itemId, currentBalance, possiblebalance, true);
                }
            }
            if (errors.size() > 0) {
                saveErrors(request, errors);
                try {
                    String specialFormName = (String) DynaSiteObjects.getFormNames().get("form" + formId);
                    if (specialFormName == null) {
                        return mapping.getInputForward();
                    } else {
                        if (specialFormName.equals("demographics")) {
                            return mapping.getInputForward();
                        } else {
                            return mapping.findForward(formName + "Error");
                        }
                    }
                } catch (Exception e1) {
                    return mapping.getInputForward();
                }
            }
        }

        if (formId == 161) { // stock_control
            Integer value = 0;
            Integer balance = 0;
            Integer tempStockControlBalance = 0;
            Long itemId = null;
            // get the item_id
            if (!dynaForm.getMap().get("item_id").equals("")) {
                itemId = Long.valueOf((String) dynaForm.getMap().get("item_id"));
            }

            if (DynaSiteObjects.getStatusMap().get("balanceMap") != null) {
                HashMap<Long, StockReport> balanceMap = (HashMap<Long, StockReport>) DynaSiteObjects
                        .getStatusMap().get("balanceMap");
                StockReport stockReport = balanceMap.get(itemId);
                //tempStockControl = InventoryDAO.getCurrentStockBalance(conn, itemId, siteId.intValue());
                if (stockReport != null) {
                    tempStockControlBalance = stockReport.getBalanceBF();
                }
            }
            // set the last_patient_item_id hidden field
            //dynaForm.getMap().put("last_patient_item_id", tempStockControl.getLast_patient_item_id());
            // change the current stock balance based on the fields in this submission
            if (!dynaForm.getMap().get("type_of_change").equals("")) {
                Integer typeOfStock = Integer.valueOf((String) dynaForm.getMap().get("type_of_change"));
                if (!dynaForm.getMap().get("change_value").equals("")) {
                    value = Integer.valueOf((String) dynaForm.getMap().get("change_value"));
                }
                switch (typeOfStock) {
                // Received
                case 3263:
                    balance = tempStockControlBalance + value;
                    break;
                // Issued
                case 3264:
                    balance = tempStockControlBalance - value;
                    break;
                // Losses
                case 3265:
                    balance = tempStockControlBalance - value;
                    break;
                // Pos. Adjust.
                case 3266:
                    balance = tempStockControlBalance + value;
                    break;
                // Neg. Adjust
                case 3267:
                    balance = tempStockControlBalance - value;
                    break;
                default:
                    balance = value;
                    break;
                }
            } else {
                balance = value;
            }

            processBalanceMessages(conn, errors, itemId, tempStockControlBalance, balance, false);

            if (errors.size() > 0) {
                saveErrors(request, errors);
                try {
                    String specialFormName = (String) DynaSiteObjects.getFormNames().get("form" + formId);
                    if (specialFormName == null) {
                        return mapping.getInputForward();
                    } else {
                        if (specialFormName.equals("demographics")) {
                            return mapping.getInputForward();
                        } else {
                            return mapping.findForward(formName + "Error");
                        }
                    }
                } catch (Exception e1) {
                    return mapping.getInputForward();
                }
            }

            // set the balance hidden field
            dynaForm.getMap().put("balance", balance);

            // reset the lowStockItems
            /*if (Constants.LOW_STOCK_WARNING_QUANTITY != null) {
               List<Task> lowStockItems = null;
               if (DynaSiteObjects.getStatusMap().get("lowStockItems") != null) {
                  lowStockItems = (List<Task>) DynaSiteObjects.getStatusMap().get("lowStockItems");
               }
               if (lowStockItems != null) {
                  int i = 0;
                  int itemToRemove = 0;
                  for (Task lowStockTask : lowStockItems) {
             i++;
             Long lowStockItemId = lowStockTask.getId();
             if (itemId.intValue() == lowStockItemId.intValue()) {
                itemToRemove = i;
                break;
             }
                  }
                  if (itemToRemove > 0) {
             lowStockItems.remove(i-1);
                  }
               }
            }*/
        }

        // We need to calculate tempStockControl's balance field a couple of times.
        StockControl tempStockControl = null;
        Map formData = dynaForm.getMap();
        try {
            if (formId == 128 || formId == 129 || formId == 130 || formId == 131 || formId == 181) {
                vo = DarFormDAO.saveForm(conn, formDef, String.valueOf(formId), patientId, formData,
                        encounterId, siteId, username, sessionPatient);
            } else {
                vo = PopulatePatientRecord.saveForm(conn, formDef, String.valueOf(formId), patientId, formData,
                        encounterId, siteId, username, sessionPatient);
            }
            if (formId == 161) {
                StockControl sc = (StockControl) vo;
                Long itemId = sc.getItem_id();
                StockControlDAO.prepareStockforAlertList(conn, sc, null, itemId);
            }
            if (formId == 132) { // Patient Dispensary
                // we're processing this item here because we don't really need to do it in EncounterProcessor,
                // but we do need the id of the recently-saved record.
                // loop through the bridge table records
                int recordsPerEncounter = formDef.getRecordsPerEncounter();
                for (int j = 1; j < recordsPerEncounter; j++) {
                    String itemIdFieldName = "PBF" + j + "_item_id";
                    String quantityDispensedFieldName = "PBF" + j + "_dispensed";
                    // get the item_id
                    Long itemId = null;
                    Integer quantityDispensed = null;
                    if (!formData.get(itemIdFieldName).equals("")) {
                        itemId = Long.valueOf((String) formData.get(itemIdFieldName));
                    }
                    if (!formData.get(quantityDispensedFieldName).equals("")) {
                        quantityDispensed = Integer.valueOf((String) formData.get(quantityDispensedFieldName));
                    }
                    if (itemId != null) {
                        //if (tempStockControl == null) {
                        tempStockControl = InventoryDAO.getCurrentStockBalance(conn, itemId, null);
                        //}
                        Integer currentBalance = tempStockControl.getBalance();

                        HashMap<Long, StockReport> balanceMap = (HashMap<Long, StockReport>) DynaSiteObjects
                                .getStatusMap().get("balanceMap");
                        StockReport stockReport = balanceMap.get(itemId);
                        if (stockReport != null) {
                            stockReport.setBalanceBF(currentBalance);
                            stockReport.setOnHand(currentBalance);
                            balanceMap.put(itemId, stockReport);
                        }
                        Integer lowStockWarning = Integer.valueOf(Constants.LOW_STOCK_WARNING_QUANTITY);
                        //Integer possiblebalance = currentBalance - quantityDispensed;
                        if (currentBalance <= 0) {
                            // first check if the most recent record for this item is an out-of-stock warning = 3279
                            try {
                                StockControl outOfStock = InventoryDAO.getMostRecentOutOfStock(conn, itemId,
                                        null);
                                // if record exists, we're ok
                            } catch (ObjectNotFoundException e) {
                                try {
                                    Date visitDateD = null;
                                    if (formData != null) {
                                        //String formName = StringManipulation.fixClassname(formDef.getName());
                                        visitDateD = DateUtils.getVisitDate(formData, formName);
                                    } else {
                                        visitDateD = DateUtils.getNow();
                                    }
                                    InventoryDAO.createOutOfStockRecord(conn, formDef, String.valueOf(formId),
                                            patientId, siteId, username, sessionPatient, vo, itemId,
                                            quantityDispensed, visitDateD);
                                } catch (Exception e2) {
                                    log.error(e2);
                                }
                            }
                        }
                    }
                }
                // refreshes the StockAlertList.
                StockControlDAO.setStockAlertList(conn, null);
            }
        } catch (Exception e) {
            log.debug("formData: " + formData);
            log.error(
                    "Error saving record - formId: " + formId + ", patientId: " + patientId + ", encounterId: "
                            + encounterId + ", siteId: " + siteId + ", username: " + username + " Error: " + e);
            if (sessionPatient == null) {
                log.error("Error saving record - null sessionPatient");
            }
            e.printStackTrace();
            if (!conn.isClosed()) {
                conn.close();
                conn = null;
            }
            request.setAttribute("exception", e);
            return mapping.findForward("error");
        }

        String menuItemText = null;
        if (formName.equals("MenuItem")) {
            menuItemText = StringManipulation.escapeString(dynaForm.get("textLink").toString());
            menuItemText = StringManipulation.fixFirstDigit(menuItemText);
            dynaForm.set("templateKey", Constants.MENUITEM_PROPERTY_PREFIX + "." + menuItemText);
        }

        //Forms that don't require patient(including admin forms) don't need the session refreshed since they aren't patient oriented
        // Submitting the PatientRegistration form does need the TimsSessionSubject initialised.
        if (formDef.isRequirePatient() == true || formName.equals("PatientRegistration")
                || formName.equals("PerpetratorDemographics")) {
            try {
                SessionPatientDAO.updateSessionPatient(conn, vo.getPatientId(), vo.getEventUuid(), session);
                // re-initialize a few vars
                sessionPatient = (SessionSubject) SessionUtil.getInstance(session).getSessionPatient();
                eventUuid = sessionPatient.getCurrentEventUuid();
                patientId = sessionPatient.getId();
            } catch (ObjectNotFoundException e) {
                // clear out session patient - it's null
                SessionUtil.getInstance(session).setSessionPatient(null);
            }
        }
        // Reset form
        form.reset(mapping, request);
        StrutsUtils.removeFormBean(mapping, request);
    } catch (ServletException e) {
        log.error(e);
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }

    /**
     * Forwards section - send user to the next form
     */

    return createForward(request, mapping, patientId, eventUuid, dynaForm, session, formId, vo);
}

From source file:dk.dma.msinm.user.security.SecurityServletFilter.java

/**
 * If the request contains a JWT header, the user will be logged in for this request using the token.
 * <p>/*w  ww  .  j a  v  a2  s  . c  om*/
 * If the authentication fails, this methods does nothing. It is left to the handler of the request,
 * say a Rest endpoint, to throw an error if security requirements are not met.
 *
 * @param request the servlet request
 * @return the request
 */
public HttpServletRequest attemptJwtAuthLogin(HttpServletRequest request, HttpServletResponse response) {
    try {
        // Get the JWT token from the header
        String jwt = getAuthHeaderToken(request, JWT_TOKEN);

        if (jwt != null) {
            // Parse and verify the JWT token
            JWTService.ParsedJWTInfo jwtInfo = jwtService.parseSignedJWT(jwt);

            // Check if the bearer token has expired
            Date now = new Date();
            if (now.after(jwtInfo.getExpirationTime())) {
                request.setAttribute(AUTH_ERROR_ATTR, 419); // 419: session timed out
                log.warn("JWT token expired for user " + jwtInfo.getSubject());
                return request;
            }

            // Before logging in, generate a one-time password token tied to the current thread.
            // This is verified in the JbossLoginModule
            String tempPwd = jwtService.issueTempJwtPwdToken(JbossLoginModule.BEARER_TOKEN_LOGIN);
            request = SecurityUtils.login(userService, request, jwtInfo.getSubject(), tempPwd);
            log.trace("Found JWT user " + request.getUserPrincipal().getName());

            // After a configurable amount of minutes, a new JWT token will automatically be
            // issued and sent back to the client.
            // This will allow the client to implement inactivity timeout instead of relying on
            // the fixed expiration date of the JWT token.
            if (jwtService.reauthJWT(jwtInfo)) {
                log.info("New JWT token issued for re-authorization of user " + jwtInfo.getSubject());
                JWTToken reAuthJwt = jwtService.createSignedJWT(getJwtIssuer(request),
                        (User) request.getUserPrincipal());
                response.setHeader("Reauthorization", reAuthJwt.getToken());
            }
        }
    } catch (Exception ex) {
        request.setAttribute(AUTH_ERROR_ATTR, HttpServletResponse.SC_UNAUTHORIZED);
        log.warn("Failed logging in using bearer token");
    }
    return request;
}

From source file:org.infoglue.deliver.applications.filters.PortalServletRequest.java

/**
 * @param req//from   w w w  . j a va  2  s  . c  o m
 */

public PortalServletRequest(HttpServletRequest req) {
    super(req);
    paramMap = PathParser.copyParameters(req.getParameterMap());

    // Extend parameter map with infoglue parameters.
    // TODO paramMap should be immutable
    paramMap.putAll(PathParser.parsePathParameters(PortalControlURL.IG, req.getServletPath(), false));

    if (paramMap.containsKey("proxyUrl") && req.getParameter("command") != null
            && !req.getParameter("command").equals("")) {
        //logger.info("\n\nCommand:" + req.getParameter("command") + " on " + req.getRequestURI());
        paramMap.put("igproxy_command", new String[] { req.getParameter("command") });
        paramMap.remove("command");
    }

    if (log.isDebugEnabled()) {
        StringBuffer str = new StringBuffer();
        for (Iterator it = paramMap.keySet().iterator(); it.hasNext();) {
            String name = (String) it.next();
            str.append(name);
            str.append(": ");
            str.append(Arrays.asList((String[]) paramMap.get(name)));
            if (it.hasNext())
                str.append(", ");
        }
        log.debug("Available params: " + str);
    }

    this.principal = (InfoGluePrincipal) req.getSession().getAttribute("infogluePrincipal");
    if (req.getUserPrincipal() != null)
        this.principal = req.getUserPrincipal();
}

From source file:com.salesmanBuddy.Controllers.SalesmanBuddy.java

@Path("stockNumbers")
@GET//www  . j a v  a2 s  . com
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getAllStockNumbers(@Context HttpServletRequest request,
        @DefaultValue("0") @QueryParam("dealershipId") Integer dealershipId,
        @DefaultValue("false") @QueryParam("all") boolean all) {
    String googleUserId = request.getUserPrincipal().getName();
    Users user = this.dao.getUserByGoogleId(googleUserId);
    if (all) {
        if (user.getType() > 2) {
            GenericEntity<List<StockNumbers>> entity = new GenericEntity<List<StockNumbers>>(
                    this.dao.getAllStockNumbers()) {
            };
            return Response.ok(entity).build();
        }
        return Response.status(400)
                .entity(new ErrorMessage("You must be an SB employee to see all stock numbers")).build();
    } else if (dealershipId != 0) {
        if (user.getType() > 2 || user.getDealershipId() == dealershipId) {
            GenericEntity<List<StockNumbers>> entity = new GenericEntity<List<StockNumbers>>(
                    this.dao.getStockNumbersForDealershipId(dealershipId)) {
            };
            return Response.ok(entity).build();
        }
        return Response.status(400)
                .entity(new ErrorMessage("You must be an SB employee or be a member of this dealership"))
                .build();
    } else {
        GenericEntity<List<StockNumbers>> entity = new GenericEntity<List<StockNumbers>>(
                this.dao.getStockNumbersForDealershipId(user.getDealershipId())) {
        };
        return Response.ok(entity).build();
    }
}

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

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

    /*if (SystemStateManager.getCurrentState() != SystemStateManager.STATUS_NORMAL) {
    return mapping.findForward(LOCKED_FORWARD);
    }*//*w  w w.j a v  a2  s .  com*/

    HttpSession session = request.getSession();
    Principal user = request.getUserPrincipal();
    Locale locale = getLocale(request);
    Locale sessionLocale = (Locale) request.getAttribute("sessionLocale");
    String sessionLocaleString = null;
    if ((sessionLocale.getLanguage() != null)
            && ((sessionLocale.getCountry() != null) && (!sessionLocale.getCountry().equals("")))) {
        sessionLocaleString = sessionLocale.getLanguage() + "_" + sessionLocale.getCountry();
    } else if (sessionLocale.getLanguage() != null) {
        sessionLocaleString = sessionLocale.getLanguage();
    }
    String username = user.getName();
    Connection conn = null;
    Form encounterForm;
    BaseEncounter encounter = null;
    Map encMap = null;
    try {
        conn = DatabaseUtils.getZEPRSConnection(username);

        String formName = null;
        String encounterIdString = "";

        if (mapping.getParameter() != null && !mapping.getParameter().equals("")) {
            formName = mapping.getParameter();
            if (request.getAttribute("encounterId") != null) {
                encounterIdString = request.getAttribute("encounterId").toString();
            }
        } else {
            formName = request.getAttribute("id").toString();
        }

        // Sometimes encounterId is sent in url
        if (request.getParameter("encounterId") != null) {
            encounterIdString = request.getParameter("encounterId").toString();
        }

        DarSessionSubject sessionPatient = null;
        Long patientId = null;
        //Long eventId = null;
        String eventUuid = null;

        if (request.getParameter("next") != null) {
            String next = request.getParameter("next");
            request.setAttribute("next", next);
        }

        String fixName = StringManipulation.fixClassname(formName);
        Long formId = (Long) DynaSiteObjects.getFormNameMap().get(fixName);
        encounterForm = ((Form) DynaSiteObjects.getForms().get(new Long(formId)));

        String siteId = "";
        try {
            siteId = SessionUtil.getInstance(session).getClientSettings().getSiteId().toString();
        } catch (SessionUtil.AttributeNotFoundException e) {
            // it's ok - we're in admin mode.
        }

        if (!formName.equals("PatientRegistration") && !formName.equals("PerpetratorDemographics")
                && encounterForm.getFormTypeId() != 5) {
            try {
                sessionPatient = (DarSessionSubject) SessionUtil.getInstance(session).getSessionPatient();
                patientId = sessionPatient.getId();
                //eventId = sessionPatient.getCurrentEventId();
                eventUuid = sessionPatient.getCurrentEventUuid();
            } catch (SessionUtil.AttributeNotFoundException e) {
                log.error("Unable to get SessionSubject for " + formName);
            }
        } else {
            if (request.getParameter("patientId") != null) {
                patientId = Long.valueOf(request.getParameter("patientId"));
                try {
                    sessionPatient = (DarSessionSubject) SessionUtil.getInstance(session).getSessionPatient();
                } catch (SessionUtil.AttributeNotFoundException e) {
                    log.error("Unable to get TimsSessionSubject");
                }
                //eventId = sessionPatient.getCurrentEventId();
                eventUuid = sessionPatient.getCurrentEventUuid();
            }
        }

        HashMap visiblePageItems = new HashMap();
        if (request.getParameter("id") != null) {
            encounterIdString = request.getParameter("id");
        }
        boolean drugList = false;

        String newform = "";
        if (request.getAttribute("newform") != null) {
            newform = (String) request.getAttribute("newform");
        }

        // Editing a form?
        if (!encounterIdString.equals("")) {
            Long encounterId = new Long(encounterIdString);
            String className = Constants.getDynasiteFormsPackage() + "."
                    + StringManipulation.fixClassname(encounterForm.getName());
            Class clazz = null;
            try {
                clazz = Class.forName(className);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            if (encounterForm.getFormTypeId() == 6) { // patient bridge table form
                encounter = PatientBridgeTableDAO.getEncounter(conn, encounterForm, formId, encounterId, clazz);
                Long encSiteId = encounter.getSiteId();
                if (encSiteId != null) {
                    Site site = (Site) DynaSiteObjects.getClinicMap().get(encSiteId);
                    if (site != null) {
                        encounter.setSiteName(site.getName());
                    }
                }
            } else {
                try {
                    encounter = populateEncounterI18n(request, sessionLocale, sessionLocaleString, conn,
                            encounterForm, formId, encounterId, clazz);
                    encMap = PatientRecordUtils.getEncounterMap(encounterForm, encounter, "fieldId");
                    encounter.setEncounterMap(encMap);
                } catch (ObjectNotFoundException e) {
                    String errorMessage = "<p>An error has occurred. The system was unable to retrieve the requested record. "
                            + "Please press the \"Back\" button and try another link.</p>"
                            + "<p>This error has been logged by the system.</p>";
                    String logMessage = errorMessage + "\n * Code is from FormDisplayAction."
                            + "\n * Debug: encounterId: " + encounterId + ", class: " + clazz + "Error: " + e;
                    log.error(logMessage);
                    log.error(e);
                    request.setAttribute("exception", errorMessage);
                    return mapping.findForward("error");
                }

                DynaValidatorForm dynaForm = (DynaValidatorForm) form;
                // used to store values used in multiselect tag
                HashMap multiValues = new HashMap();

                // Section Map is used to reveal hidden fields that have values
                // Should reveal all values in case user needs to enter data for one of the hidden fields
                Map formSection = (Map) DynaSiteObjects.getFormSections().get(encounterForm.getId());
                Map formDependencies = (Map) DynaSiteObjects.getFormDependencies().get(encounterForm.getId());
                Map collapsingSections = (Map) DynaSiteObjects.getCollapsingSections()
                        .get(encounterForm.getId());
                Map collapsingDependencies = (Map) DynaSiteObjects.getCollapsingDependencies()
                        .get(encounterForm.getId());
                // Loop through the pageItems and use the encounterMap to identify the pageItems that have values
                // If it has a value, use the sectionMap to make that section visible.
                Long section = null;
                Long collapsingTableId = null;
                // Set newPageItems = new TreeSet(new DisplayOrderComparator());
                for (Iterator iterator = encounterForm.getPageItems().iterator(); iterator.hasNext();) {
                    PageItem pageItem = (PageItem) iterator.next();
                    // createPageItem(pageItem);
                    String value = null;
                    Long collapsingSectionId = null;
                    if (pageItem.getForm_field().isEnabled() == true) {
                        // Find which section the field is in
                        try {
                            section = (Long) formDependencies.get(pageItem.getForm_field().getId());
                        } catch (Exception e) {
                            // it's ok
                        }
                        // Is it in a collapsingSection?
                        try {
                            collapsingSectionId = (Long) collapsingDependencies
                                    .get(pageItem.getForm_field().getId());
                            if (collapsingSectionId != null) {
                                ArrayList collapsingSection = (ArrayList) collapsingSections
                                        .get(collapsingSectionId);
                                //the table that is dependent upon the collapsing table if the second item in the list.
                                collapsingTableId = (Long) collapsingSection.get(1);
                            }
                            // collapsingTableId = (Long) formDependencies.get(collapsingSection);
                        } catch (Exception e) {
                            // it's ok
                        }

                        String fieldName = null;
                        FormField formField = pageItem.getForm_field();
                        /*Long currentId = formField.getId();
                        if (formField.getImportId() != null) {
                           currentId = formField.getImportId();
                        }
                        if (formField.getImportId() != null) {
                        fieldName = "field" + currentId;
                        } else {*/
                        //fieldName = StringManipulation.firstCharToLowerCase(formField.getStarSchemaName());
                        fieldName = formField.getIdentifier();
                        //}
                        value = (String) encMap.get(fieldName);
                        // value = BeanUtils.getProperty(encounter, "field" + pageItem.getForm_field().getId());
                        // Do not need to set property  if it's null
                        if (value != null) {
                            if (!pageItem.getForm_field().getType().equals("Display")) {
                                dynaForm.set(fieldName, value);
                            }
                            // Use the sectionMap to make that section visible if necessary.
                            if ((!pageItem.isVisible()) & (section != null)) {
                                // pageItem.setVisible(true);
                                visiblePageItems.put("pageItem" + pageItem.getId(), "visible");
                            }
                            // Use the sectionMap to make that collapsingSection visible if necessary.
                            if (collapsingTableId != null) {
                                visiblePageItems.put("pageItem" + collapsingTableId, "visible");
                            }

                            // also set its sister fields in the section to true
                            // loop through the formSection, matching the masterId
                            List deps = (List) formSection.get(section);
                            if (deps != null) {
                                for (int i = 0; i < deps.size(); i++) {
                                    Long depId = (Long) deps.get(i);
                                    PageItem depPageItem = (PageItem) DynaSiteObjects.getPageItems().get(depId);
                                    // depPageItem.setVisible(true);
                                    visiblePageItems.put("pageItem" + pageItem.getId(), "visible");
                                }
                            }

                        }

                        // Make all hidden fields visible
                        if (!pageItem.isVisible()) {
                            // pageItem.setVisible(true);
                            visiblePageItems.put("pageItem" + pageItem.getId(), "visible");
                        }

                        if (pageItem.getInputType().equals("druglist")) {
                            drugList = true;
                        }

                        if (pageItem.getInputType().equals("multiselect_enum")) {
                            List masterList = new ArrayList();
                            //multiValues.put(currentId, masterList);
                            multiValues.put(fieldName, masterList);
                        }

                        // populate the multiHelper array
                        // each field in which the multiselect widget stores data has the multiselect widget field id in the
                        // visibleDependencies1 property

                        if (pageItem.getInputType().equals("multiselect_item")) {
                            List itemList = null;
                            String visDeps1 = pageItem.getVisibleDependencies1();
                            if (visDeps1 != null) {
                                try {
                                    itemList = (List) multiValues.get(new Long(visDeps1));
                                } catch (NullPointerException e) {
                                    e.printStackTrace(); // multiselect_enum not exist, or out of order.
                                }
                            } else {
                                String error = "multiselect widget setup error - select the widget id for this field's visible deps1.";
                                log.error(error);
                                request.setAttribute("exception", error);
                                return mapping.findForward("error");
                            }

                            value = BeanUtils.getProperty(encounter, fieldName);
                            if (value != null) {
                                //multifields.append(value+ ",");
                                itemList.add(value);
                                //multiValues.put(pageItem.getVisibleDependencies1(), itemList);
                            }
                        }
                    }
                }
                request.setAttribute("multiValues", multiValues);
            }

            request.setAttribute(SUBJECT_KEY, encounter);

            Date dateVisit = encounter.getDateVisit();
            request.setAttribute("dateVisit", dateVisit);
            // used for remote widgets
            request.setAttribute("className", className);
            // loading of body onload DWRUtil.useLoadingMessage()
            request.setAttribute("dwr", 1);
        } else {
            if (sessionPatient != null && sessionPatient.getDead() != null
                    && sessionPatient.getDead().equals(Boolean.TRUE)) {
                String forwardString = null;
                if (sessionPatient != null) {
                    //Long flowId = sessionPatient.getCurrentFlowId();
                    Long flowId = encounterForm.getFlowId();
                    if (flowId.intValue() == 2) {
                        forwardString = "/PatientItem/list.do";
                    } else {
                        forwardString = "/patientTask.do?flowId=" + flowId.toString();
                    }
                } else {
                    forwardString = "/home.do";
                }
                ActionForward forwardForm = null;
                forwardForm = new ActionForward(forwardString);
                forwardForm.setRedirect(true);
                return forwardForm;
            }
        }

        if (visiblePageItems.size() > 0) {
            request.setAttribute("visiblePageItems", visiblePageItems);
        }

        request.setAttribute("encounterForm", encounterForm);

        List drugs = DynaSiteObjects.getDrugs();
        request.setAttribute("drugs", drugs);

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

        String patientSiteId = SessionUtil.getInstance(session).getClientSettings().getSiteId().toString();
        Site site = (Site) DynaSiteObjects.getClinicMap().get(new Long(patientSiteId));
        Integer siteTypeId = site.getSiteTypeId();
        String siteAlphaId = site.getSiteAlphaId().substring(0, 2);
        String clinicId = site.getSiteAlphaId().substring(2, 3);
        request.setAttribute("siteAlphaId", siteAlphaId);
        request.setAttribute("clinicId", clinicId);
        request.setAttribute("siteTypeId", siteTypeId);
        request.setAttribute("patientSiteId", patientSiteId);

        if ((encounterIdString.equals(""))) {
            // See if this form has 1 MaxSubmissions
            int maxSubmissions = encounterForm.getMaxSubmissions();
            Boolean startNewEvent = encounterForm.getStartNewEvent();
            if (maxSubmissions == 1) {
                if (startNewEvent != null && startNewEvent == true) {
                    // start a new Event
                } else {
                    EncounterData encounterOneOnly = null;
                    try {
                        encounterOneOnly = (EncounterData) EncountersDAO.getId(conn, patientId, eventUuid,
                                new Long(formId));
                        Long encounterId = encounterOneOnly.getId();
                        ActionForward forwardForm = null;
                        forwardForm = new ActionForward(
                                "/viewEncounter.do?patientId=" + patientId + "&id=" + encounterId);
                        forwardForm.setRedirect(true);
                        return forwardForm;
                        // send to the record view of this form.
                    } catch (ObjectNotFoundException e1) {
                        // it's ok - form not submitted yet.
                    }
                }
            }

            // patient registration needs sex to be pre-filled to female
            if (encounterForm.getId().intValue() == 1) {
                DynaValidatorForm dynaForm = (DynaValidatorForm) form;
                dynaForm.set("sex", "1");
            }
        }

        List yearList = DateUtils.getYearList();
        request.setAttribute("yearList", yearList);

        // Process the dynamic dropdown lists.
        HashMap listMap = new HashMap();
        Form inlineForm = null;
        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")) {
                List list = WidgetUtils.getList(conn, pageItem.getDropdownTable(), pageItem.getDropdownColumn(),
                        pageItem.getDropdownConstraint(), pageItem.getDropdownOrderByClause(),
                        DropdownItem.class, pageItem.getFkIdentifier());
                // Process PatientItem later.
                if (!formName.equals("PatientItem")) {
                    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);
                }
            }
        }
        // For DAR/ART care form 132
        if (formName.equals("PatientItem")) {
            // Fetch the patient's regimen.
            Long regimenId = sessionPatient.getRegimenId();
            String regimenName = sessionPatient.getRegimenName();
            List<PatientItem> items = RegimenUtils.getAllItemsForRegimen(conn, regimenId);
            // now construct a list of items for the dropdown.
            // We'll replace the one that was just created.
            HashMap<Long, StockReport> balanceMap = null;
            if (DynaSiteObjects.getStatusMap().get("balanceMap") != null) {
                balanceMap = (HashMap<Long, StockReport>) DynaSiteObjects.getStatusMap().get("balanceMap");
            }
            List list = new ArrayList();
            for (PatientItem regimenItem_bridge : items) {
                Long itemId = regimenItem_bridge.getItem_id();
                DropdownItem item = null;
                try {
                    item = RegimenUtils.getItemForRegimen(conn, itemId);
                    //StockControl tempStockControl = InventoryDAO.getCurrentStockBalance(conn, itemId, Integer.valueOf(siteId));
                    if (balanceMap != null) {
                        StockReport stockReport = balanceMap.get(itemId);
                        Integer balance = 0;
                        if (stockReport != null) {
                            balance = stockReport.getBalanceBF();
                        }
                        if (balance <= 0) {
                            /*String value = item.getDropdownValue();
                            item.setDropdownValue(value + " ** Out of Stock ** Bal: " + balance);*/
                        } else {
                            String value = item.getDropdownValue();
                            item.setDropdownValue(value + " Bal: " + balance);
                            list.add(item);
                        }
                    }
                } catch (Exception e) {
                    log.debug("Unable to fetch item for regimen: " + regimenName + " regimenId: " + regimenId
                            + " itemId: " + itemId);
                }
            }
            if (sessionPatient.getChild() != null && sessionPatient.getChild() == true) {
                List<DropdownItem> paedsItems = RegimenUtils.getPaediatricSingleDrugItems(conn);
                for (DropdownItem dropdownItem : paedsItems) {
                    StockReport stockReport = balanceMap.get(Long.valueOf(dropdownItem.getDropdownId()));
                    Integer balance = 0;
                    if (stockReport != null) {
                        balance = stockReport.getBalanceBF();
                    }
                    if (balance <= 0) {
                    } else {
                        String value = dropdownItem.getDropdownValue();
                        dropdownItem.setDropdownValue(value + " Bal: " + balance);
                        list.add(dropdownItem);
                    }
                }
            }
            List<DropdownItem> otherItems = RegimenUtils.getOtherDropdownItems(conn);
            for (DropdownItem dropdownItem : otherItems) {
                StockReport stockReport = balanceMap.get(Long.valueOf(dropdownItem.getDropdownId()));
                Integer balance = 0;
                if (stockReport != null) {
                    balance = stockReport.getBalanceBF();
                }
                if (balance <= 0) {
                } else {
                    String value = dropdownItem.getDropdownValue();
                    dropdownItem.setDropdownValue(value + " Bal: " + balance);
                    list.add(dropdownItem);
                }
            }
            //list.addAll(otherItems);
            if (list.size() > 0) {
                listMap.put(Long.valueOf(4376), list);
            }
        }
        request.setAttribute("listMap", listMap);

        if (encounterForm.getRecordsPerEncounter() != null && encounterForm.getRecordsPerEncounter() > 0) {
            if (encounterForm.getResizedForPatientBridge() == null) {
                FormUtils.createBridgeTablePageItems(encounterForm);
            }
        }

        if (sessionPatient != null && sessionPatient.getPatientType() == 2) {
            List<Patient> clientList = RelationshipDAO.getRelationshipToUuid2(conn, sessionPatient);
            request.setAttribute("relationshipList", clientList);
        }

        // Keep this block at the end - it sets sessionPatient to null in certain circumstances.
        // Set the tasklist for particular circumstances. First check if the form requires a patient or if "id" is in the reqiest.
        if ((encounterForm.isRequirePatient() || ((request.getParameter("id") != null)))) {
            // we don't need the tasklist if we're just editing a form or it's in unassigned flow
            Long unassigned = new Long("100");
            if (request.getParameter("id") == null) {
                if (!encounterForm.getFlow().getId().equals(unassigned)) {
                    // moved code for form 66 below.
                }
            }
            Boolean status = Boolean.valueOf(true);
            /*if (eventUuid == null) {
            return mapping.findForward("home");
            }*/
            List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status,
                    sessionPatient);
            request.setAttribute("activeProblems", activeProblems);
            // now get inactive problems
            status = Boolean.valueOf(false);
            List inactiveProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid,
                    status, sessionPatient);
            request.setAttribute("inactiveProblems", inactiveProblems);
            // Display task list if editing form 1.
        } else if ((encounterForm.getId().intValue() == 1) & (patientId != null)) {
            Boolean status = Boolean.valueOf(true);
            List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status,
                    sessionPatient);
            request.setAttribute("activeProblems", activeProblems);
            // now get inactive problems
            status = Boolean.valueOf(false);
            List inactiveProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid,
                    status, sessionPatient);
            request.setAttribute("inactiveProblems", inactiveProblems);
        } else if ((formName.equals("PerpetratorDemographics")) & (patientId != null)) {
            Boolean status = Boolean.valueOf(true);
            List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status,
                    sessionPatient);
            request.setAttribute("activeProblems", activeProblems);
            // now get inactive problems
            status = Boolean.valueOf(false);
            List inactiveProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid,
                    status, sessionPatient);
            request.setAttribute("inactiveProblems", inactiveProblems);
            // otherwise reset sessionPatient
        } else {
            SessionUtil.getInstance(session).setSessionPatient(null);
        }

    } catch (ServletException e) {
        log.error(e);
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }

    encounterForm = null;

    return mapping.findForward("success");

}

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

@Override
public ActionForward delete(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

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

    if (!isTokenValid(request)) {
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, TOKEN_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }//from   w ww .  j  a v  a  2s .c om

    User user = getUser(dynaForm, request, false);
    if (user == null) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, NOTFOUND_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }

    User sessionUser = (User) request.getUserPrincipal();
    if (sessionUser.getId().equals(user.getId())) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, DELETE_ADMIN_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }

    /* 
     * Als je een gebruiker probeert te verwijderen waarvan de main organization
     * null is geeft hij een fout. Wellicht als in het verleden handmatig een
     * aanpassing is gedaan in de database. Tijdelijk even op de beheerder org zetten
     * waarna de gebruiker gewist kan worden.
     *
     * TODO: Nagaan op welke plekken die main org null zou kunnen worden.
    */
    if (user.getMainOrganization() == null) {
        user.setMainOrganization(sessionUser.getMainOrganization());
        em.merge(user);
        em.flush();
    }

    em.remove(user);
    em.flush();

    dynaForm.initialize(mapping);
    prepareMethod(dynaForm, request, LIST, EDIT);
    addDefaultMessage(mapping, request, ACKNOWLEDGE_MESSAGES);
    return getDefaultForward(mapping, request);
}

From source file:src.servlets.ManagePropertys.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w w  w . j  av  a2  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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //        //set date format
    //        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
    //      //get current date time with Date()
    //      //Date date2 = new Date();
    //      //System.out.println(dateFormat.format(date2));
    //           
    //           
    //           
    //           //get current date time with Calendar()
    //      Calendar cal = Calendar.getInstance();
    //      System.out.println(dateFormat.format(cal.getTime()));

    // setup values
    Agents LoggedIn = null;
    try {
        LoggedIn = AgentsDB.getByUsername(request.getUserPrincipal().getName());
        //request.setAttribute("agent", agent);

    } //end try
    catch (Exception ex) {
        //address = "/Error.jsp";
    }
    int agentIdfromDB = 0;
    agentIdfromDB = LoggedIn.getAgentId();

    Integer id = 0;
    String street = "";
    String city = "";

    Integer listingNum = 0;
    Integer styleId = 0;
    Integer typeId = 0;
    Integer bedrooms = 0;
    Float bathrooms = null;
    Integer squarefeet = 0;
    String description = "";
    String lotsize = "";
    Short garageSize = (short) 0;
    Integer garageId = 0;
    Integer agentId = agentIdfromDB;// Need to get ID from Session when created!
    Date dateAdded = null;
    String photo;//= request.getParameter("photo");
    Double price = 0.0;

    List<FileItem> formItems2 = null;
    //////////////////
    //        if (!ServletFileUpload.isMultipartContent(request) && id!=0) {
    //            // if not, we stop here
    //            PrintWriter writer = response.getWriter();
    //            writer.println("Error: Form must has enctype=multipart/form-data.");
    //            writer.flush();
    //            return;
    //        }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // sets temporary location to store files
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);

    // sets maximum size of upload file
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // sets maximum size of request (include file + form data)
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    // this path is relative to application's directory
    String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }
    // Check file Extention
    @SuppressWarnings("unchecked")
    List<FileItem> formItems = null;
    String fileNameExt = "";

    try {
        formItems = upload.parseRequest(request);
        formItems2 = formItems;

    } catch (FileUploadException ex) {
        Logger.getLogger(ManagePropertys.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (formItems != null && formItems.size() > 0) {
        // iterates over form's fields
        for (FileItem item : formItems) {
            // processes only fields that are not form fields
            if (!item.isFormField()) {

                fileNameExt = new File(item.getName()).getName();
            }
            if (item.getFieldName().equals("street")) {
                street = item.getString();
            }
            if (item.getFieldName().equals("city")) {
                city = item.getString();
            }
            if (item.getFieldName().equals("listingNum")) {
                listingNum = Integer.parseInt(item.getString());
            }
            if (item.getFieldName().equals("styleId")) {
                styleId = Integer.parseInt(item.getString());
            }
            if (item.getFieldName().equals("typeId")) {
                typeId = Integer.parseInt(item.getString());
            }
            if (item.getFieldName().equals("bedrooms")) {
                bedrooms = Integer.parseInt(item.getString());
            }
            if (item.getFieldName().equals("bathrooms")) {
                bathrooms = Float.parseFloat(item.getString());
            }
            if (item.getFieldName().equals("squarefeet")) {
                squarefeet = Integer.parseInt(item.getString());
            }
            if (item.getFieldName().equals("description")) {
                description = item.getString();
            }
            if (item.getFieldName().equals("lotsize")) {
                lotsize = item.getString();
            }
            if (item.getFieldName().equals("garageId")) {
                garageId = Integer.parseInt(item.getString());
            }
            if (item.getFieldName().equals("garageSize")) {
                garageSize = Short.parseShort(item.getString());
            }
            if (item.getFieldName().equals("price")) {
                price = Double.parseDouble(item.getString());
            }
            if (item.getFieldName().equals("id")) {
                id = Integer.parseInt(item.getString());
            }
            //                    if(item.getFieldName().equals("dateAdded"))
            //                            {
            //                            dateAdded = Date.valueOf(item.getString());
            //                            }
            if (item.getFieldName().equals("photo")) {
                photo = item.getString();
            }
            if (request.isUserInRole("admin")) {
                if (item.getFieldName().equals("agentId")) {
                    agentId = Integer.parseInt(item.getString());
                }
            }

        }
    }
    if (!ServletFileUpload.isMultipartContent(request) && id == 0) {
        // if not, we stop here
        PrintWriter writer = response.getWriter();
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();
        return;
    }
    ///////
    String fileNameToLowerCase = fileNameExt.toLowerCase();
    String fileExtension;
    if (fileNameToLowerCase.contains(".")) {
        fileExtension = fileNameToLowerCase.substring(fileNameToLowerCase.indexOf(".") + 1,
                fileNameToLowerCase.length());
    } else {
        fileExtension = "";
    }

    if (!fileExtension.equals("png") && !fileExtension.equals("jpg") && !fileExtension.equals("jpeg")
            && !fileExtension.equals("gif") && !fileExtension.equals("bmp") && id == 0) {
        PrintWriter writer = response.getWriter();
        writer.println("Error: File must be one of the following formats only. (png,jpg,gif,bmp,jpeg)");
        writer.flush();
        return;
    }
    ////////////////

    String address = "";
    //Setup new property
    Properties newProperty = new Properties();
    newProperty.setStreet(street);
    newProperty.setCity(city);
    newProperty.setListingNum(listingNum);
    newProperty.setStyleId(styleId);
    newProperty.setTypeId(typeId);
    newProperty.setBedrooms(bedrooms);
    newProperty.setBathrooms(bathrooms);
    newProperty.setSquarefeet(squarefeet);
    newProperty.setDescription(description);
    newProperty.setLotsize(lotsize);
    newProperty.setGaragesize(garageSize);
    newProperty.setGarageId(garageId);
    newProperty.setAgentId(agentId);
    newProperty.setPrice(price);
    newProperty.setDateAdded(new java.sql.Date(System.currentTimeMillis()));

    if (id != 0) {
        if (fileExtension != "") {
            newProperty.setPhoto(id + "." + fileExtension);
        }
        newProperty.setListingNum(id);
        newProperty.setId(id);
        PropertiesDB.updateProperty(newProperty);
    } else {
        id = PropertiesDB.insertProperty(newProperty);

        newProperty.setPhoto(id + "." + fileExtension);
        newProperty.setListingNum(id);
        PropertiesDB.updateProperty(newProperty);
    }

    try {
        // parses the request's content to extract file data

        //@SuppressWarnings("unchecked")
        //List<FileItem> formItems = upload.parseRequest(request);

        if (formItems2 != null && formItems2.size() > 0) {
            // iterates over form's fields
            for (FileItem item : formItems2) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {

                    if (fileExtension != "") {
                        String fileName = id + "." + fileExtension;
                        String filePath = uploadPath + File.separator + "large" + File.separator + fileName;
                        String filePathThumbnail = uploadPath + File.separator + "thumbnails" + File.separator
                                + fileName;

                        File storeFileThumbnail = new File(filePathThumbnail);
                        File storeFile = new File(filePath);
                        item.write(storeFile);

                        //Thumnail library used for resizing of both images
                        Thumbnails.of(storeFile).size(409, 307).toFile(storeFile);//Resize Main Image with current ratio maintained. (Required before using force size on larger images)
                        Thumbnails.of(storeFile).forceSize(409, 307).toFile(storeFile);//Resize Main Image forcing size of 409x307
                        Thumbnails.of(storeFile).forceSize(75, 56).toFile(storeFileThumbnail);// create thumbnail of 75x56

                        request.setAttribute("Status", "This Property Has Been saved successfully!");
                        address = "ManagePropertys?GetProperties&Status=1";
                    }

                    ////THIS IS HOW TO DELETE/////
                    //                        storeFile.delete();
                    //                        storeFileThumbnail.delete();
                    ////THIS IS HOW TO DELETE/////
                } else {
                    request.setAttribute("Status", "This Property Has Been Updated successfully!");
                    address = "ManagePropertys?GetProperties&Status=1";
                }
            }
        }

    } catch (Exception ex) {
        address = "/Error.jsp";
    } //end catch
    response.sendRedirect("/RealtyWebsite/" + address);
    //            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
    //            dispatcher.forward(request, response);

    processRequest(request, response);
}

From source file:nl.b3p.gis.viewer.PrintAction.java

public ActionForward print(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    /* ophalen form waardes */
    String title = FormUtils.nullIfEmpty(dynaForm.getString("title"));
    String imageId = FormUtils.nullIfEmpty(dynaForm.getString("imageId"));
    String imageSize = FormUtils.nullIfEmpty(dynaForm.getString("imageSize"));
    String pageSize = FormUtils.nullIfEmpty(dynaForm.getString("pageSize"));
    boolean landscape = Boolean.valueOf(dynaForm.getString("landscape")).booleanValue();
    String outputType = FormUtils.nullIfEmpty(dynaForm.getString("outputType"));
    String remark = FormUtils.nullIfEmpty(dynaForm.getString("remark"));

    Object strPPI = dynaForm.get("ppi");

    Integer PPI = DEFAULT_PPI;/*from  w w  w  .  ja va 2 s  . c o m*/
    if (strPPI != null) {
        PPI = (Integer) strPPI;
    }

    Principal user = request.getUserPrincipal();
    GisPrincipal gp = (GisPrincipal) user;
    String organizationcode = gp.getSp().getOrganizationCode();

    /* huidige CombineImageSettings ophalen */
    CombineImageSettings originalSettings = (CombineImageSettings) request.getSession().getAttribute(imageId);
    CombineImageSettings settings = CombineImageSettings.fromJson(originalSettings.getOriginalJSON());
    settings.setLegendMap(originalSettings.getLegendMap());// Argh, ugly ugly ugly :'(

    /* bbox klaarzetten voor xsl */
    String bbox = "";
    if (settings.getBbox() != null) {
        String minx = Double.toString(settings.getBbox().getMinx());
        String miny = Double.toString(settings.getBbox().getMiny());
        String maxx = Double.toString(settings.getBbox().getMaxx());
        String maxy = Double.toString(settings.getBbox().getMaxy());
        bbox = minx + "," + miny + "," + maxx + "," + maxy;
    }

    /* nu */
    Date now = new Date();
    SimpleDateFormat df = new SimpleDateFormat("d MMMMM yyyy", new Locale("NL"));

    String imageUrl = createImageUrl(request);

    /* template keuze */
    String template;

    if (landscape && pageSize.equals("A4")) {
        template = PrintServlet.xsl_A4_Liggend;
    } else if (!landscape && pageSize.equals("A4")) {
        template = PrintServlet.xsl_A4_Staand;
    } else if (landscape && pageSize.equals("A3")) {
        template = PrintServlet.xsl_A3_Liggend;
    } else if (!landscape && pageSize.equals("A3")) {
        template = PrintServlet.xsl_A3_Staand;
    } else if (landscape && pageSize.equals("A2")) {
        template = PrintServlet.xsl_A2_Liggend;
    } else if (!landscape && pageSize.equals("A2")) {
        template = PrintServlet.xsl_A2_Staand;
    } else if (landscape && pageSize.equals("A1")) {
        template = PrintServlet.xsl_A1_Liggend;
    } else if (!landscape && pageSize.equals("A1")) {
        template = PrintServlet.xsl_A1_Staand;
    } else if (landscape && pageSize.equals("A0")) {
        template = PrintServlet.xsl_A0_Liggend;
    } else if (!landscape && pageSize.equals("A0")) {
        template = PrintServlet.xsl_A0_Staand;
    } else {
        template = PrintServlet.xsl_A4_Liggend;
    }

    /* nieuw (xml) Object voor gebruik met fop */
    PrintInfo info = new PrintInfo();

    info.setTitel(title);
    info.setDatum(df.format(now));
    info.setImageUrl(imageUrl);
    info.setBbox(bbox);
    info.setOpmerking(remark);
    info.setOrganizationcode(organizationcode);

    /* Indien schaal ingevuld in printvoorbeeld de bbox opnieuw berekenen. */
    Integer currentScale = calcCurrentScale(settings);
    String oldBBox = calculateBboxForScale(settings, currentScale);

    Integer newScale = (Integer) dynaForm.get("scale");
    String newBbox;
    if (newScale != null && newScale > 0) {
        newBbox = calculateBboxForScale(settings, newScale);
        info.setBbox(newBbox);
        settings.setBbox(newBbox);
        info.setScale(newScale);
    }

    /* Test voor grotere print resoluties en papier formaten a0, a1 en a2 */
    Double paperInches = convertPaperFormatToInches(pageSize, landscape);

    Integer newWidthPx = calcNewMapWidthFromPPI(PPI, paperInches);

    info.setKwaliteit(newWidthPx);

    /* Otherwise put legend items on new pages */
    Map legendItemsMap = new HashMap();

    String[] arr = (String[]) dynaForm.get("legendItems");
    if (arr != null && arr.length > 0) {
        for (int i = 0; i < arr.length; i++) {
            String key = arr[i];

            if (settings.getLegendMap() != null && settings.getLegendMap().containsKey(key)) {
                String url = (String) settings.getLegendMap().get(key);
                legendItemsMap.put(key, url);
            }
        }
    }

    info.setLegendItems(legendItemsMap);

    /* Ophalen kolom instellingen */
    String scaleColumnOne = (String) request.getParameter("scaleColumnOne");
    String scaleColumnTwo = (String) request.getParameter("scaleColumnTwo");
    String scaleColumnThree = (String) request.getParameter("scaleColumnThree");

    String titleColumnOne = (String) request.getParameter("titleColumnOne");
    String titleColumnTwo = (String) request.getParameter("titleColumnTwo");
    String titleColumnThree = (String) request.getParameter("titleColumnThree");

    if (scaleColumnOne != null && scaleColumnOne.equalsIgnoreCase("on")) {
        info.setScaleColumnOne("on");
    }
    if (scaleColumnTwo != null && scaleColumnTwo.equalsIgnoreCase("on")) {
        info.setScaleColumnTwo("on");
    }
    if (scaleColumnThree != null && scaleColumnThree.equalsIgnoreCase("on")) {
        info.setScaleColumnThree("on");
    }

    if (titleColumnOne != null && titleColumnOne.equalsIgnoreCase("on")) {
        info.setTitleColumnOne("on");
    }
    if (titleColumnTwo != null && titleColumnTwo.equalsIgnoreCase("on")) {
        info.setTitleColumnTwo("on");
    }
    if (titleColumnThree != null && titleColumnThree.equalsIgnoreCase("on")) {
        info.setTitleColumnThree("on");
    }

    /* Ophalen radio button per kaartlaag om in juiste kolom te plaatsen */
    Map legendItemsOne = new HashMap();
    Map legendItemsTwo = new HashMap();
    Map legendItemsThree = new HashMap();

    for (Map.Entry<String, String> entry : settings.getLegendMap().entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();

        String formValue = (String) request.getParameter(key);
        Integer column = 0;

        if (formValue != null && !formValue.equals("")) {
            column = new Integer(formValue);
        }

        if (column == 1) {
            legendItemsOne.put(key, value);
        }
        if (column == 2) {
            legendItemsTwo.put(key, value);
        }
        if (column == 3) {
            legendItemsThree.put(key, value);
        }
    }

    info.setColumnOneItems(legendItemsOne);
    info.setColumnTwoItems(legendItemsTwo);
    info.setColumnThreeItems(legendItemsThree);

    /* doorgeven mimetype en template */
    String mimeType;

    if (outputType != null && outputType.equals(OUTPUT_PDF) || outputType.equals(OUTPUT_PDF_PRINT)) {
        mimeType = MimeConstants.MIME_PDF;
    } else if (outputType != null && outputType.equals(OUTPUT_RTF)) {
        mimeType = MimeConstants.MIME_RTF;
    } else {
        mimeType = MimeConstants.MIME_PDF;
    }

    /* add javascript print dialog to pdf ? */
    boolean addJavascript = false;
    if (outputType.equals(OUTPUT_PDF_PRINT)) {
        addJavascript = true;
    }

    logFile.debug("Print url: " + info.getImageUrl());

    /* Maak de output */
    PrintServlet.setSettings(settings);
    PrintServlet.createOutput(info, mimeType, template, addJavascript, response);

    return null;
}