Example usage for javax.servlet.http HttpSession getServletContext

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

Introduction

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

Prototype

public ServletContext getServletContext();

Source Link

Document

Returns the ServletContext to which this session belongs.

Usage

From source file:uk.ac.ebi.ep.controller.BrowseTaxonomyController.java

@RequestMapping(value = SEARCH_BY_TAX_ID + "/page={pageNumber}", method = RequestMethod.GET)
public String searchByTaxIdPaginated(@PathVariable Integer pageNumber,
        @ModelAttribute("searchModel") SearchModel searchModel,
        @RequestParam(value = "entryid", required = true) Long entryID,
        @RequestParam(value = "entryname", required = false) String entryName, Model model, HttpSession session,
        RedirectAttributes attributes) {

    if (pageNumber < 1) {
        pageNumber = 1;//from   w w  w. j a  v  a 2  s .  c  o m
    }

    Pageable pageable = new PageRequest(pageNumber - 1, SEARCH_PAGESIZE, Sort.Direction.ASC, "function",
            "entryType");

    Page<UniprotEntry> page = this.enzymePortalService.findEnzymesByTaxonomy(entryID, pageable);

    List<Species> species = enzymePortalService.findSpeciesByTaxId(entryID);
    List<Compound> compouds = enzymePortalService.findCompoundsByTaxId(entryID);
    List<Disease> diseases = enzymePortalService.findDiseasesByTaxId(entryID);
    List<EcNumber> enzymeFamilies = enzymePortalService.findEnzymeFamiliesByTaxId(entryID);

    SearchParams searchParams = searchModel.getSearchparams();
    searchParams.setStart(0);
    searchParams.setType(SearchParams.SearchType.KEYWORD);
    searchParams.setText(entryName);
    searchParams.setSize(SEARCH_PAGESIZE);
    searchModel.setSearchparams(searchParams);

    List<UniprotEntry> result = page.getContent();

    int current = page.getNumber() + 1;
    int begin = Math.max(1, current - 5);
    int end = Math.min(begin + 10, page.getTotalPages());

    model.addAttribute("page", page);
    model.addAttribute("beginIndex", begin);
    model.addAttribute("endIndex", end);
    model.addAttribute("currentIndex", current);

    model.addAttribute("organismName", entryName);
    model.addAttribute("taxId", entryID);

    // model.addAttribute("summaryEntries", result);
    SearchResults searchResults = new SearchResults();

    searchResults.setTotalfound(page.getTotalElements());
    SearchFilters filters = new SearchFilters();

    filters.setSpecies(species);
    filters.setCompounds(compouds);
    filters.setEcNumbers(enzymeFamilies);
    filters.setDiseases(diseases);

    searchResults.setSearchfilters(filters);
    searchResults.setSummaryentries(result);

    searchModel.setSearchresults(searchResults);
    model.addAttribute("searchModel", searchModel);
    model.addAttribute("searchConfig", searchConfig);

    model.addAttribute("searchFilter", filters);

    String searchKey = getSearchKey(searchModel.getSearchparams());
    cacheSearch(session.getServletContext(), searchKey, searchResults);
    setLastSummaries(session, searchResults.getSummaryentries());
    clearHistory(session);
    addToHistory(session, searchModel.getSearchparams().getType(), searchKey);

    return RESULT;

}

From source file:org.wso2.carbon.ui.AbstractCarbonUIAuthenticator.java

/**
 * //w ww .j a v  a2s . co  m
 * @param request
 * @param userName
 * @throws Exception
 */
public void onSuccessAdminLogin(HttpServletRequest request, String userName) throws Exception {

    HttpSession session = request.getSession();

    String tenantDomain = MultitenantUtils.getTenantDomain(userName);
    if (tenantDomain != null && tenantDomain.trim().length() > 0) {
        session.setAttribute(MultitenantConstants.TENANT_DOMAIN, tenantDomain);
        // we will make it an attribute on request as well
        if (request.getAttribute(MultitenantConstants.TENANT_DOMAIN) == null) {
            request.setAttribute(MultitenantConstants.TENANT_DOMAIN, tenantDomain);
        }
    } else {
        audit.info("User with null domain tried to login.");
        return;
    }

    if (session.getAttribute(CarbonConstants.LOGGED_USER) != null) {
        userName = (String) session.getAttribute(CarbonConstants.LOGGED_USER);
    }
    request.setAttribute(AbstractCarbonUIAuthenticator.USERNAME, userName);

    String serverURL = getBackendUrl(request);
    if (serverURL == null) {
        throw new AuthenticationException("Server not initialized properly.");
    }

    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);

    // For local transport, cookie might be null.
    if ((serverURL == null || cookie == null) && (!CarbonUtils.isRunningOnLocalTransportMode())) {
        throw new Exception("Cannot proceed logging in. The server URL and/or Cookie is null");
    }

    if (tenantDomain != null && MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain.trim())) {
        request.getSession().setAttribute(MultitenantConstants.IS_SUPER_TENANT, "true");
    } else if (tenantDomain != null && tenantDomain.trim().length() > 0) {
        session.setAttribute(MultitenantConstants.TENANT_DOMAIN, tenantDomain);
        // we will make it an attribute on request as well
        if (request.getAttribute(MultitenantConstants.TENANT_DOMAIN) == null) {
            request.setAttribute(MultitenantConstants.TENANT_DOMAIN, tenantDomain);
        }
    } else {
        audit.info("User with null domain tried to login.");
        return;
    }

    String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(userName);

    setUserInformation(cookie, serverURL, session);

    session.setAttribute(CarbonConstants.LOGGED_USER, tenantAwareUserName);
    session.getServletContext().setAttribute(CarbonConstants.LOGGED_USER, tenantAwareUserName);
    session.setAttribute("authenticated", Boolean.parseBoolean("true"));

    UIAuthenticationExtender[] uiAuthenticationExtenders = CarbonUIServiceComponent
            .getUIAuthenticationExtenders();
    for (UIAuthenticationExtender uiAuthenticationExtender : uiAuthenticationExtenders) {
        uiAuthenticationExtender.onSuccessAdminLogin(request, tenantAwareUserName, tenantDomain, serverURL);
    }
}

From source file:de.betterform.agent.web.WebUtil.java

/**
 * this method is responsible for passing all context information needed by the Adapter and Processor from
 * ServletRequest to Context. Will be called only once when the form-session is inited (GET).
 * <p/>//  ww  w  .  j  a va 2 s .c  om
 * <p/>
 * todo: better logging of context params
 *
 * @param request     the Servlet request to fetch params from
 * @param httpSession the Http Session context
 * @param processor   the XFormsProcessor which receives the context params
 * @param sessionkey  the key to identify the XFormsSession
 */
public static void setContextParams(HttpServletRequest request, HttpSession httpSession,
        XFormsProcessor processor, String sessionkey) throws XFormsConfigException {
    Map servletMap = new HashMap();
    servletMap.put(WebProcessor.SESSION_ID, sessionkey);
    processor.setContextParam(XFormsProcessor.SUBMISSION_RESPONSE, servletMap);

    //adding requestURI to context
    processor.setContextParam(WebProcessor.REQUEST_URI, WebUtil.getRequestURI(request));

    //adding request URL to context
    String requestURL = request.getRequestURL().toString();
    processor.setContextParam(WebProcessor.REQUEST_URL, requestURL);

    // the web app name with an '/' prepended e.g. '/betterform' by default
    String contextRoot = WebUtil.getContextRoot(request);
    processor.setContextParam(WebProcessor.CONTEXTROOT, contextRoot);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("context root of webapp: " + processor.getContextParam(WebProcessor.CONTEXTROOT));
    }

    String requestPath = "";
    URL url = null;
    String plainPath = "";
    try {
        url = new URL(requestURL);
        requestPath = url.getPath();
    } catch (MalformedURLException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    if (requestPath.length() != 0) {
        //adding request path e.g. '/betterform/forms/demo/registration.xhtml'
        processor.setContextParam(WebProcessor.REQUEST_PATH, requestPath);

        //adding filename of requested doc to context
        String fileName = requestPath.substring(requestPath.lastIndexOf('/') + 1, requestPath.length());//FILENAME xforms
        processor.setContextParam(FILENAME, fileName);

        if (requestURL.contains(contextRoot)) { //case1: contextRoot is a part of the URL
            //adding plainPath which is the part between contextroot and filename e.g. '/forms' for a requestPath of '/betterform/forms/Status.xhtml'
            plainPath = requestPath.substring(contextRoot.length() + 1,
                    requestPath.length() - fileName.length());
            processor.setContextParam(PLAIN_PATH, plainPath);
        } else {//case2: contextRoot is not a part of the URL take the part previous the filename.
            String[] urlParts = requestURL.split("/");
            plainPath = urlParts[urlParts.length - 2];
        }

        //adding contextPath - requestPath without the filename
        processor.setContextParam(CONTEXT_PATH, contextRoot + "/" + plainPath);
    }

    //adding session id to context
    processor.setContextParam(HTTP_SESSION_ID, httpSession.getId());
    //adding context absolute path to context

    //EXIST-WORKAROUND: TODO triple check ...
    //TODO: triple check where this is used.
    if (request.isRequestedSessionIdValid()) {
        processor.setContextParam(EXISTDB_USER, httpSession.getAttribute(EXISTDB_USER));
    }

    //adding pathInfo to context - attention: this is only available when a servlet is requested
    String s1 = request.getPathInfo();
    if (s1 != null) {
        processor.setContextParam(WebProcessor.PATH_INFO, s1);
    }
    processor.setContextParam(WebProcessor.QUERY_STRING,
            (request.getQueryString() != null ? request.getQueryString() : ""));

    //storing the realpath for webapp

    String realPath = WebFactory.getRealPath(".", httpSession.getServletContext());
    File f = new File(realPath);
    URI fileURI = f.toURI();

    processor.setContextParam(WebProcessor.REALPATH, fileURI.toString());
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("real path of webapp: " + realPath);
    }

    //storing the TransformerService
    processor.setContextParam(TransformerService.TRANSFORMER_SERVICE,
            httpSession.getServletContext().getAttribute(TransformerService.TRANSFORMER_SERVICE));
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("TransformerService: "
                + httpSession.getServletContext().getAttribute(TransformerService.TRANSFORMER_SERVICE));
    }

    //[2] read any request params that are *not* betterForm params and pass them into the context map
    Enumeration params = request.getParameterNames();
    String s;
    while (params.hasMoreElements()) {
        s = (String) params.nextElement();
        //store all request-params we don't use in the context map of XFormsProcessorImpl
        String value = request.getParameter(s);
        processor.setContextParam(s, value);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("added request param '" + s + "' added to context");
            LOGGER.debug("param value'" + value);
        }
    }

}

From source file:org.intermine.web.struts.BagBuildController.java

/**
 * Set up environment for the buildBag page.
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @return an ActionForward object defining where control goes next
 *
 * @exception Exception if an error occurs
 *//*from   w  ww  . j a v a 2  s.  co  m*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession();
    final InterMineAPI im = SessionMethods.getInterMineAPI(session);
    Model model = im.getModel();

    ObjectStore os = im.getObjectStore();
    ObjectStoreSummary oss = im.getObjectStoreSummary();

    Collection<String> qualifiedTypes = model.getClassNames();

    ArrayList<String> typeList = new ArrayList();
    ArrayList<String> preferedTypeList = new ArrayList();

    TagManager tagManager = im.getTagManager();
    List<Tag> preferredBagTypeTags = tagManager.getTags("im:preferredBagType", null, "class",
            im.getProfileManager().getSuperuser());
    for (Tag tag : preferredBagTypeTags) {
        preferedTypeList.add(TypeUtil.unqualifiedName(tag.getObjectIdentifier()));
    }
    Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
    for (Iterator<String> iter = qualifiedTypes.iterator(); iter.hasNext();) {
        String className = iter.next();
        String unqualifiedName = TypeUtil.unqualifiedName(className);
        if (ClassKeyHelper.hasKeyFields(classKeys, unqualifiedName) && oss.getClassCount(className) > 0) {
            typeList.add(unqualifiedName);
        }
    }
    Collections.sort(preferedTypeList);
    Collections.sort(typeList);
    request.setAttribute("typeList", typeList);
    request.setAttribute("preferredTypeList", preferedTypeList);

    BagQueryConfig bagQueryConfig = im.getBagQueryConfig();
    String extraClassName = bagQueryConfig.getExtraConstraintClassName();
    if (extraClassName != null) {
        request.setAttribute("extraBagQueryClass", TypeUtil.unqualifiedName(extraClassName));

        List extraClassFieldValues = getFieldValues(os, oss, extraClassName,
                bagQueryConfig.getConstrainField());
        request.setAttribute("extraClassFieldValues", extraClassFieldValues);

        // find the types in typeList that contain a field with the name given by
        // bagQueryConfig.getConnectField()
        List<String> typesWithConnectingField = new ArrayList<String>();
        Iterator<String> allTypesIterator = new IteratorChain(typeList.iterator(), preferedTypeList.iterator());
        while (allTypesIterator.hasNext()) {
            String connectFieldName = bagQueryConfig.getConnectField();
            String typeName = allTypesIterator.next();
            String qualifiedTypeName = model.getPackageName() + "." + typeName;
            ClassDescriptor cd = model.getClassDescriptorByName(qualifiedTypeName);
            FieldDescriptor fd = cd.getFieldDescriptorByName(connectFieldName);
            if (fd != null && fd instanceof ReferenceDescriptor) {
                typesWithConnectingField.add(typeName);
            }
        }
        request.setAttribute("typesWithConnectingField", typesWithConnectingField);
        final String defaultValue = getDefaultValue(request, im);
        if (StringUtils.isNotEmpty(defaultValue)) {
            BuildBagForm bbf = (BuildBagForm) form;
            bbf.setExtraFieldValue(defaultValue);
        }
    }

    // get example bag values
    String bagExampleIdentifiersPropertiesKey = "bag.example.identifiers";
    ServletContext servletContext = session.getServletContext();
    Properties properties = SessionMethods.getWebProperties(servletContext);
    Properties bagExampleIdentifiers = PropertiesUtil
            .getPropertiesStartingWith(bagExampleIdentifiersPropertiesKey, properties);
    if (bagExampleIdentifiers.size() != 0) {
        Map<String, String> bagExampleIdentifiersMap = new HashMap<String, String>();
        Enumeration<?> e = bagExampleIdentifiers.propertyNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String value = bagExampleIdentifiers.getProperty(key);
            if (key.equals(bagExampleIdentifiersPropertiesKey)) {
                bagExampleIdentifiersMap.put("default", value);
            } else {
                bagExampleIdentifiersMap.put(key.replace(bagExampleIdentifiersPropertiesKey + ".", ""), value);
            }
            bagExampleIdentifiers.getProperty(key);
        }
        request.setAttribute("bagExampleIdentifiers", bagExampleIdentifiersMap);
    }
    return null;
}

From source file:controller.ChartAndGraphServlet.java

/**
 * Creates the appropriate chart for the patient history page or the
 * statistics page. Line charts are created to display a longitudinal view
 * of patient results on the history page. The statistics page includes pie
 * charts, bar charts, histograms, and box and whisker charts.
 *
 * @param request servlet request/*from  w ww .  j  a  va2 s . com*/
 * @param response servlet response
 * @throws IOException
 */
public void getChart(HttpServletRequest request, HttpServletResponse response) throws IOException {
    HttpSession session = request.getSession();
    response.setContentType("image/png");
    OutputStream outputStream = response.getOutputStream();
    final int widthIncreaseThreshold = 18;
    final int incrementalIncreaseThreshold = 22;
    final int incrementalIncreaseInPixels = 45;
    final int treatmentClassUnknownIndex = 6;
    int width = 640;
    int height = 450;
    int bigWidth = 780;
    ReferenceContainer rc = (ReferenceContainer) session.getServletContext().getAttribute("references");
    HealthyTargetReference htr = rc.getHealthyTargets();
    String action = request.getParameter("action");

    switch (action) {
    case "a1c": {
        ArrayList<A1cResult> a1cHistory = (ArrayList<A1cResult>) session
                .getAttribute(SessionObjectUtility.A1C_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = a1cHistory.size() - 1; i > -1; i--) {
            dataset.addValue(a1cHistory.get(i).getValue(), "A1C", a1cHistory.get(i).getDate());
        }
        /* remove reference */
        session.setAttribute(SessionObjectUtility.A1C_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("A1C History", "dates", "A1C", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getA1c().getUpperBound();
        BigDecimal lower = htr.getA1c().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (a1cHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (a1cHistory.size() > incrementalIncreaseThreshold) {
            int increments = a1cHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "psa": {
        ArrayList<ContinuousResult> psaHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.PSA_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = psaHistory.size() - 1; i > -1; i--) {
            dataset.addValue(psaHistory.get(i).getValue(), "PSA", psaHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.PSA_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("PSA History", "dates", "PSA", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getPsa().getUpperBound();
        BigDecimal lower = htr.getPsa().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (psaHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (psaHistory.size() > incrementalIncreaseThreshold) {
            int increments = psaHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "alt": {
        ArrayList<ContinuousResult> altHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.ALT_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = altHistory.size() - 1; i > -1; i--) {
            dataset.addValue(altHistory.get(i).getValue(), "ALT", altHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.ALT_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("ALT History", "dates", "ALT", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getAlt().getUpperBound();
        BigDecimal lower = htr.getAlt().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (altHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (altHistory.size() > incrementalIncreaseThreshold) {
            int increments = altHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "ast": {
        ArrayList<ContinuousResult> astHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.AST_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = astHistory.size() - 1; i > -1; i--) {
            dataset.addValue(astHistory.get(i).getValue(), "AST", astHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.AST_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("AST History", "dates", "AST", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getAst().getUpperBound();
        BigDecimal lower = htr.getAst().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (astHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (astHistory.size() > incrementalIncreaseThreshold) {
            int increments = astHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "bp": {
        ArrayList<BloodPressureResult> bpHistory = (ArrayList<BloodPressureResult>) session
                .getAttribute(SessionObjectUtility.BP_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = bpHistory.size() - 1; i > -1; i--) {
            dataset.addValue(bpHistory.get(i).getSystolicValue(), "systolic", bpHistory.get(i).getDate());
            dataset.addValue(bpHistory.get(i).getDiastolicValue(), "diastolic", bpHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.BP_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Blood Pressure History", "dates", "blood pressure",
                dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upperSystole = htr.getBloodPressureSystole().getUpperBound();
        BigDecimal upperDiastole = htr.getBloodPressureDiastole().getUpperBound();
        if (upperSystole != null) {
            ValueMarker marker = new ValueMarker(upperSystole.doubleValue());
            marker.setPaint(Color.MAGENTA);
            plot.addRangeMarker(marker);
        }
        if (upperDiastole != null) {
            ValueMarker marker = new ValueMarker(upperDiastole.doubleValue());
            marker.setPaint(Color.BLUE);
            plot.addRangeMarker(marker);
        }

        if (bpHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (bpHistory.size() > incrementalIncreaseThreshold) {
            int increments = bpHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "bmi": {
        ArrayList<ContinuousResult> bmiHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.BMI_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = bmiHistory.size() - 1; i > -1; i--) {
            dataset.addValue(bmiHistory.get(i).getValue(), "BMI", bmiHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.BMI_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("BMI History", "dates", "BMI", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getBmi().getUpperBound();
        BigDecimal lower = htr.getBmi().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (bmiHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (bmiHistory.size() > incrementalIncreaseThreshold) {
            int increments = bmiHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "creatinine": {
        ArrayList<ContinuousResult> creatinineHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.CREATININE_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = creatinineHistory.size() - 1; i > -1; i--) {
            dataset.addValue(creatinineHistory.get(i).getValue(), "creatinine",
                    creatinineHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.CREATININE_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Creatinine History", "dates", "creatinine", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getCreatinine().getUpperBound();
        BigDecimal lower = htr.getCreatinine().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (creatinineHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (creatinineHistory.size() > incrementalIncreaseThreshold) {
            int increments = creatinineHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "egfr": {
        ArrayList<ContinuousResult> egfrHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.EGFR_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = egfrHistory.size() - 1; i > -1; i--) {
            dataset.addValue(egfrHistory.get(i).getValue(), "eGFR", egfrHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.EGFR_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("eGFR History", "dates", "eGFR", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getEgfr().getUpperBound();
        BigDecimal lower = htr.getEgfr().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (egfrHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (egfrHistory.size() > incrementalIncreaseThreshold) {
            int increments = egfrHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "glucose": {
        ArrayList<ContinuousResult> glucoseHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.GLUCOSE_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = glucoseHistory.size() - 1; i > -1; i--) {
            dataset.addValue(glucoseHistory.get(i).getValue(), "glucose", glucoseHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.GLUCOSE_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Glucose History", "dates", "glucose", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getGlucoseAc().getUpperBound();
        BigDecimal lower = htr.getGlucoseAc().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (glucoseHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (glucoseHistory.size() > incrementalIncreaseThreshold) {
            int increments = glucoseHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "hdl": {
        ArrayList<ContinuousResult> hdlHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.HDL_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = hdlHistory.size() - 1; i > -1; i--) {
            dataset.addValue(hdlHistory.get(i).getValue(), "HDL", hdlHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.HDL_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /*get the chart */
        JFreeChart chart = ChartFactory.createLineChart("HDL History", "dates", "HDL", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upperFemale = htr.getHdlFemale().getUpperBound();
        BigDecimal lowerFemale = htr.getHdlFemale().getLowerBound();
        BigDecimal upperMale = htr.getHdlMale().getUpperBound();
        BigDecimal lowerMale = htr.getHdlMale().getLowerBound();
        if (upperFemale != null) {
            ValueMarker marker = new ValueMarker(upperFemale.doubleValue());
            marker.setPaint(Color.MAGENTA);
            plot.addRangeMarker(marker);
        }
        if (lowerFemale != null) {
            ValueMarker marker = new ValueMarker(lowerFemale.doubleValue());
            marker.setPaint(Color.MAGENTA);
            plot.addRangeMarker(marker);
        }
        if (upperMale != null) {
            ValueMarker marker = new ValueMarker(upperMale.doubleValue());
            marker.setPaint(Color.BLUE);
            plot.addRangeMarker(marker);
        }
        if (lowerMale != null) {
            ValueMarker marker = new ValueMarker(lowerMale.doubleValue());
            marker.setPaint(Color.BLUE);
            plot.addRangeMarker(marker);
        }

        if (hdlHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (hdlHistory.size() > incrementalIncreaseThreshold) {
            int increments = hdlHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "ldl": {
        ArrayList<LdlResult> ldlHistory = (ArrayList<LdlResult>) session
                .getAttribute(SessionObjectUtility.LDL_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = ldlHistory.size() - 1; i > -1; i--) {
            dataset.addValue(ldlHistory.get(i).getValue(), "LDL", ldlHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.LDL_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("LDL History", "dates", "LDL", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getLdl().getUpperBound();
        BigDecimal lower = htr.getLdl().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (ldlHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (ldlHistory.size() > incrementalIncreaseThreshold) {
            int increments = ldlHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "compliance": {
        ArrayList<ContinuousResult> complianceHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.COMPLIANCE_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = complianceHistory.size() - 1; i > -1; i--) {
            dataset.addValue(complianceHistory.get(i).getValue(), "compliance",
                    complianceHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.COMPLIANCE_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Compliance History", "dates", "compliance", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        if (complianceHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (complianceHistory.size() > incrementalIncreaseThreshold) {
            int increments = complianceHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "physicalActivity": {
        ArrayList<DiscreteResult> physicalActivityHistory = (ArrayList<DiscreteResult>) session
                .getAttribute(SessionObjectUtility.PHYSICAL_ACTIVITY_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = physicalActivityHistory.size() - 1; i > -1; i--) {
            dataset.addValue(physicalActivityHistory.get(i).getValue(), "physical activity",
                    physicalActivityHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.PHYSICAL_ACTIVITY_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Physical Activity History", "dates", "min per wk",
                dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getPhysicalActivity().getUpperBound();
        BigDecimal lower = htr.getPhysicalActivity().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (physicalActivityHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (physicalActivityHistory.size() > incrementalIncreaseThreshold) {
            int increments = physicalActivityHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "psychological": {
        ArrayList<PsychologicalScreeningResult> psychologicalHistory = (ArrayList<PsychologicalScreeningResult>) session
                .getAttribute(SessionObjectUtility.PSYCHOLOGICAL_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = psychologicalHistory.size() - 1; i > -1; i--) {
            dataset.addValue(psychologicalHistory.get(i).getScore(), "PHQ9 score",
                    psychologicalHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.PSYCHOLOGICAL_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Psychological Screening History", "dates", "score",
                dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        if (psychologicalHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (psychologicalHistory.size() > incrementalIncreaseThreshold) {
            int increments = psychologicalHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "t4": {
        ArrayList<ContinuousResult> t4History = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.T4_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = t4History.size() - 1; i > -1; i--) {
            dataset.addValue(t4History.get(i).getValue(), "T4", t4History.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.T4_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("T4 History", "dates", "T4", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getT4().getUpperBound();
        BigDecimal lower = htr.getT4().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (t4History.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (t4History.size() > incrementalIncreaseThreshold) {
            int increments = t4History.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "triglycerides": {
        ArrayList<ContinuousResult> triglyceridesHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.TRIGLYCERIDES_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = triglyceridesHistory.size() - 1; i > -1; i--) {
            dataset.addValue(triglyceridesHistory.get(i).getValue(), "triglycerides",
                    triglyceridesHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.TRIGLYCERIDES_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Triglycerides History", "dates", "triglycerides",
                dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getTriglycerides().getUpperBound();
        BigDecimal lower = htr.getTriglycerides().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (triglyceridesHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (triglyceridesHistory.size() > incrementalIncreaseThreshold) {
            int increments = triglyceridesHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "tsh": {
        ArrayList<TshResult> tshHistory = (ArrayList<TshResult>) session
                .getAttribute(SessionObjectUtility.TSH_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = tshHistory.size() - 1; i > -1; i--) {
            dataset.addValue(tshHistory.get(i).getValue(), "TSH", tshHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.TSH_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("TSH History", "dates", "TSH", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getTsh().getUpperBound();
        BigDecimal lower = htr.getTsh().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (tshHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (tshHistory.size() > incrementalIncreaseThreshold) {
            int increments = tshHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "uacr": {
        ArrayList<ContinuousResult> uacrHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.UACR_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = uacrHistory.size() - 1; i > -1; i--) {
            dataset.addValue(uacrHistory.get(i).getValue(), "UACR", uacrHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.UACR_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("UACR History", "dates", "UACR", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getUacr().getUpperBound();
        BigDecimal lower = htr.getUacr().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (uacrHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (uacrHistory.size() > incrementalIncreaseThreshold) {
            int increments = uacrHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "waist": {
        ArrayList<ContinuousResult> waistHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.WAIST_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = waistHistory.size() - 1; i > -1; i--) {
            dataset.addValue(waistHistory.get(i).getValue(), "waist", waistHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.WAIST_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Waist History", "dates", "waist", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upperFemale = htr.getWaistFemale().getUpperBound();
        BigDecimal lowerFemale = htr.getWaistFemale().getLowerBound();
        BigDecimal upperMale = htr.getWaistMale().getUpperBound();
        BigDecimal lowerMale = htr.getWaistMale().getLowerBound();
        if (upperFemale != null) {
            ValueMarker marker = new ValueMarker(upperFemale.doubleValue());
            marker.setPaint(Color.MAGENTA);
            plot.addRangeMarker(marker);
        }
        if (lowerFemale != null) {
            ValueMarker marker = new ValueMarker(lowerFemale.doubleValue());
            marker.setPaint(Color.MAGENTA);
            plot.addRangeMarker(marker);
        }
        if (upperMale != null) {
            ValueMarker marker = new ValueMarker(upperMale.doubleValue());
            marker.setPaint(Color.BLUE);
            plot.addRangeMarker(marker);
        }
        if (lowerMale != null) {
            ValueMarker marker = new ValueMarker(lowerMale.doubleValue());
            marker.setPaint(Color.BLUE);
            plot.addRangeMarker(marker);
        }

        if (waistHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (waistHistory.size() > incrementalIncreaseThreshold) {
            int increments = waistHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "agedemographics": {
        DemographicData demographicData = (DemographicData) session
                .getAttribute(SessionObjectUtility.AGE_DEMOGRAPHICS_GRAPH_DATA);
        HistogramDataset dataset = new HistogramDataset();
        ArrayList<Integer> ages = demographicData.getAges();
        if (ages.size() > 0) {
            double[] vector = new double[ages.size()];

            for (int i = 0; i < vector.length; i++) {
                vector[i] = ages.get(i);
            }

            /* add the data */
            dataset.addSeries("number of patients", vector, 10);

            /* remove reference */
            session.setAttribute(SessionObjectUtility.AGE_DEMOGRAPHICS_GRAPH_DATA, null);

            boolean legend = true;
            boolean tooltips = false;
            boolean urls = false;

            /* get the chart */
            JFreeChart chart = ChartFactory.createHistogram("Age Distribution", "age", "number of patients",
                    dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

            chart.setBorderPaint(Color.GREEN);
            chart.setBorderStroke(new BasicStroke(5.0f));
            chart.setBorderVisible(true);

            XYPlot plot = chart.getXYPlot();

            final XYBarRenderer renderer = (XYBarRenderer) plot.getRenderer();

            /* creating a shadow */
            renderer.setShadowXOffset(4.0);
            renderer.setShadowYOffset(1.5);
            renderer.setShadowVisible(true);

            ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        }
        break;
    }
    case "genderdemographics": {
        DemographicData demographicData = (DemographicData) session
                .getAttribute(SessionObjectUtility.GENDER_DEMOGRAPHICS_GRAPH_DATA);
        DefaultPieDataset dataset = new DefaultPieDataset();

        /* add the data */
        dataset.setValue("female", demographicData.getPercentFemale());
        dataset.setValue("male", demographicData.getPercentMale());

        /* remove reference */
        session.setAttribute(SessionObjectUtility.GENDER_DEMOGRAPHICS_GRAPH_DATA, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createPieChart3D("Gender", dataset, legend, tooltips, urls);

        final PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setStartAngle(90);
        plot.setForegroundAlpha(0.60f);
        plot.setInteriorGap(0.02);

        PieSectionLabelGenerator labels = new StandardPieSectionLabelGenerator("{0}: ({2})",
                new DecimalFormat("0"), new DecimalFormat("0%"));
        plot.setLabelGenerator(labels);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "racedemographics": {
        DemographicData demographicData = (DemographicData) session
                .getAttribute(SessionObjectUtility.RACE_DEMOGRAPHICS_GRAPH_DATA);
        DefaultPieDataset dataset = new DefaultPieDataset();

        /* add the data */
        dataset.setValue("White", demographicData.getPercentWhite());
        dataset.setValue("African American", demographicData.getPercentAfricanAmerican());
        dataset.setValue("Asian/Pacific Islander", demographicData.getPercentAsian());
        dataset.setValue("American Indian/Alaska Native", demographicData.getPercentIndian());
        dataset.setValue("Hispanic", demographicData.getPercentHispanic());
        dataset.setValue("Middle Eastern", demographicData.getPercentMiddleEastern());
        dataset.setValue("Other", demographicData.getPercentOther());

        /* remove reference */
        session.setAttribute(SessionObjectUtility.RACE_DEMOGRAPHICS_GRAPH_DATA, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createPieChart3D("Race", dataset, legend, tooltips, urls);

        final PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setStartAngle(90);
        plot.setForegroundAlpha(0.60f);
        plot.setInteriorGap(0.02);

        PieSectionLabelGenerator labels = new StandardPieSectionLabelGenerator("{0}: ({2})",
                new DecimalFormat("0"), new DecimalFormat("0%"));
        plot.setLabelGenerator(labels);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "lasta1c": {
        Stats glycemicStats = (Stats) session.getAttribute(SessionObjectUtility.LAST_A1C_DATA);
        HistogramDataset dataset = new HistogramDataset();
        ArrayList<CategoricalValue> lastA1cValues = new ArrayList<>();

        if (glycemicStats.getGroups() != null) {
            int i;
            for (i = 0; i < glycemicStats.getGroups().size(); i++) {
                if (glycemicStats.getGroups().get(i) != null) {
                    lastA1cValues.addAll(glycemicStats.getGroups().get(i));
                }
            }
        }
        if (lastA1cValues.size() > 0) {
            double[] vector = new double[lastA1cValues.size()];

            for (int i = 0; i < vector.length; i++) {
                vector[i] = lastA1cValues.get(i).getValue().doubleValue();
            }

            /* add the data */
            dataset.addSeries("number of patients", vector, 15);

            /* remove reference */
            session.setAttribute(SessionObjectUtility.LAST_A1C_DATA, null);

            boolean legend = true;
            boolean tooltips = false;
            boolean urls = false;

            /* get the chart */
            JFreeChart chart = ChartFactory.createHistogram("Most Recent A1C Values", "last A1C(%)",
                    "number of patients", dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

            chart.setBorderPaint(Color.GREEN);
            chart.setBorderStroke(new BasicStroke(5.0f));
            chart.setBorderVisible(true);

            XYPlot plot = chart.getXYPlot();

            final XYBarRenderer renderer = (XYBarRenderer) plot.getRenderer();

            /* creating a shadow */
            renderer.setShadowXOffset(4.0);
            renderer.setShadowYOffset(1.5);
            renderer.setShadowVisible(true);

            ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        }
        break;
    }
    case "lasta1cbyclassattendance": {
        final int topGroupIndex = 4;
        Stats glycemicStats = (Stats) session.getAttribute(SessionObjectUtility.LAST_A1C_BY_CLASS_DATA);

        DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

        if (glycemicStats.getGroups() != null) {
            for (int i = 0; i < glycemicStats.getGroups().size(); i++) {
                if ((glycemicStats.getGroups().get(i) != null)
                        && (!glycemicStats.getGroups().get(i).isEmpty())) {
                    List values = new ArrayList();
                    for (CategoricalValue cv : glycemicStats.getGroups().get(i)) {
                        values.add(cv.getValue());
                    }
                    if (i == topGroupIndex) {
                        dataset.add(BoxAndWhiskerCalculator.calculateBoxAndWhiskerStatistics(values),
                                "last A1C(%)", "5 or more");
                    } else {
                        dataset.add(BoxAndWhiskerCalculator.calculateBoxAndWhiskerStatistics(values),
                                "last A1C(%)", i + 1);
                    }
                }
            }
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.LAST_A1C_BY_CLASS_DATA, null);

        CategoryAxis domainAxis = new CategoryAxis("number of classes attended");
        NumberAxis rangeAxis = new NumberAxis("last A1C(%)");
        BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
        CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);
        JFreeChart chart = new JFreeChart("Most Recent A1C by Classes Attended", plot);
        renderer.setMeanVisible(false);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "lastbmimales": {
        Stats bmiMalesStats = (Stats) session.getAttribute(SessionObjectUtility.LAST_BMI_MALES_DATA);
        HistogramDataset dataset = new HistogramDataset();
        ArrayList<CategoricalValue> lastBmiMalesValues = new ArrayList<>();
        if ((bmiMalesStats.getGroups() != null) && (!bmiMalesStats.getGroups().isEmpty())) {
            for (int i = 0; i < bmiMalesStats.getGroups().size(); i++) {
                if (bmiMalesStats.getGroups().get(i) != null) {
                    lastBmiMalesValues.addAll(bmiMalesStats.getGroups().get(i));
                }
            }
        }
        if (lastBmiMalesValues.size() > 0) {
            double[] vector = new double[lastBmiMalesValues.size()];

            for (int i = 0; i < vector.length; i++) {
                vector[i] = lastBmiMalesValues.get(i).getValue().doubleValue();
            }

            /* add the data */
            dataset.addSeries("number of patients", vector, 15);

            /* remove reference */
            session.setAttribute(SessionObjectUtility.LAST_BMI_MALES_DATA, null);

            boolean legend = true;
            boolean tooltips = false;
            boolean urls = false;

            /* get the chart */
            JFreeChart chart = ChartFactory.createHistogram("Most Recent BMI Values for Males", "last BMI",
                    "number of patients", dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

            chart.setBorderPaint(Color.GREEN);
            chart.setBorderStroke(new BasicStroke(5.0f));
            chart.setBorderVisible(true);

            XYPlot plot = chart.getXYPlot();

            final XYBarRenderer renderer = (XYBarRenderer) plot.getRenderer();

            /* creating a shadow */
            renderer.setShadowXOffset(4.0);
            renderer.setShadowYOffset(1.5);
            renderer.setShadowVisible(true);

            ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        }
        break;
    }
    case "lastbmifemales": {
        Stats bmiFemalesStats = (Stats) session.getAttribute(SessionObjectUtility.LAST_BMI_FEMALES_DATA);
        HistogramDataset dataset = new HistogramDataset();
        ArrayList<CategoricalValue> lastBmiFemalesValues = new ArrayList<>();
        if ((bmiFemalesStats.getGroups() != null) && (!bmiFemalesStats.getGroups().isEmpty())) {
            for (int i = 0; i < bmiFemalesStats.getGroups().size(); i++) {
                if (bmiFemalesStats.getGroups().get(i) != null) {
                    lastBmiFemalesValues.addAll(bmiFemalesStats.getGroups().get(i));
                }
            }
        }
        if (lastBmiFemalesValues.size() > 0) {
            double[] vector = new double[lastBmiFemalesValues.size()];

            for (int i = 0; i < vector.length; i++) {
                vector[i] = lastBmiFemalesValues.get(i).getValue().doubleValue();
            }

            /* add the data */
            dataset.addSeries("number of patients", vector, 15);

            /* remove reference */
            session.setAttribute(SessionObjectUtility.LAST_BMI_FEMALES_DATA, null);

            boolean legend = true;
            boolean tooltips = false;
            boolean urls = false;

            /* get the chart */
            JFreeChart chart = ChartFactory.createHistogram("Most Recent BMI Values for Females", "last BMI",
                    "number of patients", dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

            chart.setBorderPaint(Color.GREEN);
            chart.setBorderStroke(new BasicStroke(5.0f));
            chart.setBorderVisible(true);

            XYPlot plot = chart.getXYPlot();

            final XYBarRenderer renderer = (XYBarRenderer) plot.getRenderer();

            /* creating a shadow */
            renderer.setShadowXOffset(4.0);
            renderer.setShadowYOffset(1.5);
            renderer.setShadowVisible(true);

            ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        }
        break;
    }
    case "lastbmimalesbyclassattendance": {
        final int topGroupIndex = 4;
        Stats bmiMalesStats = (Stats) session.getAttribute(SessionObjectUtility.LAST_BMI_MALES_BY_CLASS_DATA);

        DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

        if (bmiMalesStats.getGroups() != null) {
            for (int i = 0; i < bmiMalesStats.getGroups().size(); i++) {
                if ((bmiMalesStats.getGroups().get(i) != null)
                        && (!bmiMalesStats.getGroups().get(i).isEmpty())) {
                    List values = new ArrayList();
                    for (CategoricalValue cv : bmiMalesStats.getGroups().get(i)) {
                        values.add(cv.getValue());
                    }
                    if (i == topGroupIndex) {
                        dataset.add(BoxAndWhiskerCalculator.calculateBoxAndWhiskerStatistics(values),
                                "last BMI (males)", "5 or more");
                    } else {
                        dataset.add(BoxAndWhiskerCalculator.calculateBoxAndWhiskerStatistics(values),
                                "last BMI (males)", i + 1);
                    }
                }
            }
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.LAST_BMI_MALES_BY_CLASS_DATA, null);

        CategoryAxis domainAxis = new CategoryAxis("number of classes attended");
        NumberAxis rangeAxis = new NumberAxis("last BMI (males)");
        BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
        CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);
        JFreeChart chart = new JFreeChart("Most Recent BMI for Males by Classes Attended", plot);
        renderer.setMeanVisible(false);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "lastbmifemalesbyclassattendance": {
        final int topGroupIndex = 4;
        Stats bmiFemalesStats = (Stats) session
                .getAttribute(SessionObjectUtility.LAST_BMI_FEMALES_BY_CLASS_DATA);

        DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

        if (bmiFemalesStats.getGroups() != null) {
            for (int i = 0; i < bmiFemalesStats.getGroups().size(); i++) {
                if ((bmiFemalesStats.getGroups().get(i) != null)
                        && (!bmiFemalesStats.getGroups().get(i).isEmpty())) {
                    List values = new ArrayList();
                    for (CategoricalValue cv : bmiFemalesStats.getGroups().get(i)) {
                        values.add(cv.getValue());
                    }
                    if (i == topGroupIndex) {
                        dataset.add(BoxAndWhiskerCalculator.calculateBoxAndWhiskerStatistics(values),
                                "last BMI (females)", "5 or more");
                    } else {
                        dataset.add(BoxAndWhiskerCalculator.calculateBoxAndWhiskerStatistics(values),
                                "last BMI (females)", i + 1);
                    }
                }
            }
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.LAST_BMI_FEMALES_BY_CLASS_DATA, null);

        CategoryAxis domainAxis = new CategoryAxis("number of classes attended");
        NumberAxis rangeAxis = new NumberAxis("last BMI (females)");
        BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
        CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);
        JFreeChart chart = new JFreeChart("Most Recent BMI for Females by Classes Attended", plot);
        renderer.setMeanVisible(false);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "lasta1cbytreatment": {
        final int firstIndex = 0;
        Stats glycemicStats = (Stats) session.getAttribute(SessionObjectUtility.LAST_A1C_BY_TREATMENT);

        DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

        if (glycemicStats.getGroups() != null) {
            for (int i = 0; i < glycemicStats.getGroups().size(); i++) {
                if ((glycemicStats.getGroups().get(i) != null)
                        && (!glycemicStats.getGroups().get(i).isEmpty())) {
                    String category = glycemicStats.getGroups().get(i).get(firstIndex) != null
                            ? glycemicStats.getGroups().get(i).get(firstIndex).getCategory()
                            : "";
                    List values = new ArrayList();
                    for (CategoricalValue cv : glycemicStats.getGroups().get(i)) {
                        values.add(cv.getValue());
                    }
                    dataset.add(BoxAndWhiskerCalculator.calculateBoxAndWhiskerStatistics(values), "last A1C(%)",
                            category);
                }
            }
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.LAST_A1C_BY_TREATMENT, null);

        CategoryAxis domainAxis = new CategoryAxis("treatment class");
        NumberAxis rangeAxis = new NumberAxis("last A1C(%)");
        BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
        CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);
        JFreeChart chart = new JFreeChart("Most Recent A1C by Treatment Class", plot);
        renderer.setMeanVisible(false);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "treatmentclasscounts": {
        int treatmentClassCountsIndex = 1;

        Stats treatmentData = (Stats) session.getAttribute(SessionObjectUtility.CLASS_COUNTS_TREATMENT_STATS);
        DefaultPieDataset dataset = new DefaultPieDataset();

        /* add the treatment data to the dataset */
        for (int i = 0; i < treatmentClassUnknownIndex + 1; i++) {
            dataset.setValue(treatmentData.getGroups().get(treatmentClassCountsIndex).get(i).getCategory(),
                    treatmentData.getGroups().get(treatmentClassCountsIndex).get(i).getValue());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.CLASS_COUNTS_TREATMENT_STATS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createPieChart3D("Treatment Class", dataset, legend, tooltips, urls);

        final PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setStartAngle(90);
        plot.setForegroundAlpha(0.60f);
        plot.setInteriorGap(0.02);

        PieSectionLabelGenerator labels = new StandardPieSectionLabelGenerator("{0}: {1} ({2})",
                new DecimalFormat("0"), new DecimalFormat("0%"));
        plot.setLabelGenerator(labels);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "treatmentgenderclasscounts": {
        int maleClassCountsIndex = 2;
        int femaleClassCountsIndex = 3;

        Stats treatmentData = (Stats) session
                .getAttribute(SessionObjectUtility.GENDER_CLASS_COUNTS_TREATMENT_STATS);
        final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        HashMap<Integer, String> genderMap = new HashMap<>();
        genderMap.put(maleClassCountsIndex, "Male");
        genderMap.put(femaleClassCountsIndex, "Female");

        /* load data for males and females into the dataset */
        for (int i = femaleClassCountsIndex; i > maleClassCountsIndex - 1; i--) {
            for (int j = 0; j < treatmentClassUnknownIndex + 1; j++) {
                dataset.addValue(treatmentData.getGroups().get(i).get(j).getValue(), genderMap.get(i),
                        treatmentData.getGroups().get(i).get(j).getCategory());
            }
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.GENDER_CLASS_COUNTS_TREATMENT_STATS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        JFreeChart barChart = ChartFactory.createBarChart("Treatment Class by Gender", "Treatment Class",
                "Number of Patients", dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

        barChart.setBorderPaint(Color.GREEN);
        barChart.setBorderStroke(new BasicStroke(5.0f));
        barChart.setBorderVisible(true);

        CategoryPlot plot = barChart.getCategoryPlot();

        final BarRenderer renderer = (BarRenderer) plot.getRenderer();

        /* creating a shadow */
        renderer.setShadowXOffset(4.0);
        renderer.setShadowYOffset(1.5);
        renderer.setShadowVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, barChart, width, height);

        break;
    }
    case "treatmentraceclasscounts": {
        int whiteClassCountsIndex = 4;
        int africanAmericanClassCountsIndex = 5;
        int asianPacificIslanderClassCountsIndex = 6;
        int americanIndianAlaskaNativeClassCountsIndex = 7;
        int hispanicClassCountsIndex = 8;
        int middleEasternClassCountsIndex = 9;
        int otherClassCountsIndex = 10;

        Stats treatmentData = (Stats) session
                .getAttribute(SessionObjectUtility.RACE_CLASS_COUNTS_TREATMENT_STATS);
        final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        HashMap<Integer, String> raceMap = new HashMap<>();
        raceMap.put(whiteClassCountsIndex, "White");
        raceMap.put(africanAmericanClassCountsIndex, "African American");
        raceMap.put(asianPacificIslanderClassCountsIndex, "Asian/Pacific Islander");
        raceMap.put(americanIndianAlaskaNativeClassCountsIndex, "American Indian/Alaska Native");
        raceMap.put(hispanicClassCountsIndex, "Hispanic");
        raceMap.put(middleEasternClassCountsIndex, "Middle Eastern");
        raceMap.put(otherClassCountsIndex, "Other");

        /* load data for each race into the dataset */
        for (int i = whiteClassCountsIndex; i < otherClassCountsIndex + 1; i++) {
            for (int j = 0; j < treatmentClassUnknownIndex + 1; j++) {
                dataset.addValue(treatmentData.getGroups().get(i).get(j).getValue(), raceMap.get(i),
                        treatmentData.getGroups().get(i).get(j).getCategory());
            }
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.RACE_CLASS_COUNTS_TREATMENT_STATS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        JFreeChart barChart = ChartFactory.createStackedBarChart("Treatment Class by Race", "Treatment Class",
                "Number of Patients", dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

        barChart.setBorderPaint(Color.GREEN);
        barChart.setBorderStroke(new BasicStroke(5.0f));
        barChart.setBorderVisible(true);

        CategoryPlot plot = barChart.getCategoryPlot();

        final BarRenderer renderer = (BarRenderer) plot.getRenderer();

        /* creating a shadow */
        renderer.setShadowXOffset(4.0);
        renderer.setShadowYOffset(1.5);
        renderer.setShadowVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, barChart, width, height);

        break;
    }
    default:
        break;
    }
}

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

@SuppressWarnings("unchecked")
@RequestMapping(value = "setDefence", method = RequestMethod.POST)
@ResponseBody/*from www  .j  ava2  s  .co  m*/
@Transactional
public GeneralResponse setDefence(String set_status, String carNum, HttpSession sess,
        HttpServletRequest request, HttpServletResponse response) {
    GeneralResponse message = new GeneralResponse();
    User loginUser = (User) sess.getAttribute("loginUser");
    String defenceOperation = "";
    if ("0".equals(set_status))
        defenceOperation = "";
    boolean test = false;
    if (test || "test".equals(loginUser.getUserName())) {
        message.setCode(1);
        message.setMsg("" + carNum + defenceOperation + "?");
        return message;
    }
    try {
        //            String jsonStr = "\"mobi_num\":\""+loginUser.getMobile()+"\",\"car_num\":\""+carNum+"\"";
        //            logger.info("jsonStr:"+jsonStr);
        //            String sign = MD5Utils.getMD5Str(jsonStr);
        //            logger.info("sign:"+sign);
        //            jsonStr = "{" + jsonStr + ",\"sign\":\"" + sign + "\"}";
        String path = "http://122.226.49.30:60001/wy/wy/wx/pandect-getdata.action";
        Map<String, String> map = new HashMap<String, String>();
        map.put("rtype", "1");

        Map<String, Object> mapData = new HashMap<String, Object>();
        mapData = new HashMap<String, Object>();
        mapData.put("\"mobi_num\"", "\"" + loginUser.getMobile() + "\"");//???
        mapData.put("\"set_status\"", "\"" + set_status + "\"");//
        mapData.put("\"licenseNumber\"", "\"" + carNum + "\"");//?
        mapData.put("\"md_five\"", "\"itylhogiwuEDjfMK\"");//MD5key=================?
        System.out.println("?=sign?" + mapData.toString());
        String md5Str = MD5Utils.getMD5Str(mapData.toString());//MD5
        mapData.put("\"sign\"", "\"" + md5Str + "\"");//DESsign

        mapData.remove("\"md_five\"");

        //
        String sf_encrypt_Str = DESUtils.encrypt(mapData.toString());

        map.put("data", sf_encrypt_Str);
        String encode = "utf8";
        HttpRequestUtils instance = new HttpRequestUtils();
        String result = instance.sendHttpClientPost(path, map, encode);
        logger.info("---------------result----------" + result);
        String resultAfterDecrypt = DESUtils.decrypt(result);//"Qia0wVT6+gGqDvNHi6qVoHljL16CORbw4afSJ+h2Mv+jwjammp0T2GgCyeZIuEQe"
        logger.info("---------------resultAfterDecrypt----------" + resultAfterDecrypt);
        if (resultAfterDecrypt.indexOf("true") > 0) {
            JSONObject strjsonObject = JSONObject.fromObject(resultAfterDecrypt);
            Map<String, Object> map1Json = new HashMap<String, Object>();
            map1Json = JSONObject.fromObject(strjsonObject);
            String lastaddr = map1Json.get("lastaddr").toString();
            logger.info("---------------lastaddr1----------" + map1Json.get("lastaddr").toString());
            message.setRes(lastaddr == null ? "" : lastaddr);
            CarNumber carNumber = new CarNumber();
            carNumber.setCarNum(carNum);
            carNumber.setDefenceStatus(Integer.valueOf(set_status));
            carNumberService.updateByNum(carNumber);
            message.setCode(1);
            if ("0".equals(set_status))
                sess.getServletContext().removeAttribute("location" + carNum);
            message.setMsg("" + carNum + defenceOperation + "?");
        } else {
            message.setCode(0);
            message.setMsg("" + carNum + defenceOperation + "");
        }
    } catch (Exception e) {
        message.setCode(0);
        message.setMsg(e.getMessage());
    }
    return message;
}

From source file:com.idega.core.accesscontrol.business.LoginBusinessBean.java

protected void storeUserAndGroupInformationInSession(HttpSession session, User user) throws Exception {
    List<Group> groups = null;
    LoginSession lSession = LoginBusinessBean.getLoginSessionBean();
    if (isUsingOldUserSystem()) {
        // Old user system
        // iwc.setSessionAttribute(LoginAttributeParameter, new Hashtable());
        // LoginBusinessBean.setUser(iwc, user);
        lSession.setUser(user);//www  . j  ava2  s .c om
        groups = UserBusiness.getUserGroups(user);
        // Old user system end
    } else {
        // New user system
        // iwc.setSessionAttribute(LoginAttributeParameter, new Hashtable());
        // LoginBusinessBean.setUser(iwc, user);
        lSession.setUser(user);
        IWApplicationContext iwac = getIWApplicationContext(session);
        com.idega.user.business.UserBusiness userbusiness = getUserBusiness(iwac);
        com.idega.user.data.User newUser = com.idega.user.util.Converter.convertToNewUser(user);
        Collection<Group> userGroups = userbusiness.getUserGroups(newUser);
        if (userGroups != null) {
            groups = ListUtil.convertCollectionToList(userGroups);
            // New user system end
        }
    }
    if (groups != null) {
        // LoginBusinessBean.setPermissionGroups(iwc, groups);
        lSession.setPermissionGroups(groups);
    }
    int userGroupId = user.getGroupID();
    if (userGroupId != -1) {
        // LoginBusinessBean.setUserRepresentativeGroup(iwc,
        // ((com.idega.core.user.data.UserGroupRepresentativeHome)com.idega.data.IDOLookup.getHomeLegacy(UserGroupRepresentative.class)).findByPrimaryKeyLegacy(userGroupId));
        lSession.setRepresentativeGroup(
                ((com.idega.core.user.data.UserGroupRepresentativeHome) com.idega.data.IDOLookup
                        .getHomeLegacy(UserGroupRepresentative.class)).findByPrimaryKeyLegacy(userGroupId));
    }
    if (user.getPrimaryGroupID() != -1) {
        GenericGroup primaryGroup = ((com.idega.core.data.GenericGroupHome) com.idega.data.IDOLookup
                .getHome(GenericGroup.class)).findByPrimaryKey(new Integer(user.getPrimaryGroupID()));
        // LoginBusinessBean.setPrimaryGroup(iwc, primaryGroup);
        lSession.setPrimaryGroup(primaryGroup);
    }
    IWMainApplication iwma = IWMainApplication.getIWMainApplication(session.getServletContext());
    UserProperties properties = new UserProperties(iwma, user.getID());
    // setLoginAttribute(USER_PROPERTY_PARAMETER, properties, iwc);
    lSession.setUserProperties(properties);
}

From source file:org.wso2.carbon.ui.CarbonSecuredHttpContext.java

/**
 * {@inheritDoc}//  w  w  w  . j av a 2  s.c  o  m
 */
public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String requestedURI = request.getRequestURI();

    // Get the matching CarbonUIAuthenticator. If no match found for the given request, this
    // will return null.
    CarbonUIAuthenticator authenticator = CarbonUILoginUtil.getAuthenticator(request);

    // This check is required for Single Logout implementation. If the request is not for SSO
    // based authentication page or SSO Servlet, then if the session is invalid redirect the
    // requests to logout_action.jsp.
    CarbonSSOSessionManager ssoSessionManager = CarbonSSOSessionManager.getInstance();
    requestedURI = ssoSessionManager.getRequestedUrl(request, authenticator);

    HttpSession session;
    String sessionId;
    boolean authenticated = false;

    try {
        // Get the user's current authenticated session - if any exists.
        session = request.getSession();
        sessionId = session.getId();
        Boolean authenticatedObj = (Boolean) session.getAttribute("authenticated");
        if (authenticatedObj != null) {
            authenticated = authenticatedObj.booleanValue();
            if (log.isDebugEnabled()) {
                log.debug("Is authenticated " + authenticated);
            }
        }
    } catch (Exception e) {
        log.debug("No session exits");
        return false;
    }

    String context = request.getContextPath();
    if ("/".equals(context)) {
        context = "";
    }

    // We eliminate the /tenant/{tenant-domain} from authentications
    Matcher matcher = CarbonUILoginUtil.getTenantEnabledUriPattern().matcher(requestedURI);
    if (matcher.matches()) {
        log.debug("Tenant webapp request " + requestedURI);
        return CarbonUILoginUtil.escapeTenantWebAppRequests(authenticated, response, requestedURI, context);
    }

    // TODO: When filtered from a Servlet filter the request uri always contains 2 //, this is a
    // temporary fix
    if (requestedURI.indexOf("//") == 0) {
        requestedURI = requestedURI.substring(1);
    }

    if (httpUrlsToBeByPassed.isEmpty()) {
        // Populates http urls to be by passed.
        populatehttpUrlsToBeByPassed();
    }

    if (requestedURI.equals(context) || requestedURI.equals(context + "/")) {
        return handleRequestOnContext(request, response);
    }

    // Storing intermediate value of requestedURI.
    // This is needed for OpenID authentication later.
    String tempUrl = requestedURI;

    // When war is deployed on top of an existing app server we cannot use root context
    // for deployment. Hence a new context is added.Now url changes from eg:
    // carbon/admin/index.jsp to wso2/carbon/admin/index.jsp In this case before doing anything,
    // we need to remove web app context (eg: wso2) .
    CarbonUILoginUtil.addNewContext(requestedURI);

    // Disabling http access to admin console user guide documents should be allowed to access
    // via http protocol
    int val = -1;
    if ((val = allowNonSecuredContent(requestedURI, request, response, authenticated,
            authenticator)) != CarbonUILoginUtil.CONTINUE) {
        if (val == CarbonUILoginUtil.RETURN_TRUE) {
            log.debug("Skipping security check for non secured content. " + requestedURI);
            return true;
        } else {
            log.debug("Security check failed for the resource " + requestedURI);
            return false;
        }
    }
    // We are allowing requests for  .jar/.class resources. Otherwise applets won't get loaded
    // due to session checks. (applet loading happens over https://)
    if (requestedURI.endsWith(".jar") || requestedURI.endsWith(".class")) {
        log.debug("Skipping authentication for .jar files and .class file." + requestedURI);
        return true;
    }

    String resourceURI = requestedURI.replaceFirst("/carbon/", "../");

    if (log.isDebugEnabled()) {
        log.debug("CarbonSecuredHttpContext -> handleSecurity() requestURI:" + requestedURI + " id:" + sessionId
                + " resourceURI:" + resourceURI);
    }

    if (urlsToBeByPassed.isEmpty()) {
        // retrieve urls that should be by-passed from security check
        populateUrlsToBeBypassed();
    }

    // if the current uri is marked to be by-passed, let it pass through
    if (isCurrentUrlToBePassed(request, session, resourceURI)) {
        return true;
    }

    String indexPageURL = CarbonUIUtil.getIndexPageURL(session.getServletContext(), request.getSession());

    // Reading the requestedURL from the cookie to obtain the request made while not
    // authanticated; and setting it as the indexPageURL
    indexPageURL = CarbonUILoginUtil.getIndexPageUrlFromCookie(requestedURI, indexPageURL, request);

    // If a custom index page is used send the login request with the indexpage specified
    indexPageURL = CarbonUILoginUtil.getCustomIndexPage(request, indexPageURL);

    // Reading home page set on product.xml
    // If the params in the servletcontext is null get them from the UTIL
    indexPageURL = updateIndexPageWithHomePage(indexPageURL);

    if ((val = CarbonUILoginUtil.handleLoginPageRequest(requestedURI, request, response, authenticated, context,
            indexPageURL)) != CarbonUILoginUtil.CONTINUE) {
        if (val == CarbonUILoginUtil.RETURN_TRUE) {
            return true;
        } else {
            return false;
        }
    }

    // If authenticator defines to skip URL, return true
    if (ssoSessionManager.skipAuthentication(request)) {
        if (log.isDebugEnabled()) {
            log.debug("Skipping security checks for authenticator defined URL " + requestedURI);
        }
        return true;
    }

    // If someone signed in from a tenant, try to access a different tenant domain, he should be
    // forced to sign out without any prompt Cloud requirement
    requestedURI = CarbonUILoginUtil.getForcedSignOutRequestedURI(requestedURI, request);

    String contextPath = (request.getContextPath().equals("") || request.getContextPath().equals("/")) ? ""
            : request.getContextPath();

    String tenantDomain = (String) session.getAttribute(MultitenantConstants.TENANT_DOMAIN);
    if (tenantDomain != null && !tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
        contextPath += "/" + MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/" + tenantDomain;
    }

    String httpLogin = request.getParameter("gsHttpRequest");

    boolean skipLoginPage = false;

    // Login page is not required for all the Authenticators.
    if (authenticator != null && authenticator.skipLoginPage() && requestedURI.indexOf("login_action.jsp") < 0
            && (requestedURI.endsWith("/carbon/")
                    || (requestedURI.indexOf("/registry/atom") == -1 && requestedURI.endsWith("/carbon")))) {
        // Add this to session for future use.
        request.getSession().setAttribute("skipLoginPage", "true");
    }

    if (request.getSession().getAttribute("skipLoginPage") != null) {
        if ("true".equals(((String) request.getSession().getAttribute("skipLoginPage")))) {
            skipLoginPage = true;
        }
    }

    if (requestedURI.indexOf("login_action.jsp") > -1 && authenticator != null) {
        return CarbonUILoginUtil.handleLogin(authenticator, request, response, session, authenticated,
                contextPath, indexPageURL, httpLogin);
    } else if (requestedURI.indexOf("logout_action.jsp") > 1) {
        return CarbonUILoginUtil.handleLogout(authenticator, request, response, session, authenticated,
                contextPath, indexPageURL, httpLogin);
    }

    if (requestedURI.endsWith("/carbon/")) {
        if (skipLoginPage) {
            response.sendRedirect(contextPath + indexPageURL + "?skipLoginPage=true");
        } else {
            response.sendRedirect(contextPath + indexPageURL);
        }
        return false;
    } else if (requestedURI.indexOf("/registry/atom") == -1 && requestedURI.endsWith("/carbon")) {
        if (skipLoginPage) {
            response.sendRedirect(contextPath + indexPageURL + "?skipLoginPage=true");
        } else {
            response.sendRedirect(contextPath + indexPageURL);
        }
        return false;
    } else if (CarbonUILoginUtil.letRequestedUrlIn(requestedURI, tempUrl)) {
        return true;
    } else if (requestedURI.endsWith(".jsp") && authenticated) {
        return true;
    }

    if (!authenticated) {
        if (requestedURI.endsWith("ajaxprocessor.jsp")) {
            // Prevent login page appearing
            return true;
        } else {
            return CarbonUILoginUtil.saveOriginalUrl(authenticator, request, response, session, skipLoginPage,
                    contextPath, indexPageURL, requestedURI);
        }
    }
    if (request.getSession().isNew()) {
        if (skipLoginPage) {
            response.sendRedirect(contextPath + "/carbon/admin/login_action.jsp");
        } else {
            response.sendRedirect(contextPath + "/carbon/admin/login.jsp");

        }
        return false;
    }
    return true;
}

From source file:com.portfolio.rest.RestServicePortfolio.java

@Path("/nodes/{node-id}/xsl/{xsl-file}")
@GET/*from  www  .  j  a va 2  s.  c o m*/
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_XML)
public String getNodeWithXSL(@CookieParam("user") String user, @CookieParam("credential") String token,
        @QueryParam("group") int groupId, @PathParam("node-id") String nodeUuid,
        @PathParam("xsl-file") String xslFile, @Context ServletConfig sc,
        @Context HttpServletRequest httpServletRequest, @HeaderParam("Accept") String accept,
        @QueryParam("user") Integer userId, @QueryParam("p1") String p1, @QueryParam("p2") String p2,
        @QueryParam("p3") String p3) {
    UserInfo ui = checkCredential(httpServletRequest, user, token, null);

    try {
        javax.servlet.http.HttpSession session = httpServletRequest.getSession(true);
        String ppath = session.getServletContext().getRealPath(File.separator);
        // TODO xslFile avec _ => repertoire_fichier
        xslFile = xslFile.replace(".", "");
        xslFile = xslFile.replace("/", "");
        String[] tmp = xslFile.split("-");

        xslFile = ppath.substring(0, ppath.lastIndexOf(File.separator)) + File.separator + "xsl"
                + File.separator + tmp[0] + File.separator + tmp[1] + ".xsl";
        String returnValue = dataProvider
                .getNodeWithXSL(new MimeType("text/xml"), nodeUuid, xslFile, ui.userId, groupId).toString();
        if (returnValue.length() != 0) {
            if (accept.equals(MediaType.APPLICATION_JSON))
                returnValue = XML.toJSONObject(returnValue).toString();
            logRestRequest(httpServletRequest, null, returnValue, Status.OK.getStatusCode());
        } else {
            throw new RestWebApplicationException(Status.FORBIDDEN, "Vous n'avez pas les droits necessaires");
        }

        return returnValue;
    } catch (RestWebApplicationException ex) {
        throw new RestWebApplicationException(Status.FORBIDDEN, "Vous n'avez pas les droits necessaires");
    }

    catch (NullPointerException ex) {
        logRestRequest(httpServletRequest, null, null, Status.NOT_FOUND.getStatusCode());

        throw new RestWebApplicationException(Status.NOT_FOUND,
                "Node " + nodeUuid + " not found or xsl not found :" + ex.getMessage());
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, null, ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex),
                Status.INTERNAL_SERVER_ERROR.getStatusCode());

        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        dataProvider.disconnect();
    }
}