Example usage for java.lang NullPointerException getStackTrace

List of usage examples for java.lang NullPointerException getStackTrace

Introduction

In this page you can find the example usage for java.lang NullPointerException getStackTrace.

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

Provides programmatic access to the stack trace information printed by #printStackTrace() .

Usage

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.ClassgroupRetryController.java

public void doPost(HttpServletRequest req, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(req, response, SimplePermission.USE_MISCELLANEOUS_ADMIN_PAGES.ACTION)) {
        return;/*from  w  w w.  j  ava 2  s  .  c o m*/
    }

    VitroRequest request = new VitroRequest(req);

    //create an EditProcessObject for this and put it in the session
    EditProcessObject epo = super.createEpo(request);

    String action = null;
    if (epo.getAction() == null) {
        action = "insert";
        epo.setAction("insert");
    } else {
        action = epo.getAction();
    }

    VClassGroupDao cgDao = ModelAccess.on(getServletContext()).getWebappDaoFactory().getVClassGroupDao();

    epo.setDataAccessObject(cgDao);

    VClassGroup vclassGroupForEditing = null;
    if (!epo.getUseRecycledBean()) {
        if (request.getParameter("uri") != null) {
            try {
                vclassGroupForEditing = (VClassGroup) cgDao.getGroupByURI(request.getParameter("uri"));
                action = "update";
                epo.setAction("update");
            } catch (NullPointerException e) {
                log.error("Need to implement 'record not found' error message.");
            }
            if (vclassGroupForEditing == null) {
                //UTF-8 expected due to URIEncoding on Connector in server.xml
                String uriToFind = new String(request.getParameter("uri"));
                vclassGroupForEditing = (VClassGroup) cgDao.getGroupByURI(uriToFind);
            }
        } else {
            vclassGroupForEditing = new VClassGroup();
        }
        epo.setOriginalBean(vclassGroupForEditing);
    } else {
        vclassGroupForEditing = (VClassGroup) epo.getNewBean();
    }

    //validators
    List<Validator> validatorList = new ArrayList<Validator>();
    validatorList.add(new RequiredFieldValidator());
    epo.getValidatorMap().put("PublicName", validatorList);

    //make a postinsert pageforwarder that will send us to a new class's fetch screen
    epo.setPostInsertPageForwarder(new VclassGroupInsertPageForwarder());
    //make a postdelete pageforwarder that will send us to the list of classes
    epo.setPostDeletePageForwarder(new UrlForwarder("listGroups"));

    //set the getMethod so we can retrieve a new bean after we've inserted it
    try {
        Class[] args = new Class[1];
        args[0] = String.class;
        epo.setGetMethod(cgDao.getClass().getDeclaredMethod("getGroupByURI", args));
    } catch (NoSuchMethodException e) {
        log.error(this.getClass().getName() + " could not find the getGroupByURI method");
    }

    FormObject foo = new FormObject();
    foo.setErrorMap(epo.getErrMsgMap());
    epo.setFormObject(foo);

    FormUtils.populateFormFromBean(vclassGroupForEditing, action, foo, epo.getBadValueMap());

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("formJsp", "/templates/edit/specific/classgroup_retry.jsp");
    request.setAttribute("scripts", "/templates/edit/formBasic.js");
    request.setAttribute("title", "Classgroup Editing Form");
    request.setAttribute("_action", action);
    request.setAttribute("unqualifiedClassName", "VClassGroup");
    setRequestAttributes(request, epo);

    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("VclassGroupRetryController could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.OntologyRetryController.java

public void doPost(HttpServletRequest req, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(req, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) {
        return;/*from   w  w  w  .  j a  v a2s.c  om*/
    }

    VitroRequest request = new VitroRequest(req);

    //create an EditProcessObject for this and put it in the session
    EditProcessObject epo = super.createEpo(request);

    /*for testing*/
    Ontology testMask = new Ontology();
    epo.setBeanClass(Ontology.class);
    epo.setBeanMask(testMask);

    String action = null;
    if (epo.getAction() == null) {
        action = "insert";
        epo.setAction("insert");
    } else {
        action = epo.getAction();
    }

    OntologyDao oDao = request.getUnfilteredWebappDaoFactory().getOntologyDao();
    epo.setDataAccessObject(oDao);

    Ontology ontologyForEditing = null;
    if (!epo.getUseRecycledBean()) {
        if (request.getParameter("uri") != null) {
            try {
                ontologyForEditing = oDao.getOntologyByURI(request.getParameter("uri"));
                action = "update";
            } catch (NullPointerException e) {
                log.error("No ontology record found for the namespace " + request.getParameter("uri"));
            }
        } else {
            ontologyForEditing = new Ontology();
        }
        epo.setOriginalBean(ontologyForEditing);
    } else {
        ontologyForEditing = (Ontology) epo.getNewBean();
    }

    //validators
    List<Validator> validatorList = new ArrayList<Validator>();
    validatorList.add(new RequiredFieldValidator());
    validatorList.add(new UrlValidator());
    epo.getValidatorMap().put("URI", validatorList);

    //make a simple mask for the class's id
    Object[] simpleMaskPair = new Object[2];
    simpleMaskPair[0] = "Id";
    simpleMaskPair[1] = Integer.valueOf(ontologyForEditing.getId());
    epo.getSimpleMask().add(simpleMaskPair);

    //set up any listeners

    //make a postinsert pageforwarder that will send us to a new ontology's edit screen
    epo.setPostInsertPageForwarder(new OntologyInsertPageForwarder());
    //make a postdelete pageforwarder that will send us to the list of ontologies
    epo.setPostDeletePageForwarder(new UrlForwarder("listOntologies"));

    //set the getMethod so we can retrieve a new bean after we've inserted it
    try {
        Class[] args = new Class[1];
        args[0] = String.class;
        epo.setGetMethod(oDao.getClass().getDeclaredMethod("getOntologyByURI", args));
    } catch (NoSuchMethodException e) {
        log.error("OntologyRetryController could not find the getOntologyByURI method in the DAO");
    }

    FormObject foo = new FormObject();

    foo.setErrorMap(epo.getErrMsgMap());

    epo.setFormObject(foo);

    FormUtils.populateFormFromBean(ontologyForEditing, action, foo, epo.getBadValueMap());

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("formJsp", "/templates/edit/specific/ontology_retry.jsp");
    request.setAttribute("scripts", "/templates/edit/formBasic.js");
    request.setAttribute("title", "Ontology Editing Form");
    request.setAttribute("_action", action);
    request.setAttribute("unqualifiedClassName", "Ontology");
    setRequestAttributes(request, epo);

    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("OntologyRetryContro" + "ller could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.PropertyGroupRetryController.java

public void doPost(HttpServletRequest req, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(req, response, SimplePermission.USE_MISCELLANEOUS_ADMIN_PAGES.ACTION)) {
        return;//from   w  ww. ja  v  a 2s  .c  om
    }

    VitroRequest request = new VitroRequest(req);

    //create an EditProcessObject for this and put it in the session
    EditProcessObject epo = super.createEpo(request);

    String action = null;
    if (epo.getAction() == null) {
        action = "insert";
        epo.setAction("insert");
    } else {
        action = epo.getAction();
    }

    PropertyGroupDao pgDao = ModelAccess.on(getServletContext()).getWebappDaoFactory().getPropertyGroupDao();

    epo.setDataAccessObject(pgDao);

    PropertyGroup propertyGroupForEditing = null;
    if (!epo.getUseRecycledBean()) {
        if (request.getParameter("uri") != null) {
            try {
                propertyGroupForEditing = (PropertyGroup) pgDao.getGroupByURI(request.getParameter("uri"));
                action = "update";
                epo.setAction("update");
            } catch (NullPointerException e) {
                log.error("Need to implement 'record not found' error message.");
            }
            if (propertyGroupForEditing == null) {
                // UTF-8 expected due to URIEncoding on Connector element in server.xml
                String uriToFind = new String(request.getParameter("uri"));
                propertyGroupForEditing = (PropertyGroup) pgDao.getGroupByURI(uriToFind);
            }
        } else {
            propertyGroupForEditing = new PropertyGroup();
        }
        epo.setOriginalBean(propertyGroupForEditing);
    } else {
        propertyGroupForEditing = (PropertyGroup) epo.getNewBean();
    }

    //validators
    List<Validator> validatorList = new ArrayList<Validator>();
    validatorList.add(new RequiredFieldValidator());
    epo.getValidatorMap().put("Name", validatorList);

    //make a postinsert pageforwarder that will send us to a new class's fetch screen
    epo.setPostInsertPageForwarder(new PropertyGroupInsertPageForwarder());
    //make a postdelete pageforwarder that will send us to the list of classes
    epo.setPostDeletePageForwarder(new UrlForwarder("listPropertyGroups"));

    //set the getMethod so we can retrieve a new bean after we've inserted it
    try {
        Class[] args = new Class[1];
        args[0] = String.class;
        epo.setGetMethod(pgDao.getClass().getDeclaredMethod("getGroupByURI", args));
    } catch (NoSuchMethodException e) {
        log.error(this.getClass().getName() + " could not find the getGroupByURI method");
    }

    FormObject foo = new FormObject();
    foo.setErrorMap(epo.getErrMsgMap());
    epo.setFormObject(foo);

    FormUtils.populateFormFromBean(propertyGroupForEditing, action, foo, epo.getBadValueMap());

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("formJsp", "/templates/edit/specific/propertyGroup_retry.jsp");
    request.setAttribute("scripts", "/templates/edit/formBasic.js");
    request.setAttribute("title", "Property Group Editing Form");
    request.setAttribute("_action", action);
    request.setAttribute("unqualifiedClassName", "PropertyGroup");
    setRequestAttributes(request, epo);

    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("PropertyGroupRetryController could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

From source file:net.cbtltd.rest.interhome.A_Handler.java

/**
 * Read prices.//from ww w  .j  a v a 2 s .  c  o m
 *
 * @param version the version
 * @param salesoffice the salesoffice
 * @param currency the currency
 * @param duration the duration
 */
private synchronized void readPrices(Date version, String salesoffice, Currency.Code currency, int duration) {
    String altparty = getAltpartyid();
    String message = "Interhome readPrices Weekly " + altparty;
    LOG.debug(message);
    String fn = null;
    final SqlSession sqlSession = RazorServer.openSession();
    try {
        JAXBContext jc = JAXBContext.newInstance("net.cbtltd.rest.interhome.price");
        Unmarshaller um = jc.createUnmarshaller();

        fn = "price_" + salesoffice + "_" + currency.name().toLowerCase()
                + (duration < 14 ? "" : "_" + String.valueOf(duration)) + ".xml";
        Prices prices = (Prices) um.unmarshal(ftp(fn));

        if (prices != null && prices.getPrice() != null) {
            int count = prices.getPrice().size();
            LOG.debug("Total prices for " + duration + " days: " + count);
        } else {
            LOG.debug("Error, no price file for " + duration + " days");
            return;
        }

        int i = 0;
        for (Price weekprice : prices.getPrice()) {
            String altid = weekprice.getCode();
            //            if (!altid.equals("CH3920.126.1") || !"CH3920.126.1".equalsIgnoreCase(altid)) continue;
            String productid = getProductId(altid);

            if (productid == null) {
                Product product = sqlSession.getMapper(ProductMapper.class)
                        .altread(new NameId(altparty, altid));
                if (product == null) {
                    LOG.error(Error.product_id.getMessage() + " " + weekprice.getCode());
                    continue;
                }
                PRODUCTS.put(altid, product.getId());
                productid = getProductId(altid);
            }

            //            if (!productid.equals("27077") || !String.valueOf(27077).equalsIgnoreCase(productid)) continue;

            Date fromdate = weekprice.getStartdate().toGregorianCalendar().getTime();
            Date todate = weekprice.getEnddate().toGregorianCalendar().getTime();

            if (weekprice.getServices() != null && weekprice.getServices().getService() != null) {
                net.cbtltd.shared.Price mandatory = new net.cbtltd.shared.Price();
                mandatory.setEntitytype(NameId.Type.Mandatory.name());
                mandatory.setEntityid(productid);
                mandatory.setCurrency(currency.name());
                mandatory.setPartyid(altparty);
                mandatory.setVersion(version);

                for (Service service : weekprice.getServices().getService()) {
                    mandatory.setType("Fees");
                    mandatory.setDate(fromdate);
                    mandatory.setTodate(todate);
                    mandatory.setQuantity(0.0);
                    mandatory.setUnit(Unit.EA);
                    mandatory.setAvailable(1);
                    mandatory.setMinStay(1);
                    net.cbtltd.shared.Price existprice = sqlSession.getMapper(PriceMapper.class)
                            .exists(mandatory);
                    if (existprice == null) {
                        sqlSession.getMapper(PriceMapper.class).create(mandatory);
                    } else {
                        mandatory = existprice;
                    }

                    mandatory.setState(net.cbtltd.shared.Price.CREATED);
                    mandatory.setName(getServicename(service.getCode()));
                    mandatory.setMinimum(0.0);
                    mandatory.setValue(
                            service.getServiceprice() == null ? 0.0 : service.getServiceprice().doubleValue());
                    mandatory.setRule("Manual");
                    sqlSession.getMapper(PriceMapper.class).update(mandatory);
                }
                sqlSession.getMapper(PriceMapper.class).cancelversion(mandatory);
            }

            //            Adjustment adjustment = setAdjustment(sqlSession, productid, 7, 7, currency.name(), fromdate, todate, weekprice, "1111111", "week", version);

            Adjustment action = new Adjustment();
            action.setCurrency(currency.name());
            action.setState(Adjustment.Created);
            action.setPartyID(altparty);
            action.setProductID(productid);
            action.setFromDate(fromdate);
            action.setToDate(todate);
            action.setMaxStay(999);
            action.setMinStay(5);

            Adjustment example = sqlSession.getMapper(AdjustmentMapper.class).readbyexample(action);
            if (example == null)
                continue;

            Double rentalPrice;
            if (weekprice.getSpecialoffer() != null
                    && weekprice.getSpecialoffer().getSpecialofferprice() != null) {
                rentalPrice = weekprice.getSpecialoffer().getSpecialofferprice().doubleValue();
            } else {
                rentalPrice = weekprice.getRentalprice().doubleValue();
            }

            Double dailyprice = DAILYPRICES.get(example.getID());
            Double fixprice = example.getFixPrice();
            Double extra = ((rentalPrice - fixprice) / duration) - dailyprice;// ( ( weekprice - fixprice ) / 7 ) - rentalprice[per/day]

            action.setMinStay(duration);
            action.setMaxStay(duration);
            action.setState(null);

            net.cbtltd.shared.Adjustment exists = sqlSession.getMapper(AdjustmentMapper.class).exists(action);
            if (exists == null) {
                sqlSession.getMapper(AdjustmentMapper.class).create(action);
            } else {
                action = exists;
            }

            action.setExtra(PaymentHelper.getAmountWithTwoDecimals(extra));
            action.setServicedays(Adjustment.WEEK);
            action.setState(Adjustment.Created);
            action.setFixPrice(fixprice);
            action.setVersion(version);

            sqlSession.getMapper(AdjustmentMapper.class).update(action);
            sqlSession.getMapper(AdjustmentMapper.class).cancelversion(action);

            LOG.debug(i++ + " WeekPrice: " + " " + weekprice.getCode() + " " + productid + " " + salesoffice
                    + " " + action.getExtra() + " " + currency + " " + duration);
        }
        sqlSession.commit();
    } catch (NullPointerException ex) {
        ex.printStackTrace();
        LOG.error("NPE" + ex.getStackTrace());
        sqlSession.rollback();
    } catch (RuntimeException e) {
        e.printStackTrace();
        LOG.error("RuntimeExc " + e.getStackTrace());
        sqlSession.rollback();
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getClass().getName() + ": " + x.getMessage());
    } finally {
        sqlSession.close();
        delete(fn);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.DatapropRetryController.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) {
        return;/*from   w  w  w .  j  a v  a  2s.  com*/
    }

    //create an EditProcessObject for this and put it in the session
    EditProcessObject epo = super.createEpo(request);
    epo.setBeanClass(DataProperty.class);

    VitroRequest vreq = new VitroRequest(request);

    WebappDaoFactory wadf = ModelAccess.on(getServletContext()).getWebappDaoFactory();

    DatatypeDao dDao = wadf.getDatatypeDao();
    DataPropertyDao dpDao = wadf.getDataPropertyDao();
    epo.setDataAccessObject(dpDao);
    OntologyDao ontDao = wadf.getOntologyDao();

    DataProperty objectForEditing = null;
    String action = null;
    if (epo.getAction() == null) {
        action = "insert";
        epo.setAction("insert");
    } else {
        action = epo.getAction();
    }
    if (epo.getUseRecycledBean()) {
        objectForEditing = (DataProperty) epo.getNewBean();
    } else {
        String uri = request.getParameter("uri");
        if (uri != null) {
            try {
                objectForEditing = dpDao.getDataPropertyByURI(uri);
                epo.setOriginalBean(objectForEditing);
                action = "update";
                epo.setAction("update");
            } catch (NullPointerException e) {
                log.error("Need to implement 'record not found' error message.");
            }
        } else {
            action = "insert";
            epo.setAction("insert");
            objectForEditing = new DataProperty();
            epo.setOriginalBean(objectForEditing);
        }
    }

    //put this in the parent class?
    //make a simple mask for the class's id
    Object[] simpleMaskPair = new Object[2];
    simpleMaskPair[0] = "URI";
    simpleMaskPair[1] = objectForEditing.getURI();
    epo.getSimpleMask().add(simpleMaskPair);

    //set any validators

    LinkedList lnList = new LinkedList();
    lnList.add(new XMLNameValidator());
    epo.getValidatorMap().put("LocalName", lnList);

    LinkedList vlist = new LinkedList();
    vlist.add(new IntValidator(0, 99));
    epo.getValidatorMap().put("StatusId", vlist);

    //set the getMethod so we can retrieve a new bean after we've inserted it
    try {
        Class[] args = new Class[1];
        args[0] = String.class;
        epo.setGetMethod(dpDao.getClass().getDeclaredMethod("getDataPropertyByURI", args));
    } catch (NoSuchMethodException e) {
        log.error("DatapropRetryController could not find the getDataPropertyByURI method in the facade");
    }

    //make a postinsert pageforwarder that will send us to a new class's fetch screen
    epo.setPostInsertPageForwarder(new DataPropertyInsertPageForwarder());
    //make a postdelete pageforwarder that will send us to the list of properties
    epo.setPostDeletePageForwarder(new UrlForwarder("listDatatypeProperties"));

    //set up any listeners
    List changeListenerList = new ArrayList();
    changeListenerList.add(new PropertyRestrictionListener());
    epo.setChangeListenerList(changeListenerList);

    FormObject foo = new FormObject();
    foo.setErrorMap(epo.getErrMsgMap()); // retain error messages from previous time through the form

    epo.setFormObject(foo);
    FormUtils.populateFormFromBean(objectForEditing, action, foo);
    //for now, this is also making the value hash - need to separate this out

    HashMap optionMap = new HashMap();
    List namespaceList = FormUtils.makeOptionListFromBeans(ontDao.getAllOntologies(), "URI", "Name",
            ((objectForEditing.getNamespace() == null) ? "" : objectForEditing.getNamespace()), null,
            (objectForEditing.getNamespace() != null));
    namespaceList.add(0, new Option(vreq.getUnfilteredWebappDaoFactory().getDefaultNamespace(), "default"));
    optionMap.put("Namespace", namespaceList);

    List<Option> domainOptionList = FormUtils.makeVClassOptionList(vreq.getUnfilteredWebappDaoFactory(),
            objectForEditing.getDomainClassURI());
    if (objectForEditing.getDomainClassURI() != null) {
        VClass domain = vreq.getWebappDaoFactory().getVClassDao()
                .getVClassByURI(objectForEditing.getDomainClassURI());
        if (domain != null && domain.isAnonymous()) {
            domainOptionList.add(0, new Option(domain.getURI(), domain.getName(), true));
        }
    }
    domainOptionList.add(0, new Option("", "(none specified)"));
    optionMap.put("DomainClassURI", domainOptionList);

    List datatypeOptionList = FormUtils.makeOptionListFromBeans(dDao.getAllDatatypes(), "Uri", "Name",
            objectForEditing.getRangeDatatypeURI(), null);
    datatypeOptionList.add(0, new Option("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral",
            "XML literal (allows XHTML markup)"));
    datatypeOptionList.add(0, new Option(null, "untyped (use if language tags desired)"));
    optionMap.put("RangeDatatypeURI", datatypeOptionList);

    List groupOptList = FormUtils.makeOptionListFromBeans(
            vreq.getUnfilteredWebappDaoFactory().getPropertyGroupDao().getPublicGroups(true), "URI", "Name",
            ((objectForEditing.getGroupURI() == null) ? "" : objectForEditing.getGroupURI()), null,
            (objectForEditing.getGroupURI() != null));
    HashMap<String, Option> hashMap = new HashMap<String, Option>();
    groupOptList = getSortedList(hashMap, groupOptList, vreq);
    groupOptList.add(0, new Option("", "none"));
    optionMap.put("GroupURI", groupOptList);

    optionMap.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getDisplayOptionsList(objectForEditing));
    optionMap.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getUpdateOptionsList(objectForEditing));
    optionMap.put("HiddenFromPublishBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getPublishOptionsList(objectForEditing));

    foo.setOptionLists(optionMap);

    request.setAttribute("functional", objectForEditing.getFunctional());

    //checkboxes are pretty annoying : we don't know if someone *unchecked* a box, so we have to default to false on updates.
    if (objectForEditing.getURI() != null) {
        objectForEditing.setFunctional(false);
    }

    foo.setErrorMap(epo.getErrMsgMap());

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("colspan", "4");
    request.setAttribute("scripts", "/templates/edit/formBasic.js");
    request.setAttribute("formJsp", "/templates/edit/specific/dataprop_retry.jsp");
    request.setAttribute("title", "Data Property Editing Form");
    request.setAttribute("_action", action);
    request.setAttribute("unqualifiedClassName", "DatatypeProperty");
    setRequestAttributes(request, epo);

    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("DatatypeRetryController could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.PropertyRetryController.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(req, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) {
        return;/*w w  w.  j  ava2 s .c o  m*/
    }

    VitroRequest request = new VitroRequest(req);

    //create an EditProcessObject for this and put it in the session
    EditProcessObject epo = super.createEpo(request);

    /*for testing*/
    ObjectProperty testMask = new ObjectProperty();
    epo.setBeanClass(ObjectProperty.class);
    epo.setBeanMask(testMask);

    String action = null;
    if (epo.getAction() == null) {
        action = "insert";
        epo.setAction("insert");
    } else {
        action = epo.getAction();
    }

    ObjectPropertyDao propDao = ModelAccess.on(getServletContext()).getWebappDaoFactory()
            .getObjectPropertyDao();
    epo.setDataAccessObject(propDao);
    OntologyDao ontDao = request.getUnfilteredWebappDaoFactory().getOntologyDao();

    ObjectProperty propertyForEditing = null;
    if (!epo.getUseRecycledBean()) {
        String uri = request.getParameter("uri");
        if (uri != null) {
            try {
                propertyForEditing = propDao.getObjectPropertyByURI(uri);
                action = "update";
                epo.setAction("update");
            } catch (NullPointerException e) {
                log.error("Need to implement 'record not found' error message.");
                throw (e);
            }
        } else {
            propertyForEditing = new ObjectProperty();
            if (request.getParameter("parentId") != null) {
                propertyForEditing.setParentURI(request.getParameter("parentId"));
            }
            if (request.getParameter("domainClassUri") != null) {
                propertyForEditing.setDomainVClassURI(request.getParameter("domainClassUri"));
            }
        }
        epo.setOriginalBean(propertyForEditing);
    } else {
        propertyForEditing = (ObjectProperty) epo.getNewBean();
    }

    //make a simple mask for the class's id
    Object[] simpleMaskPair = new Object[2];
    simpleMaskPair[0] = "Id";
    simpleMaskPair[1] = propertyForEditing.getURI();
    epo.getSimpleMask().add(simpleMaskPair);

    //set any validators
    List<Validator> localNameValidatorList = new ArrayList<>();
    localNameValidatorList.add(new XMLNameValidator());
    List<Validator> localNameInverseValidatorList = new ArrayList<>();
    localNameInverseValidatorList.add(new XMLNameValidator(true));
    epo.getValidatorMap().put("LocalName", localNameValidatorList);
    epo.getValidatorMap().put("LocalNameInverse", localNameInverseValidatorList);
    List<Validator> displayRankValidatorList = new ArrayList<Validator>();
    displayRankValidatorList.add(new IntValidator());
    epo.getValidatorMap().put("DisplayRank", displayRankValidatorList);

    //set up any listeners
    List<ChangeListener> changeListenerList = new ArrayList<>();
    changeListenerList.add(new PropertyRestrictionListener());
    epo.setChangeListenerList(changeListenerList);

    //make a postinsert pageforwarder that will send us to a new class's fetch screen
    epo.setPostInsertPageForwarder(new PropertyInsertPageForwarder());
    //make a postdelete pageforwarder that will send us to the list of properties
    epo.setPostDeletePageForwarder(new UrlForwarder("listPropertyWebapps"));

    //set the getMethod so we can retrieve a new bean after we've inserted it
    try {
        Class<?>[] args = new Class[1];
        args[0] = String.class;
        epo.setGetMethod(propDao.getClass().getDeclaredMethod("getObjectPropertyByURI", args));
    } catch (NoSuchMethodException e) {
        log.error(
                "PropertyRetryController could not find the getPropertyByURI method in the PropertyWebappDao");
    }

    FormObject foo = new FormObject();
    foo.setErrorMap(epo.getErrMsgMap());

    HashMap<String, List<Option>> optionMap = new HashMap<String, List<Option>>();
    try {
        populateOptionMap(optionMap, propertyForEditing, request, ontDao, propDao);
    } catch (Exception e) {
        log.error(e, e);
        throw new RuntimeException(e);
    }

    optionMap.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getDisplayOptionsList(propertyForEditing));
    optionMap.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getUpdateOptionsList(propertyForEditing));
    optionMap.put("HiddenFromPublishBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getPublishOptionsList(propertyForEditing));

    List<Option> groupOptList = FormUtils.makeOptionListFromBeans(
            request.getUnfilteredWebappDaoFactory().getPropertyGroupDao().getPublicGroups(true), "URI", "Name",
            ((propertyForEditing.getGroupURI() == null) ? "" : propertyForEditing.getGroupURI()), null,
            (propertyForEditing.getGroupURI() != null));
    HashMap<String, Option> hashMap = new HashMap<String, Option>();
    groupOptList = getSortedList(hashMap, groupOptList, request);
    groupOptList.add(0, new Option("", "none"));
    optionMap.put("GroupURI", groupOptList);

    foo.setOptionLists(optionMap);

    request.setAttribute("transitive", propertyForEditing.getTransitive());
    request.setAttribute("symmetric", propertyForEditing.getSymmetric());
    request.setAttribute("functional", propertyForEditing.getFunctional());
    request.setAttribute("inverseFunctional", propertyForEditing.getInverseFunctional());
    request.setAttribute("selectFromExisting", propertyForEditing.getSelectFromExisting());
    request.setAttribute("offerCreateNewOption", propertyForEditing.getOfferCreateNewOption());
    request.setAttribute("objectIndividualSortPropertyURI",
            propertyForEditing.getObjectIndividualSortPropertyURI());
    request.setAttribute("domainEntitySortDirection", propertyForEditing.getDomainEntitySortDirection());
    request.setAttribute("collateBySubclass", propertyForEditing.getCollateBySubclass());

    //checkboxes are pretty annoying : we don't know if someone *unchecked* a box, so we have to default to false on updates.
    if (propertyForEditing.getURI() != null) {
        propertyForEditing.setTransitive(false);
        propertyForEditing.setSymmetric(false);
        propertyForEditing.setFunctional(false);
        propertyForEditing.setInverseFunctional(false);
        propertyForEditing.setSelectFromExisting(false);
        propertyForEditing.setOfferCreateNewOption(false);
        //propertyForEditing.setStubObjectRelation(false);
        propertyForEditing.setCollateBySubclass(false);
    }

    epo.setFormObject(foo);

    FormUtils.populateFormFromBean(propertyForEditing, action, foo, epo.getBadValueMap());

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("colspan", "5");
    request.setAttribute("formJsp", "/templates/edit/specific/property_retry.jsp");
    request.setAttribute("scripts", "/templates/edit/formBasic.js");
    request.setAttribute("title", "Property Editing Form");
    request.setAttribute("_action", action);
    setRequestAttributes(request, epo);

    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("PropertyRetryController could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.EntityRetryController.java

public void doPost(HttpServletRequest request, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.DO_BACK_END_EDITING.ACTION)) {
        return;//from  w  w w  .j  av  a2s .  c  o  m
    }

    VitroRequest vreq = new VitroRequest(request);
    String siteAdminUrl = vreq.getContextPath() + Controllers.SITE_ADMIN;

    //create an EditProcessObject for this and put it in the session
    EditProcessObject epo = super.createEpo(request);

    epo.setBeanClass(Individual.class);
    epo.setImplementationClass(IndividualImpl.class);

    String action = null;
    if (epo.getAction() == null) {
        action = "insert";
        epo.setAction("insert");
    } else {
        action = epo.getAction();
    }

    LoginStatusBean loginBean = LoginStatusBean.getBean(request);
    WebappDaoFactory myWebappDaoFactory = getWebappDaoFactory(loginBean.getUserURI());

    IndividualDao ewDao = myWebappDaoFactory.getIndividualDao();
    epo.setDataAccessObject(ewDao);
    VClassDao vcDao = myWebappDaoFactory.getVClassDao();
    VClassGroupDao cgDao = myWebappDaoFactory.getVClassGroupDao();
    DataPropertyDao dpDao = myWebappDaoFactory.getDataPropertyDao();

    Individual individualForEditing = null;
    if (epo.getUseRecycledBean()) {
        individualForEditing = (Individual) epo.getNewBean();
    } else {
        String uri = vreq.getParameter("uri");
        if (uri != null) {
            try {
                individualForEditing = (Individual) ewDao.getIndividualByURI(uri);
                action = "update";
                epo.setAction("update");
            } catch (NullPointerException e) {
                log.error("Need to implement 'record not found' error message.");
            }
        } else {
            individualForEditing = new IndividualImpl();
            if (vreq.getParameter("VClassURI") != null) {
                individualForEditing.setVClassURI(vreq.getParameter("VClassURI"));
            }
        }

        epo.setOriginalBean(individualForEditing);

        //make a simple mask for the entity's id
        Object[] simpleMaskPair = new Object[2];
        simpleMaskPair[0] = "URI";
        simpleMaskPair[1] = individualForEditing.getURI();
        epo.getSimpleMask().add(simpleMaskPair);

    }

    //set any validators

    LinkedList lnList = new LinkedList();
    lnList.add(new RequiredFieldValidator());
    epo.getValidatorMap().put("Name", lnList);

    //make a postinsert pageforwarder that will send us to a new entity's fetch screen
    epo.setPostInsertPageForwarder(new EntityInsertPageForwarder());
    epo.setPostDeletePageForwarder(new UrlForwarder(siteAdminUrl));

    //set the getMethod so we can retrieve a new bean after we've inserted it
    try {
        Class[] args = new Class[1];
        args[0] = String.class;
        epo.setGetMethod(ewDao.getClass().getDeclaredMethod("getIndividualByURI", args));
    } catch (NoSuchMethodException e) {
        log.error("EntityRetryController could not find the entityByURI method in the dao");
    }

    epo.setIdFieldName("URI");
    epo.setIdFieldClass(String.class);

    HashMap hash = new HashMap();

    if (individualForEditing.getVClassURI() == null) {
        // we need to do a special thing here to make an option list with option groups for the classgroups.
        List classGroups = cgDao.getPublicGroupsWithVClasses(true, true, false); // order by displayRank, include uninstantiated classes, don't get the counts of individuals
        Iterator classGroupIt = classGroups.iterator();
        ListOrderedMap optGroupMap = new ListOrderedMap();
        while (classGroupIt.hasNext()) {
            VClassGroup group = (VClassGroup) classGroupIt.next();
            List classes = group.getVitroClassList();
            optGroupMap.put(group.getPublicName(), FormUtils.makeOptionListFromBeans(classes, "URI", "Name",
                    individualForEditing.getVClassURI(), null, false));
        }
        hash.put("VClassURI", optGroupMap);
    } else {
        VClass vClass = null;
        Option opt = null;
        try {
            vClass = vcDao.getVClassByURI(individualForEditing.getVClassURI());
        } catch (Exception e) {
        }
        if (vClass != null) {
            opt = new Option(vClass.getURI(), vClass.getName(), true);
        } else {
            opt = new Option(individualForEditing.getVClassURI(), individualForEditing.getVClassURI(), true);
        }
        List<Option> optList = new LinkedList<Option>();
        optList.add(opt);
        hash.put("VClassURI", optList);
    }

    hash.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getDisplayOptionsList(individualForEditing));
    hash.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getUpdateOptionsList(individualForEditing));
    hash.put("HiddenFromPublishBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getPublishOptionsList(individualForEditing));

    FormObject foo = new FormObject();
    foo.setOptionLists(hash);

    ListOrderedMap dpMap = new ListOrderedMap();

    //make dynamic datatype property fields
    List<VClass> vclasses = individualForEditing.getVClasses(true);
    if (vclasses == null) {
        vclasses = new ArrayList<VClass>();
        if (individualForEditing.getVClassURI() != null) {
            try {
                VClass cls = vreq.getUnfilteredWebappDaoFactory().getVClassDao()
                        .getVClassByURI(individualForEditing.getVClassURI());
                if (cls != null) {
                    vclasses.add(cls);
                }
            } catch (Exception e) {
            }
        }
    }
    List<DataProperty> allApplicableDataprops = new ArrayList<DataProperty>();
    for (VClass cls : vclasses) {
        List<DataProperty> dataprops = dpDao.getDataPropertiesForVClass(cls.getURI());
        for (DataProperty dp : dataprops) {
            boolean notDuplicate = true;
            for (DataProperty existingDp : allApplicableDataprops) {
                if (existingDp.getURI().equals(dp.getURI())) {
                    notDuplicate = false;
                    break;
                }
            }
            if (notDuplicate) {
                allApplicableDataprops.add(dp);
            }
        }
    }
    Collections.sort(allApplicableDataprops);

    if (allApplicableDataprops != null) {
        Iterator<DataProperty> datapropsIt = allApplicableDataprops.iterator();

        while (datapropsIt.hasNext()) {
            DataProperty d = datapropsIt.next();
            if (!dpMap.containsKey(d.getURI())) {
                dpMap.put(d.getURI(), d);
            }

        }

        if (individualForEditing.getDataPropertyList() != null) {
            Iterator<DataProperty> existingDps = individualForEditing.getDataPropertyList().iterator();
            while (existingDps.hasNext()) {
                DataProperty existingDp = existingDps.next();
                // Since the edit form begins with a "name" field, which gets saved as the rdfs:label,
                // do not want to include the label as well. 
                if (!existingDp.getPublicName().equals("label")) {
                    dpMap.put(existingDp.getURI(), existingDp);
                }
            }
        }

        List<DynamicField> dynamicFields = new ArrayList();
        Iterator<String> dpHashIt = dpMap.orderedMapIterator();
        while (dpHashIt.hasNext()) {
            String uri = dpHashIt.next();
            DataProperty dp = (DataProperty) dpMap.get(uri);
            DynamicField dynamo = new DynamicField();
            dynamo.setName(dp.getPublicName());
            dynamo.setTable("DataPropertyStatement");
            dynamo.setVisible(dp.getDisplayLimit());
            dynamo.setDeleteable(true);
            DynamicFieldRow rowTemplate = new DynamicFieldRow();
            Map parameterMap = new HashMap();
            parameterMap.put("DatatypePropertyURI", dp.getURI());
            rowTemplate.setParameterMap(parameterMap);
            dynamo.setRowTemplate(rowTemplate);
            try {
                Iterator<DataPropertyStatement> existingValues = dp.getDataPropertyStatements().iterator();
                while (existingValues.hasNext()) {
                    DataPropertyStatement existingValue = existingValues.next();
                    DynamicFieldRow row = new DynamicFieldRow();
                    //TODO: UGH
                    //row.setId(existingValue.getId());
                    row.setParameterMap(parameterMap);
                    row.setValue(existingValue.getData());
                    if (dynamo.getRowList() == null)
                        dynamo.setRowList(new ArrayList());
                    dynamo.getRowList().add(row);
                }
            } catch (NullPointerException npe) {
                //whatever
            }
            if (dynamo.getRowList() == null)
                dynamo.setRowList(new ArrayList());
            dynamo.getRowList().add(rowTemplate);
            dynamicFields.add(dynamo);
        }
        foo.setDynamicFields(dynamicFields);
    }

    foo.setErrorMap(epo.getErrMsgMap());

    epo.setFormObject(foo);

    // DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    DateFormat minutesOnlyDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    DateFormat dateOnlyFormat = new SimpleDateFormat("yyyy-MM-dd");
    FormUtils.populateFormFromBean(individualForEditing, action, epo, foo, epo.getBadValueMap());

    List cList = new ArrayList();
    cList.add(new IndividualDataPropertyStatementProcessor());
    //cList.add(new SearchReindexer()); // handled for now by SearchReindexingListener on model
    epo.setChangeListenerList(cList);

    epo.getAdditionalDaoMap().put("DataPropertyStatement", myWebappDaoFactory.getDataPropertyStatementDao()); // EntityDatapropProcessor will look for this
    epo.getAdditionalDaoMap().put("DataProperty", myWebappDaoFactory.getDataPropertyDao()); // EntityDatapropProcessor will look for this

    ApplicationBean appBean = vreq.getAppBean();

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("formJsp", "/templates/edit/specific/entity_retry.jsp");
    request.setAttribute("epoKey", epo.getKey());
    request.setAttribute("title", "Individual Editing Form");
    request.setAttribute("css",
            "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + appBean.getThemeDir() + "css/edit.css\"/>");
    request.setAttribute("scripts", "/js/edit/entityRetry.js");
    // NC Commenting this out for now. Going to pass on DWR for moniker and use jQuery instead
    // request.setAttribute("bodyAttr"," onLoad=\"monikerInit()\"");
    request.setAttribute("_action", action);
    request.setAttribute("unqualifiedClassName", "Individual");
    setRequestAttributes(request, epo);
    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("EntityRetryController could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}