edu.uiowa.icts.bluebutton.controller.ClinicalDocumentController.java Source code

Java tutorial

Introduction

Here is the source code for edu.uiowa.icts.bluebutton.controller.ClinicalDocumentController.java

Source

package edu.uiowa.icts.bluebutton.controller;

/*
 * #%L
 * blue-button Spring MVC Web App
 * %%
 * Copyright (C) 2014 - 2015 University of Iowa Institute for Clinical and Translational Science (ICTS)
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Junction;
import org.hibernate.criterion.Restrictions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import edu.uiowa.icts.bluebutton.domain.ClinicalDocument;
import edu.uiowa.icts.bluebutton.domain.Person;
import edu.uiowa.icts.spring.GenericDaoListOptions;
import edu.uiowa.icts.sql.Alias;
import edu.uiowa.icts.util.DataTableHeader;
import edu.uiowa.icts.util.SortColumn;

/**
 * Generated by Protogen 
 * @since 07/31/2014 09:37:03 CDT
 */
@Controller
@RequestMapping("/clinicaldocument/*")
public class ClinicalDocumentController extends AbstractBluebuttonController {

    private static final Log log = LogFactory.getLog(ClinicalDocumentController.class);

    @RequestMapping(value = "list_alt.html", method = RequestMethod.GET)
    public String listNoScript(Model model) {
        model.addAttribute("clinicalDocumentList", bluebuttonDaoService.getClinicalDocumentService().list());
        return "/bluebutton/clinicaldocument/list_alt";
    }

    @RequestMapping(value = { "list.html", "", "/" }, method = RequestMethod.GET)
    public String list() {
        return "/bluebutton/clinicaldocument/list";
    }

    @ResponseBody
    @RequestMapping(value = "datatable", produces = "application/json")
    public String datatable(HttpServletRequest request,
            @RequestParam(value = "personId", required = false) Integer personId,
            @RequestParam(value = "length", required = false) Integer limit,
            @RequestParam(value = "start", required = false) Integer start,
            @RequestParam(value = "draw", required = false) String draw,
            @RequestParam(value = "search[regex]", required = false, defaultValue = "false") Boolean searchRegularExpression,
            @RequestParam(value = "search[value]", required = false) String search,
            @RequestParam(value = "columnCount", required = false, defaultValue = "0") Integer columnCount,
            @RequestParam(value = "individualSearch", required = false, defaultValue = "false") Boolean individualSearch,
            @RequestParam(value = "display", required = false, defaultValue = "list") String display) {

        List<DataTableHeader> headers = new ArrayList<DataTableHeader>();
        for (int i = 0; i < columnCount; i++) {
            DataTableHeader dth = new DataTableHeader();
            dth.setData(Integer.valueOf(request.getParameter("columns[" + i + "][data]")));
            dth.setName(request.getParameter("columns[" + i + "][name]"));
            dth.setOrderable(Boolean.valueOf(request.getParameter("columns[" + i + "][orderable]")));
            dth.setSearchable(Boolean.valueOf(request.getParameter("columns[" + i + "][searchable]")));
            dth.setSearchValue(request.getParameter("columns[" + i + "][search][value]"));
            dth.setSearchRegex(Boolean.valueOf(request.getParameter("columns[" + i + "][search][regex]")));
            headers.add(dth);
        }

        ArrayList<SortColumn> sorts = new ArrayList<SortColumn>();

        JSONObject ob = new JSONObject();

        try {

            for (int i = 0; i < columnCount; i++) {
                Integer columnIndex = null;
                String columnIndexString = request.getParameter("order[" + i + "][column]");
                if (columnIndexString != null) {
                    try {
                        columnIndex = Integer.parseInt(columnIndexString);
                    } catch (NumberFormatException e) {
                        continue;
                    }
                    if (columnIndex != null) {
                        if (StringUtils.equalsIgnoreCase("person", headers.get(columnIndex).getName())) {
                            sorts.add(new SortColumn("person.lastName",
                                    request.getParameter("order[" + i + "][dir]")));
                            sorts.add(new SortColumn("person.firstName",
                                    request.getParameter("order[" + i + "][dir]")));
                        } else {
                            sorts.add(new SortColumn(headers.get(columnIndex).getName(),
                                    request.getParameter("order[" + i + "][dir]")));
                        }
                    }
                }
            }

            GenericDaoListOptions options = new GenericDaoListOptions();

            List<Alias> aliases = new ArrayList<Alias>();
            aliases.add(new Alias("person", "person"));
            options.setAliases(aliases);

            Map<String, Object> individualEquals = new HashMap<String, Object>();
            if (personId != null) {
                individualEquals.put("person.personId", personId);
            }
            options.setIndividualEquals(individualEquals);

            if (!individualSearch) {
                ArrayList<String> searchColumns = new ArrayList<String>();
                for (int i = 0; i < columnCount; i++) {
                    if (headers.get(i).getSearchable()) {
                        if (StringUtils.equalsIgnoreCase("person", headers.get(i).getName())) {
                            searchColumns.add("person.lastName");
                            searchColumns.add("person.firstName");
                        } else {
                            searchColumns.add(headers.get(i).getName());
                        }
                    }
                }
                options.setSearch(search);
                options.setSearchColumns(searchColumns);
            } else {

                List<Junction> disjunctions = new ArrayList<Junction>();

                for (DataTableHeader header : headers) {
                    if (header.getSearchable() && header.getSearchValue() != null
                            && !StringUtils.equals("", header.getSearchValue().trim())) {
                        for (String splitColumnValue : StringUtils.split(header.getSearchValue().trim(), ' ')) {
                            Disjunction disjunction = Restrictions.disjunction();
                            if (StringUtils.equalsIgnoreCase("person", header.getName())) {
                                disjunction
                                        .add(Restrictions.ilike("person.lastName", "%" + splitColumnValue + "%"));
                                disjunction
                                        .add(Restrictions.ilike("person.firstName", "%" + splitColumnValue + "%"));
                            } else {
                                disjunction.add(Restrictions.ilike(header.getName(), "%" + splitColumnValue + "%"));
                            }
                            disjunctions.add(disjunction);
                        }
                    }
                }
                options.setJunctions(disjunctions);
            }

            Integer count = bluebuttonDaoService.getClinicalDocumentService().count(options);

            options.setLimit(limit);
            options.setStart(start);
            options.setSorts(sorts);

            List<ClinicalDocument> clinicalDocumentList = bluebuttonDaoService.getClinicalDocumentService()
                    .list(options);

            ob.put("draw", draw);
            ob.put("recordsFiltered", count);
            ob.put("recordsTotal", count);
            JSONArray jsonArray = new JSONArray();
            for (ClinicalDocument clinicalDocument : clinicalDocumentList) {
                JSONArray tableRow = new JSONArray();
                for (DataTableHeader header : headers) {
                    String headerName = header.getName();
                    if (StringUtils.equals("clinicalDocumentId", headerName)) {
                        tableRow.put(clinicalDocument.getClinicalDocumentId());
                    } else if (StringUtils.equals("document", headerName)) {
                        tableRow.put(clinicalDocument.getDocument());
                    } else if (StringUtils.equals("name", headerName)) {
                        tableRow.put(clinicalDocument.getName());
                    } else if (StringUtils.equals("source", headerName)) {
                        tableRow.put(clinicalDocument.getSource());
                    } else if (StringUtils.equals("description", headerName)) {
                        tableRow.put(clinicalDocument.getDescription());
                    } else if (StringUtils.equals("dateUploaded", headerName)) {
                        tableRow.put(clinicalDocument.getDateUploaded());
                    } else if (StringUtils.equals("jsonParserVersion", headerName)) {
                        tableRow.put(clinicalDocument.getJsonParserVersion());
                    } else if (StringUtils.equals("person", headerName)) {
                        String toPut = "";
                        if (clinicalDocument.getPerson() != null) {
                            toPut = clinicalDocument.getPerson().getLastName() + ", "
                                    + clinicalDocument.getPerson().getFirstName();
                        }
                        tableRow.put(toPut);
                    } else if (StringUtils.equals("urls", headerName)) {
                        String urls = "";
                        if (StringUtils.equals("list", display)) {
                            urls += "<a href=\"show?" + "clinicalDocumentId="
                                    + clinicalDocument.getClinicalDocumentId()
                                    + "\"><span class=\"glyphicon glyphicon-eye-open\"></a> ";
                            urls += "<a href=\"edit?" + "clinicalDocumentId="
                                    + clinicalDocument.getClinicalDocumentId()
                                    + "\"><span class=\"glyphicon glyphicon-pencil\"></a> ";
                            urls += "<a href=\"delete?" + "clinicalDocumentId="
                                    + clinicalDocument.getClinicalDocumentId()
                                    + "\"><span class=\"glyphicon glyphicon-trash\"></a>";
                        } else if (StringUtils.equals("person", display)) {
                            urls += "<a href=\"" + request.getContextPath()
                                    + "/clinicaldocument/show.html?clinicalDocumentId="
                                    + clinicalDocument.getClinicalDocumentId() + "\">[view]</a>";
                        } else {

                        }
                        tableRow.put(urls);
                    } else {
                        tableRow.put("[error: column " + headerName + " not supported]");
                    }
                }
                jsonArray.put(tableRow);
            }
            ob.put("data", jsonArray);

        } catch (Exception e) {
            log.error("error builing datatable json object for ClinicalDocument", e);
            try {
                String stackTrace = e.getMessage() + String.valueOf('\n');
                for (StackTraceElement ste : e.getStackTrace()) {
                    stackTrace += ste.toString() + String.valueOf('\n');
                }
                ob = new JSONObject();
                ob.put("draw", draw);
                ob.put("recordsFiltered", 0);
                ob.put("recordsTotal", 0);
                ob.put("error", stackTrace);
            } catch (JSONException je) {
                log.error("error building json error object for ClinicalDocument", je);
            }
        }

        return ob.toString();
    }

    @RequestMapping(value = "add.html", method = RequestMethod.GET)
    public ModelAndView add() {
        ModelMap model = new ModelMap();
        ClinicalDocument clinicalDocument = new ClinicalDocument();
        model.addAttribute("clinicalDocument", clinicalDocument);
        model.addAttribute("personList", bluebuttonDaoService.getPersonService().list());
        return new ModelAndView("/bluebutton/clinicaldocument/edit", model);
    }

    @RequestMapping(value = "edit.html", method = RequestMethod.GET)
    public String edit(@RequestParam("clinicalDocumentId") Integer clinicalDocumentId, Model model) {
        ClinicalDocument clinicalDocument = bluebuttonDaoService.getClinicalDocumentService()
                .findById(clinicalDocumentId);
        if (clinicalDocument == null) {
            return "/bluebutton/clinicaldocuments/list";
        } else {
            model.addAttribute("clinicalDocument", clinicalDocument);
            return "/bluebutton/clinicaldocument/confirmSource";
        }
    }

    @RequestMapping(value = "{fileName}/file", method = RequestMethod.GET)
    public String showByFileName(@PathVariable String fileName, Model model) {
        ClinicalDocument clinicalDocument = bluebuttonDaoService.getClinicalDocumentService().findByProperty("name",
                fileName);
        if (clinicalDocument == null) {
            return "/bluebutton/clinicaldocument/list";
        } else {
            return "redirect:/person/show?personId=".concat(clinicalDocument.getPerson().getPersonId().toString());
        }
    }

    @RequestMapping(value = "show", method = RequestMethod.GET)
    public String show(@RequestParam("clinicalDocumentId") Integer clinicalDocumentId, Model model) {
        ClinicalDocument clinicalDocument = bluebuttonDaoService.getClinicalDocumentService()
                .findById(clinicalDocumentId);
        if (clinicalDocument == null) {
            return "/bluebutton/clinicaldocument/list";
        } else {
            return "redirect:/person/show?personId=".concat(clinicalDocument.getPerson().getPersonId().toString());
        }
    }

    @RequestMapping(value = "save.html", method = RequestMethod.POST)
    public String save(@RequestParam("person.personId") Integer person_personId,
            @Valid @ModelAttribute("clinicalDocument") ClinicalDocument clinicalDocument, BindingResult result, // must immediately follow bound object
            @RequestParam("file") MultipartFile document, Model model) throws IOException {
        if (document.isEmpty()) {
            result.addError(new FieldError("clinicalDocument", "document", "may not be empty"));
        }
        if (result.hasErrors()) {
            model.addAttribute("personList", bluebuttonDaoService.getPersonService().list());
            return "/bluebutton/clinicaldocument/edit";
        } else {
            clinicalDocument.setPerson(bluebuttonDaoService.getPersonService().findById(person_personId));
            clinicalDocument.setDocument(document.getBytes());
            clinicalDocument.setName(document.getOriginalFilename());
            clinicalDocument.setDateUploaded(new Date());
            bluebuttonDaoService.getClinicalDocumentService().saveOrUpdate(clinicalDocument);
            return "redirect:/clinicaldocument/confirm?clinicalDocumentId="
                    + clinicalDocument.getClinicalDocumentId();
        }
    }

    @RequestMapping(value = "confirm", method = RequestMethod.GET)
    public String confim(@RequestParam("clinicalDocumentId") Integer clinicalDocumentId, Model model) {
        ClinicalDocument clinicalDocument = bluebuttonDaoService.getClinicalDocumentService()
                .findById(clinicalDocumentId);
        if (clinicalDocument == null) {
            return "redirect:/clinicaldocument/";
        } else {
            model.addAttribute("clinicalDocument", clinicalDocument);
            return "/bluebutton/clinicaldocument/confirmSource";
        }
    }

    @RequestMapping(value = "confirm", method = RequestMethod.POST)
    public String confirmSave(@ModelAttribute("clinicalDocument") ClinicalDocument clinicalDocument, Model model,
            BindingResult result) {
        ClinicalDocument cd = this.bluebuttonDaoService.getClinicalDocumentService()
                .findById(clinicalDocument.getClinicalDocumentId());
        if (clinicalDocument.getSource() == null || clinicalDocument.getSource().trim().length() < 1) {
            result.addError(new FieldError("clinicalDocument", "source", "May not be empty"));
        }
        if (result.hasErrors()) {
            clinicalDocument.setDocument(cd.getDocument());
            model.addAttribute("clinicalDocument", clinicalDocument);
            return "/bluebutton/clinicaldocument/confirmSource";
        } else {
            cd.setParsedJson(clinicalDocument.getParsedJson());
            cd.setSource(clinicalDocument.getSource().trim());
            cd.setJsonParserVersion("1.0.0");
            bluebuttonDaoService.getClinicalDocumentService().update(cd);
            return "redirect:/person/show?personId=".concat(cd.getPerson().getPersonId().toString());
        }
    }

    @RequestMapping(value = "delete.html", method = RequestMethod.GET)
    public String confirmDelete(@RequestParam("clinicalDocumentId") Integer clinicalDocumentId, Model model) {
        model.addAttribute("clinicalDocument",
                bluebuttonDaoService.getClinicalDocumentService().findById(clinicalDocumentId));
        return "/bluebutton/clinicaldocument/delete";
    }

    @RequestMapping(value = "delete.html", method = RequestMethod.POST)
    public String doDelete(@RequestParam(value = "submit") String submitButtonValue,
            @RequestParam("clinicalDocumentId") Integer clinicalDocumentId) {
        if (StringUtils.equalsIgnoreCase(submitButtonValue, "yes")) {
            ClinicalDocument clinicalDocument = bluebuttonDaoService.getClinicalDocumentService()
                    .findById(clinicalDocumentId);
            bluebuttonDaoService.getClinicalDocumentService().delete(clinicalDocument);
        }
        return "redirect:/clinicaldocument/list.html";
    }
}