List of usage examples for java.lang NullPointerException getMessage
public String getMessage()
From source file:edu.cornell.mannlib.vedit.controller.OperationController.java
public void doPost(HttpServletRequest request, HttpServletResponse response) { String defaultLandingPage = getDefaultLandingPage(request); // get the Edit Process Object which will tell us wh HashMap epoHash = null;/* www . java 2 s . co m*/ EditProcessObject epo = null; try { epoHash = (HashMap) request.getSession().getAttribute("epoHash"); epo = (EditProcessObject) epoHash.get(request.getParameter("_epoKey")); } catch (NullPointerException e) { //session or edit process expired try { response.sendRedirect(defaultLandingPage); } catch (IOException ioe) { log.error(this.getClass().getName() + " IOError on redirect: ", ioe); } return; } if (epo == null) { try { response.sendRedirect(defaultLandingPage); } catch (IOException ioe) { log.error(this.getClass().getName() + " IOError on redirect: ", ioe); } return; } // if we're canceling, we don't need to do anything if (request.getParameter("_cancel") != null) { String referer = epo.getReferer(); if (referer == null) { try { response.sendRedirect(defaultLandingPage); } catch (IOException ioe) { log.error(this.getClass().getName() + " IOError on redirect: ", ioe); } return; } else { try { response.sendRedirect(referer); } catch (IOException ioe) { log.error(this.getClass().getName() + " IOError on redirect: ", ioe); } return; } } // reset - if reset button is of type submit if (request.getParameter("_reset") != null) { try { response.sendRedirect(request.getHeader("Referer")); } catch (IOException ioe) { log.error(this.getClass().getName() + " IOError on redirect: ", ioe); } return; } try { Object newObj = getNewObj(epo); //populate this object from the req. params boolean valid = populateObjectFromRequestParamsAndValidate(epo, newObj, request); //run preprocessors runPreprocessors(epo, newObj); //applySimpleMask(epo, newObj); //put the newObj back in the epo where other things can look at it epo.setNewBean(newObj); //if validation failed, go back to the form controller if (!valid) { epo.setAttribute("globalErrorMsg", "Please correct errors highlighted below."); retry(request, response, epo); return; } String action = getAction(request); boolean status = performEdit(epo, newObj, action); if (status == FAILURE) { retry(request, response, epo); return; } /* put request parameters and attributes into epo where the listeners can see */ epo.setRequestParameterMap(request.getParameterMap()); notifyChangeListeners(epo, action); /* send the user somewhere */ if (action.equals("insert")) { // Object[] args = new Object[1]; // args[0] = result; // epo.setNewBean(epo.getGetMethod().invoke(facade,args)); PageForwarder pipf = epo.getPostInsertPageForwarder(); if (pipf != null) { pipf.doForward(request, response, epo); return; } } else if (action.equals("update")) { PageForwarder pupf = epo.getPostUpdatePageForwarder(); if (pupf != null) { pupf.doForward(request, response, epo); return; } } else if (action.equals("delete")) { PageForwarder pdpf = epo.getPostDeletePageForwarder(); if (pdpf != null) { pdpf.doForward(request, response, epo); return; } } //if no page forwarder was set, just go back to referring page: String referer = epo.getReferer(); if (referer == null) response.sendRedirect(defaultLandingPage); else response.sendRedirect(referer); } catch (Exception e) { log.error("Error performing edit", e); String errMsg = (e.getMessage() != null) ? e.getMessage() : "Error performing edit"; epo.setAttribute("globalErrorMsg", errMsg); try { retry(request, response, epo); return; } catch (IOException ioe) { log.error(this.getClass().getName() + " IOError on redirect: ", ioe); } } }
From source file:org.finra.herd.service.BusinessObjectFormatServiceTest.java
@Test public void testUpdateBusinessObjectFormatAttributeDefinitionsMissingOptionalParameters() { List<Attribute> attributes = businessObjectDefinitionServiceTestHelper.getNewAttributes(); BusinessObjectFormat originalBusinessObjectFormat = businessObjectFormatServiceTestHelper .createTestBusinessObjectFormat(attributes); // Passing null as optional parameter List<AttributeDefinition> attributeDefinitions = new ArrayList<>(); attributeDefinitions.add(new AttributeDefinition(AbstractServiceTest.ATTRIBUTE_NAME_1_MIXED_CASE, null)); // Perform an update by changing the attribute definition with an empty list. BusinessObjectFormatAttributeDefinitionsUpdateRequest request = new BusinessObjectFormatAttributeDefinitionsUpdateRequest( attributeDefinitions);/*from ww w.j a v a 2 s. co m*/ try { businessObjectFormatService .updateBusinessObjectFormatAttributeDefinitions(new BusinessObjectFormatKey(NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, INITIAL_FORMAT_VERSION), request); fail("Should throw an IllegalArgumentException."); } catch (NullPointerException ex) { assertEquals(null, ex.getMessage()); } }
From source file:de.innovationgate.wgpublisher.lucene.LuceneManager.java
public WGResultSet search(WGDatabase db, List<String> fields, String phrase, Map parameters, WGA wga) throws WGQueryException { if (wga == null) { wga = WGA.get(_core);//from w w w . j a va 2 s . c o m } // set max clause count for boolean queries BooleanQuery.setMaxClauseCount(_booleanQueryMaxClauseCount); if (this.isRebuildingIndex()) { throw new WGQueryException(phrase, "Lucene search temporary disabled. Rebuilding lucene index ..."); } // Registering problem in that case but not cancelling the query, as this is old, expected behaviour. The query will just return no results. if (!_core.getLuceneManager().indexIsEnabled(db.getDbReference())) { _core.getProblemRegistry().addProblem( Problem.create(new TMLContext.WebTMLOccasion(), new DatabaseScope(db.getDbReference()), "webtmlProblem.luceneIndexExpected", ProblemSeverity.LOW)); } if (phrase == null || phrase.trim().equals("")) { return null; } try { BooleanQuery wholeQuery = new BooleanQuery(); int max = WGACore.DEFAULT_QUERY_MAXRESULTS; Integer maxResults = (Integer) parameters.get(WGDatabase.QUERYOPTION_MAXRESULTS); if (maxResults != null) { if (maxResults == 0 || maxResults == -1) { max = Integer.MAX_VALUE; } else { max = maxResults; } } // handle dboption EXCLUDEDOCUMENT WGContent excludeContent = (WGContent) parameters.get(WGDatabase.QUERYOPTION_EXCLUDEDOCUMENT); if (excludeContent != null) { String uniqueKey = buildUniqueIndexKey(excludeContent.getDatabase().getDbReference(), excludeContent.getDocumentKey()); wholeQuery.add(new TermQuery(new Term(INDEXFIELD_UNIQUEKEY, uniqueKey)), BooleanClause.Occur.MUST_NOT); wholeQuery.add(new TermQuery(new Term(INDEXFIELD_PARENTKEY, uniqueKey)), BooleanClause.Occur.MUST_NOT); } // list of dbs to search in String searchScope = (String) parameters.get(LuceneManager.QUERYOPTION_SEARCHSCOPE); List searchDBKeys = new ArrayList(); if (searchScope.equals(LuceneManager.SEARCHSCOPE_DB)) { searchDBKeys.add(db.getDbReference()); } if (searchScope.equals(LuceneManager.SEARCHSCOPE_DOMAIN)) { Iterator<WGDatabase> dbs = _core .getDatabasesForDomain((String) db.getAttribute(WGACore.DBATTRIB_DOMAIN)).iterator(); while (dbs.hasNext()) { WGDatabase currentDB = dbs.next(); if (wga.openDatabase(currentDB)) { searchDBKeys.add(currentDB.getDbReference()); } } } if (searchScope.equals(LuceneManager.SEARCHSCOPE_WGA)) { Iterator dbs = _core.getContentdbs().values().iterator(); while (dbs.hasNext()) { WGDatabase currentDB = (WGDatabase) dbs.next(); if (wga.openDatabase(currentDB)) { searchDBKeys.add(currentDB.getDbReference()); } } } if (searchScope.equals(LuceneManager.SEARCHSCOPE_DB_LIST)) { String dbListCSV = (String) parameters.get(QUERYOPTION_SEARCHDBKEYS); if (dbListCSV == null || dbListCSV.trim().equals("")) { throw new WGQueryException(phrase, "Search scope is 'dblist' but no db keys given."); } else { Iterator dbkeys = WGUtils.deserializeCollection(dbListCSV, ",").iterator(); while (dbkeys.hasNext()) { String dbkey = (String) dbkeys.next(); WGDatabase currentDB = wga.db(dbkey); if (currentDB.isSessionOpen()) { searchDBKeys.add(dbkey.trim().toLowerCase()); } } } } // Handle language selection; List<WGLanguage> languagesPriorityList = null; boolean filterLanguages = false; if (parameters.containsKey(WGDatabase.QUERYOPTION_LANGUAGES)) { List<WGLanguage> langs = (List<WGLanguage>) parameters.get(WGDatabase.QUERYOPTION_LANGUAGES); if (langs.size() > 1) { BooleanQuery langQuery = new BooleanQuery(); for (WGLanguage lang : langs) { langQuery.add(new TermQuery(new Term(WGContent.META_LANGUAGE, lang.getName())), BooleanClause.Occur.SHOULD); } wholeQuery.add(langQuery, BooleanClause.Occur.MUST); languagesPriorityList = langs; filterLanguages = true; } else if (langs.size() == 1) { wholeQuery.add(new TermQuery(new Term(WGContent.META_LANGUAGE, langs.get(0).getName())), BooleanClause.Occur.MUST); languagesPriorityList = Collections.singletonList(langs.get(0)); } } else if (parameters.containsKey(WGDatabase.QUERYOPTION_ONLYLANGUAGE)) { String language = (String) parameters.get(WGDatabase.QUERYOPTION_ONLYLANGUAGE); wholeQuery.add(new TermQuery(new Term(WGContent.META_LANGUAGE, language)), BooleanClause.Occur.MUST); languagesPriorityList = Collections.singletonList(db.getLanguage(language)); } if (languagesPriorityList == null) { languagesPriorityList = getLanguagesForSearchDBKeys(searchDBKeys); ; } // Handle visibility selection if (!parameters.containsKey(WGDatabase.QUERYOPTION_ENHANCE) || parameters.get(WGDatabase.QUERYOPTION_ENHANCE).equals(new Boolean(true))) { wholeQuery.add(new TermQuery(new Term(WGContent.META_VISIBLE, "true")), BooleanClause.Occur.MUST); String role = (String) parameters.get(WGDatabase.QUERYOPTION_ROLE); if (role != null) { if (!role.equalsIgnoreCase(WGContent.DISPLAYTYPE_NONE)) { wholeQuery.add(new TermQuery(new Term("HIDDENIN" + role.toUpperCase(), "false")), BooleanClause.Occur.MUST); } } } if (parameters.containsKey(WGDatabase.QUERYOPTION_ONLYRELEASED)) { wholeQuery.add(new TermQuery(new Term(WGContent.META_STATUS, WGContent.STATUS_RELEASE)), BooleanClause.Occur.MUST); } // build dbQuery (OR combination of all searchDbs indexed by lucene) BooleanQuery dbQuery = new BooleanQuery(); Iterator itSearchDBKeys = searchDBKeys.iterator(); while (itSearchDBKeys.hasNext()) { String currentDBKey = (String) itSearchDBKeys.next(); if (_indexedDbs.containsKey(currentDBKey)) { dbQuery.add(new TermQuery(new Term(INDEXFIELD_DBKEY, currentDBKey)), BooleanClause.Occur.SHOULD); } } wholeQuery.add(dbQuery, BooleanClause.Occur.MUST); // Add parsed search phrase. // Search in allcontent for each language using the configured analyzer // if no analyzer is configured for a language search at least with one // default analyzer boolean searchWithDefaultAnalyzer = false; //if no languages found search at least with DefaultAnalyzer if (languagesPriorityList.size() <= 0) { searchWithDefaultAnalyzer = true; } // parse native options Sort sort = null; String sortFieldName = ""; Operator defaultOperator = QueryParser.AND_OPERATOR; String nativeOptionsStr = (String) parameters.get(WGDatabase.QUERYOPTION_NATIVEOPTIONS); boolean includeVirtualContent = false; String doctype = DOCTYPE_CONTENT; if (nativeOptionsStr != null) { Iterator nativeOptions = WGUtils.deserializeCollection(nativeOptionsStr, ",", true).iterator(); while (nativeOptions.hasNext()) { String option = (String) nativeOptions.next(); if (option.startsWith("sort:")) { sortFieldName = option.substring(5).trim(); boolean reverse = false; if (sortFieldName.toLowerCase().endsWith("(asc)")) { sortFieldName = sortFieldName.substring(0, sortFieldName.length() - 5).trim(); } else if (sortFieldName.toLowerCase().endsWith("(desc)")) { sortFieldName = sortFieldName.substring(0, sortFieldName.length() - 6).trim(); reverse = true; } if (sortFieldName.length() > 0) { char first = sortFieldName.charAt(0); if (first >= 'A' && first <= 'Z') { // meta sort sortFieldName = sortFieldName.toUpperCase(); } else { // item sort sortFieldName = sortFieldName.toLowerCase(); } } // sort order currently only german sort = new Sort(new SortField(SORTITEM_PREFIX + sortFieldName, Locale.GERMANY, reverse)); } else if (option.equalsIgnoreCase(NATIVE_QUERYOPTION_INCLUDEVIRTUALCONTENT)) { includeVirtualContent = true; } else if (option.startsWith("doctype:")) { doctype = option.substring("doctype:".length()).trim(); } else if (option.startsWith("operator:")) { String op = option.substring("operator:".length()).trim(); if (op.equalsIgnoreCase("or")) defaultOperator = QueryParser.OR_OPERATOR; } } } if (!includeVirtualContent) { wholeQuery.add(new TermQuery(new Term(INDEXFIELD_ISVIRTUALCONTENT, String.valueOf(true))), BooleanClause.Occur.MUST_NOT); } // handle doctype option // we cannot be sure that all documents in index already contains the field DOCTYPE (introduced with OpenWGA 7.1) therefore we have to perform some excludes if (doctype.equals(DOCTYPE_CONTENT)) { wholeQuery.add(new TermQuery(new Term(INDEXFIELD_DOCTYPE, DOCTYPE_ATTACHMENT)), BooleanClause.Occur.MUST_NOT); } else if (!doctype.equals(DOCTYPE_ALL)) { wholeQuery.add(new TermQuery(new Term(INDEXFIELD_DOCTYPE, doctype)), BooleanClause.Occur.MUST); } //build phrase query BooleanQuery phraseQuery = new BooleanQuery(); phraseQuery.setBoost(10); Iterator languageList = languagesPriorityList.iterator(); List<String> searchFields = new ArrayList<String>(); Map<String, Float> searchBoosts = new HashMap<String, Float>(); for (String field : fields) { String[] parts = field.split("\\^"); searchFields.add(parts[0]); if (parts.length == 2) { searchBoosts.put(parts[0], Float.parseFloat(parts[1])); } } if (!searchFields.contains("allcontent")) searchFields.add("allcontent"); if (!searchFields.contains("TITLE")) searchFields.add("TITLE"); if (!searchFields.contains("DESCRIPTION")) searchFields.add("DESCRIPTION"); if (!searchFields.contains("KEYWORDS")) searchFields.add("KEYWORDS"); while (languageList.hasNext()) { WGLanguage languageItem = (WGLanguage) languageList.next(); Analyzer analyzer = _core.getAnalyzerForLanguageCode(languageItem.getName().substring(0, 2)); if (analyzer != null) { QueryParser parser = new IndexingRuleBasedQueryParser(searchFields.toArray(new String[0]), analyzer, searchBoosts, _indexedDbs, searchDBKeys, _metaKeywordFields); parser.setDefaultOperator(defaultOperator); Query query = parser.parse(phrase); if (filterLanguages) { BooleanQuery testPhraseAndLangQuery = new BooleanQuery(); testPhraseAndLangQuery.add(query, BooleanClause.Occur.MUST); testPhraseAndLangQuery.add( new TermQuery(new Term(WGContent.META_LANGUAGE, languageItem.getName())), BooleanClause.Occur.MUST); phraseQuery.add(testPhraseAndLangQuery, BooleanClause.Occur.SHOULD); } else { phraseQuery.add(query, BooleanClause.Occur.SHOULD); } } else { searchWithDefaultAnalyzer = true; } } if (searchWithDefaultAnalyzer) { QueryParser parser = new IndexingRuleBasedQueryParser(searchFields.toArray(new String[0]), _core.getDefaultAnalyzer(), searchBoosts, _indexedDbs, searchDBKeys, _metaKeywordFields); parser.setDefaultOperator(defaultOperator); Query query = parser.parse(phrase); phraseQuery.add(query, BooleanClause.Occur.SHOULD); } //LOG.info(phraseQuery.toString()); wholeQuery.add(phraseQuery, BooleanClause.Occur.MUST); TopDocs hits; //register executed query as output parameter parameters.put(WGDatabase.QUERYOPTION_RETURNQUERY, wholeQuery.toString()); // simplify query and register as taginfo parameters.put(TAGINFO_SIMPLIFIEDQUERY, rewrite(wholeQuery)); long timeBefore = System.currentTimeMillis(); if (sort != null) { try { hits = search(wholeQuery, max, sort); } catch (NullPointerException e) { // lucene bug when sorting for non existing fields with Locale throw new WGQueryException(wholeQuery.toString(), "Sortfield '" + sortFieldName + "' not indexed."); } } else { try { hits = search(wholeQuery, max, null); } catch (BooleanQuery.TooManyClauses e) { parameters.put(TAGINFO_UNSPECIFICQUERY, new Boolean(true)); throw new WGQueryException(phrase, "Too many BooleanClauses in query. " + "Please use a more specific query or increase value of " + "'booleanQueryMaxClauseCount' via WGAManager. Current value is '" + this.getBooleanQueryMaxClauseCount() + "'."); } } long timeAfter = System.currentTimeMillis(); long executionTime = timeAfter - timeBefore; LuceneResultSet resultSet; if (filterLanguages) { resultSet = new LuceneLanguageChoosingResultSet(hits, wga, parameters, wholeQuery, executionTime, languagesPriorityList); } else { resultSet = new LuceneMultiDBResultSet(hits, wga, parameters, wholeQuery, executionTime); } // put resultset in per thread list List rsList = (List) _resultsetList.get(); if (rsList == null) { rsList = new LinkedList(); _resultsetList.set(rsList); } rsList.add(resultSet); return resultSet; } catch (org.apache.lucene.queryParser.ParseException e) { throw new WGQueryException("Unable to parse lucene query", e.getMessage(), e); } catch (Exception e) { LOG.error("Error executing lucene search: " + e.getClass().getName() + " - " + e.getMessage(), e); throw new WGQueryException(phrase, e.getClass().getName() + ": " + e.getMessage(), e); } }
From source file:org.akaza.openclinica.control.submit.DataEntryServlet.java
private HashMap<String, ArrayList<String>> runRules(List<DisplayItemWithGroupBean> allItems, List<RuleSetBean> ruleSets, Boolean dryRun, Boolean shouldRunRules, MessageType mt, Phase phase, EventCRFBean ecb, HttpServletRequest request) { UserAccountBean ub = (UserAccountBean) request.getSession().getAttribute(USER_BEAN_NAME); StudyBean currentStudy = (StudyBean) request.getSession().getAttribute("study"); if (shouldRunRules) { Container c = new Container(); try {/*from w w w . java 2s . c o m*/ c = populateRuleSpecificHashMaps(allItems, c, dryRun); ruleSets = getRuleSetService(request).filterRuleSetsBySectionAndGroupOrdinal(ruleSets, c.grouped); ruleSets = getRuleSetService(request).solidifyGroupOrdinalsUsingFormProperties(ruleSets, c.grouped); // next line here ? } catch (NullPointerException npe) { LOGGER.debug("found NPE " + npe.getMessage()); npe.printStackTrace(); } // above throws NPE? // return getRuleSetService().runRules(ruleSets, dryRun, // currentStudy, c.variableAndValue, ub); LOGGER.debug("running rules ... rule sets size is " + ruleSets.size()); return getRuleSetService(request).runRulesInDataEntry(ruleSets, dryRun, currentStudy, ub, c.variableAndValue, phase, ecb, request).getByMessageType(mt); } else { return new HashMap<String, ArrayList<String>>(); } }
From source file:com.emental.mindraider.ui.graph.spiders.SpidersGraph.java
/** * This class kernel method - render active model. <br/>Remarks: o Label vs * ID vs URI o label is just human readable annotation, used just for human * searches o it is system level identification of the node - ID must be * unique (used in touchgraph hashes) o URI is annotation of mine resource, * it is additional information; MR uses URIs to search for resources (note * that URIs are independent from IDs - ID is system level; URI is MR logic * level) Icons o all nodes that are clickable are marked with network icon * * @todo o performance o on selection of notebook in explorer panel, it is * rendered twice o set zoom and lookahead to proper value in order to * improve performance of the graph rendering o prepare rendering * profile for MR - colors of resource types (notebook, attachment, * etc.) o prepare renderNg() method (old rename to renderOld() and * encapsulate them to render() where will be just switch) o it's * therefore rendering profiles will require rendering by statement * (which is already implemented) o loop (getStatement(); * selectSubject(); createStatement(already exists)); *//*from w ww . j a v a 2 s . c o m*/ public void renderModel() { if (OutlineJPanel.getInstance().spidersAndTagsTabs.getSelectedIndex() == 1) { return; } if (rdfModel == null || rdfModel.getModel() == null) { return; } // detect whether there is some node selected, if so, remember its ID Node selectedNode; String selectedNodeId; // try to remember selected node id to select it after rendering try { selectedNode = tgPanel.getSelect(); // @todo solve literals ID selection - invent some stable ID // generation algorithm selectedNodeId = selectedNode.getID(); } catch (NullPointerException e) { selectedNode = null; selectedNodeId = null; } // clean up visuals clearGraph(); // render it again // make initial TG setup // @todo set this according to zoom and whether predicate is/is not // rendered Edge.setEdgeDefaultLength(80); Edge.setEdgeDefaultColor(render.getEdgeDefaultColor()); // now fill in the TG representation try { Node firstNode = null, subjectNode, objectNode, predicateNode = null; NodeDescriptor nodeDescriptor; Statement statement; String id, label; StmtIterator i = rdfModel.getModel().listStatements(); while (i.hasNext()) { statement = i.nextStatement(); /* * facet */ if (!facet.showThisStatement(statement)) { logger.debug(" Facet: skipping " + statement); continue; } renderedTriplets++; /* * rendering */ // subject node nodeDescriptor = getNodeDescriptor(statement.getSubject()); // @todo find node by URL, if it fail, then it must be some // noname node - so use ID instead if ((subjectNode = tgPanel.findNode(nodeDescriptor.getId())) == null) { subjectNode = createSubjectNode(nodeDescriptor); subjectNode.rdfNode = statement.getSubject(); tgPanel.addNode(subjectNode); } // predicate node if (!hidePredicates) { // default predicate has empty label String ns = statement.getPredicate().getNameSpace(); if (StringUtils.equals(MindRaiderConstants.MR_RDF_PREDICATE_NS, ns) && StringUtils.equals(MindRaiderConstants.MR_RDF_PREDICATE, ns)) { label = ""; } else { label = uriLabels ? statement.getPredicate().getURI() : statement.getPredicate().getLocalName(); } // for predicate, ID is always unique id = statement.getPredicate().getURI() + "_" + MindRaiderConstants.MR + renderedTriplets; predicateNode = createPredicateNode(id, label); tgPanel.addNode(predicateNode); // the first half of the edge createSubject2PredicateEdge(subjectNode, predicateNode); } // object node if (statement.getObject() instanceof Resource) { nodeDescriptor = getNodeDescriptor((Resource) statement.getObject()); if ((objectNode = tgPanel.findNode(nodeDescriptor.getId())) == null) { objectNode = createObjectNode(nodeDescriptor); tgPanel.addNode(objectNode); } } else { // literal objectNode = createLiteralNode("literal_" + MindRaiderConstants.MR + renderedTriplets, statement.getObject().toString()); tgPanel.addNode(objectNode); } objectNode.rdfNode = statement.getObject(); if (!hidePredicates) { // the second half of the edge createPredicate2ObjectEdge(predicateNode, objectNode); } else { // hide predicates createPredicate2ObjectEdgePredicateHidden(subjectNode, objectNode, statement.getPredicate().getURI()); } } if (firstNode == null) { firstNode = tgPanel.getGES().getFirstNode(); tgPanel.setLocale(firstNode, 0); tgPanel.setSelect(firstNode); } // now try to previously selected node AND set locality if (selectedNodeId != null) { selectedNode = tgPanel.findNode(selectedNodeId); } else { tgPanel.selectFirstNode(); selectedNode = getSelectedNode(); } tgPanel.setSelect(selectedNode); tgPanel.setLocale(selectedNode, glPanel.localityScroll.getLocalityRadius()); logger.debug(" Total triplets: " + renderedTriplets); } catch (Exception e) { logger.error("Unable to enumerate statements: " + e.getMessage(), e); } }
From source file:org.akaza.openclinica.control.submit.DataEntryServlet.java
/** * Get the input beans - the EventCRFBean and the SectionBean. For both beans, look first in the request attributes to see if the bean has been stored * there. If not, look in the parameters for the bean id, and then retrieve the bean from the database. The beans are stored as protected class members. * @param request TODO/*from www.j av a 2 s .c o m*/ */ protected void getInputBeans(HttpServletRequest request) throws InsufficientPermissionException { HttpSession session = request.getSession(); StudyBean currentStudy = (StudyBean) session.getAttribute("study"); // BWP >>we should have the correct crfVersionId, in order to acquire // the correct // section IDs FormProcessor fp = new FormProcessor(request); EventCRFDAO ecdao = new EventCRFDAO(getDataSource()); SectionDAO sdao = new SectionDAO(getDataSource()); EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF); //JN:Happening when drilling down? if (ecb == null) { int eventCRFId = fp.getInt(INPUT_EVENT_CRF_ID, true); LOGGER.debug("found event crf id: " + eventCRFId); if (eventCRFId > 0) { LOGGER.debug("***NOTE*** that we didnt have to create an event crf because we already have one: " + eventCRFId); // there is an event CRF already, only need to update ecb = (EventCRFBean) ecdao.findByPK(eventCRFId); // ecb.setUpdatedDate(new Date()); // ecb.setUpdater(ub); // ecb = (EventCRFBean) ecdao.update(ecb); // logger.trace("found an event crf id "+eventCRFId); // YW 11-12-2007 << if interviewer or/and interview date // has/have been updated for study/site from "blank" to // "pre-populated" // But at this point, this update only shows on web page and // will not be updated to database. int studyEventId = fp.getInt(INPUT_STUDY_EVENT_ID); request.setAttribute(INPUT_EVENT_CRF, ecb); if (studyEventId > 0) { StudyEventDAO sedao = new StudyEventDAO(getDataSource()); StudyEventBean sEvent = (StudyEventBean) sedao.findByPK(studyEventId); ecb = updateECB(sEvent, request); } request.setAttribute(INPUT_EVENT_CRF, ecb); // YW >> } else { // CRF id <=0, so we need to create a new CRF // use toCreateCRF as a flag to prevent user to submit event CRF // more than once // for example, user reloads the page String toCreateCRF = (String) session.getAttribute("to_create_crf"); if (StringUtil.isBlank(toCreateCRF) || "0".equals(toCreateCRF)) { session.setAttribute("to_create_crf", "1"); } try { // if (ecb.getInterviewerName() != null) { LOGGER.debug("Initial: to create an event CRF."); String toCreateCRF1 = (String) session.getAttribute("to_create_crf"); if (!StringUtil.isBlank(toCreateCRF1) && "1".equals(toCreateCRF1)) { ecb = createEventCRF(request, fp); session.setAttribute("ecb", ecb); request.setAttribute(INPUT_EVENT_CRF, ecb); session.setAttribute("to_create_crf", "0"); } else { ecb = (EventCRFBean) session.getAttribute("ecb"); } // } } catch (InconsistentStateException ie) { ie.printStackTrace(); addPageMessage(ie.getOpenClinicaMessage(), request); throw new InsufficientPermissionException(Page.LIST_STUDY_SUBJECTS_SERVLET, ie.getOpenClinicaMessage(), "1"); } catch (NullPointerException ne) { ne.printStackTrace(); addPageMessage(ne.getMessage(), request); throw new InsufficientPermissionException(Page.LIST_STUDY_SUBJECTS_SERVLET, ne.getMessage(), "1"); } } } // added to allow sections shown on this page DisplayTableOfContentsBean displayBean = new DisplayTableOfContentsBean(); displayBean = TableOfContentsServlet.getDisplayBean(ecb, getDataSource(), currentStudy); // escape apostrophe in event name displayBean.getStudyEventDefinition() .setName(StringEscapeUtils.escapeJavaScript(displayBean.getStudyEventDefinition().getName())); request.setAttribute(TOC_DISPLAY, displayBean); int sectionId = fp.getInt(INPUT_SECTION_ID, true); ArrayList sections; if (sectionId <= 0) { StudyEventDAO studyEventDao = new StudyEventDAO(getDataSource()); int maximumSampleOrdinal = studyEventDao.getMaxSampleOrdinal(displayBean.getStudyEventDefinition(), displayBean.getStudySubject()); request.setAttribute("maximumSampleOrdinal", maximumSampleOrdinal); sections = sdao.findAllByCRFVersionId(ecb.getCRFVersionId()); for (int i = 0; i < sections.size(); i++) { SectionBean sb = (SectionBean) sections.get(i); sectionId = sb.getId();// find the first section of this CRF break; } } SectionBean sb = new SectionBean(); if (sectionId > 0) { // int sectionId = fp.getInt(INPUT_SECTION_ID, true); //synchronized(this) { sb = (SectionBean) sdao.findByPK(sectionId); } } int tabId = fp.getInt("tab", true); if (tabId <= 0) { tabId = 1; } request.setAttribute(INPUT_TAB, new Integer(tabId)); request.setAttribute(SECTION_BEAN, sb); }
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;/* ww w .j a va 2 s .co m*/ } //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:net.wastl.webmail.server.WebMailSession.java
/** * Create a Message List.//w w w . j a va 2 s . co m * Fetches a list of headers in folder foldername for part list_part. * The messagelist will be stored in the "MESSAGES" environment. * * @param foldername folder for which a message list should be built * @param list_part part of list to display (1 = last xx messages, 2 = total-2*xx - total-xx messages) */ public void createMessageList(String folderhash, int list_part) throws NoSuchFolderException { long time_start = System.currentTimeMillis(); TimeZone tz = TimeZone.getDefault(); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, user.getPreferredLocale()); df.setTimeZone(tz); try { Folder folder = getFolder(folderhash); Element xml_folder = model.getFolder(folderhash); Element xml_current = model.setCurrentFolder(folderhash); Element xml_messagelist = model.getMessageList(xml_folder); if (folder == null) { throw new NoSuchFolderException(folderhash); } long fetch_start = System.currentTimeMillis(); if (!folder.isOpen()) { folder.open(Folder.READ_ONLY); } else { folder.close(false); folder.open(Folder.READ_ONLY); } /* Calculate first and last message to show */ int total_messages = folder.getMessageCount(); int new_messages = folder.getNewMessageCount(); int show_msgs = user.getMaxShowMessages(); xml_messagelist.setAttribute("total", total_messages + ""); xml_messagelist.setAttribute("new", new_messages + ""); log.debug("Total: " + total_messages); /* Handle small messagelists correctly */ if (total_messages < show_msgs) { show_msgs = total_messages; } /* Don't accept list-parts smaller than 1 */ if (list_part < 1) { list_part = 1; } for (int k = 0; k < list_part; k++) { total_messages -= show_msgs; } /* Handle beginning of message list */ if (total_messages < 0) { total_messages = 0; } int first = total_messages + 1; int last = total_messages + show_msgs; /* Set environment variable */ setEnv(); xml_current.setAttribute("first_msg", first + ""); xml_current.setAttribute("last_msg", last + ""); xml_current.setAttribute("list_part", list_part + ""); /* Fetch headers */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.CONTENT_INFO); log.debug("Last: " + last + ", first: " + first); Message[] msgs = folder.getMessages(first, last); log.debug(msgs.length + " messages fetching..."); folder.fetch(msgs, fp); long fetch_stop = System.currentTimeMillis(); Map header = new Hashtable(15); Flags.Flag[] sf; String from, to, cc, bcc, replyto, subject; String messageid; for (int i = msgs.length - 1; i >= 0; i--) { // if(((MimeMessage)msgs[i]).getMessageID() == null) { // folder.close(false); // folder.open(Folder.READ_WRITE); // ((MimeMessage)msgs[i]).setHeader("Message-ID","<"+user.getLogin()+"."+System.currentTimeMillis()+".jwebmail@"+user.getDomain()+">"); // ((MimeMessage)msgs[i]).saveChanges(); // folder.close(false); // folder.open(Folder.READ_ONLY); // } try { StringTokenizer tok = new StringTokenizer(((MimeMessage) msgs[i]).getMessageID(), "<>"); messageid = tok.nextToken(); } catch (NullPointerException ex) { // For mail servers that don't generate a Message-ID (Outlook et al) messageid = user.getLogin() + "." + i + ".jwebmail@" + user.getDomain(); } XMLMessage xml_message = model.getMessage(xml_folder, msgs[i].getMessageNumber() + "", messageid); /* Addresses */ from = ""; replyto = ""; to = ""; cc = ""; bcc = ""; try { from = MimeUtility.decodeText(Helper.joinAddress(msgs[i].getFrom())); } catch (UnsupportedEncodingException e) { from = Helper.joinAddress(msgs[i].getFrom()); } try { replyto = MimeUtility.decodeText(Helper.joinAddress(msgs[i].getReplyTo())); } catch (UnsupportedEncodingException e) { replyto = Helper.joinAddress(msgs[i].getReplyTo()); } try { to = MimeUtility .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.TO))); } catch (UnsupportedEncodingException e) { to = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.TO)); } try { cc = MimeUtility .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.CC))); } catch (UnsupportedEncodingException e) { cc = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.CC)); } try { bcc = MimeUtility .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.BCC))); } catch (UnsupportedEncodingException e) { bcc = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.BCC)); } if (from == "") from = getStringResource("unknown sender"); if (to == "") to = getStringResource("unknown recipient"); /* Flags */ sf = msgs[i].getFlags().getSystemFlags(); String basepath = parent.getBasePath(); for (int j = 0; j < sf.length; j++) { if (sf[j] == Flags.Flag.RECENT) xml_message.setAttribute("recent", "true"); if (sf[j] == Flags.Flag.SEEN) xml_message.setAttribute("seen", "true"); if (sf[j] == Flags.Flag.DELETED) xml_message.setAttribute("deleted", "true"); if (sf[j] == Flags.Flag.ANSWERED) xml_message.setAttribute("answered", "true"); if (sf[j] == Flags.Flag.DRAFT) xml_message.setAttribute("draft", "true"); if (sf[j] == Flags.Flag.FLAGGED) xml_message.setAttribute("flagged", "true"); if (sf[j] == Flags.Flag.USER) xml_message.setAttribute("user", "true"); } if (msgs[i] instanceof MimeMessage && ((MimeMessage) msgs[i]).getContentType().toUpperCase().startsWith("MULTIPART/")) { xml_message.setAttribute("attachment", "true"); } if (msgs[i] instanceof MimeMessage) { int size = ((MimeMessage) msgs[i]).getSize(); size /= 1024; xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB"); } /* Subject */ subject = ""; if (msgs[i].getSubject() != null) { try { subject = MimeUtility.decodeText(msgs[i].getSubject()); } catch (UnsupportedEncodingException ex) { subject = msgs[i].getSubject(); log.warn("Unsupported Encoding: " + ex.getMessage()); } } if (subject == null || subject.equals("")) { subject = getStringResource("no subject"); } /* Set all of what we found into the DOM */ xml_message.setHeader("FROM", from); try { // hmm, why decode subject twice? Though it doesn't matter.. xml_message.setHeader("SUBJECT", MimeUtility.decodeText(subject)); } catch (UnsupportedEncodingException e) { xml_message.setHeader("SUBJECT", subject); log.warn("Unsupported Encoding: " + e.getMessage()); } xml_message.setHeader("TO", to); xml_message.setHeader("CC", cc); xml_message.setHeader("BCC", bcc); xml_message.setHeader("REPLY-TO", replyto); /* Date */ Date d = msgs[i].getSentDate(); String ds = ""; if (d != null) { ds = df.format(d); } xml_message.setHeader("DATE", ds); } long time_stop = System.currentTimeMillis(); // try { // XMLCommon.writeXML(model.getRoot(),new FileOutputStream("/tmp/wmdebug"),""); // } catch(IOException ex) {} log.debug("Construction of message list took " + (time_stop - time_start) + " ms. Time for IMAP transfer was " + (fetch_stop - fetch_start) + " ms."); folder.close(false); } catch (NullPointerException e) { log.error("Failed to construct message list", e); throw new NoSuchFolderException(folderhash); } catch (MessagingException ex) { log.error("Failed to construct message list. " + "For some reason, contuing anyways.", ex); } }
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;//from w w w.j a v a 2s . 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:at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorServlet.java
/** * Handles the reception of a STORK response message * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */// w w w. ja v a 2 s . c o m protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pendingRequestID = null; try { Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); Logger.info("PEPSConnector Servlet invoked, expecting C-PEPS message."); Logger.debug("This ACS endpoint is: " + HTTPUtils.getBaseURL(request)); super.setNoCachingHeadersInHttpRespone(request, response); Logger.trace("No Caching headers set for HTTP response"); //check if https or only http super.checkIfHTTPisAllowed(request.getRequestURL().toString()); Logger.debug("Beginning to extract SAMLResponse out of HTTP Request"); //extract STORK Response from HTTP Request //Decodes SAML Response byte[] decSamlToken; try { decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLResponse")); Logger.debug("SAMLResponse: " + new String(decSamlToken)); } catch (NullPointerException e) { Logger.error("Unable to retrieve STORK Response", e); throw new MOAIDException("stork.04", null); } //Get SAMLEngine instance STORKSAMLEngine engine = STORKSAMLEngine.getInstance("outgoing"); STORKAuthnResponse authnResponse = null; try { //validate SAML Token Logger.debug("Starting validation of SAML response"); authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, (String) request.getRemoteHost()); Logger.info("SAML response succesfully verified!"); } catch (STORKSAMLEngineException e) { Logger.error("Failed to verify STORK SAML Response", e); throw new MOAIDException("stork.05", null); } Logger.info("STORK SAML Response message succesfully extracted"); Logger.debug("STORK response: "); Logger.debug(authnResponse.toString()); Logger.debug("Trying to find MOA Session-ID ..."); //String moaSessionID = request.getParameter(PARAM_SESSIONID); //first use SAML2 relayState String moaSessionID = request.getParameter("RelayState"); // escape parameter strings moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID); //check if SAML2 relaystate includes a MOA sessionID if (StringUtils.isEmpty(moaSessionID)) { //if relaystate is emtpty, use SAML response -> inResponseTo element as session identifier moaSessionID = authnResponse.getInResponseTo(); moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID); if (StringUtils.isEmpty(moaSessionID)) { //No authentication session has been started before Logger.error("MOA-SessionID was not found, no previous AuthnRequest had been started"); Logger.debug("PEPSConnectorURL was: " + request.getRequestURL()); throw new AuthenticationException("auth.02", new Object[] { moaSessionID }); } else Logger.trace( "Use MOA SessionID " + moaSessionID + " from AuthnResponse->inResponseTo attribute."); } else //Logger.trace("MOA SessionID " + moaSessionID + " is found in http GET parameter."); Logger.trace("MOA SessionID " + moaSessionID + " is found in SAML2 relayState."); /*INFO!!!! * SAML message IDs has an different format then MOASessionIDs * This is only a workaround because many PEPS does not support SAML2 relayState or * MOASessionID as AttributConsumerServiceURL GET parameter */ // if (!ParamValidatorUtils.isValidSessionID(moaSessionID)) // throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12"); pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); //load MOASession from database AuthenticationSession moaSession = AuthenticationServer.getSession(moaSessionID); //change MOASessionID moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); Logger.info("Found MOA sessionID: " + moaSessionID); String statusCodeValue = authnResponse.getStatusCode(); if (!statusCodeValue.equals(StatusCode.SUCCESS_URI)) { Logger.error("Received ErrorResponse from PEPS: " + statusCodeValue); throw new MOAIDException("stork.06", new Object[] { statusCodeValue }); } Logger.info("Got SAML response with authentication success message."); Logger.debug("MOA session is still valid"); STORKAuthnRequest storkAuthnRequest = moaSession.getStorkAuthnRequest(); if (storkAuthnRequest == null) { Logger.error( "Could not find any preceeding STORK AuthnRequest to this MOA session: " + moaSessionID); throw new MOAIDException("stork.07", null); } OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() .getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix()); if (oaParam == null) throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() }); //================== Check QAA level start ==================== int reqQaa = -1; int authQaa = -1; String authQaaStr = null; try { reqQaa = storkAuthnRequest.getQaa(); //TODO: found better solution, but QAA Level in response could be not supported yet try { authQaaStr = authnResponse.getAssertions().get(0).getAuthnStatements().get(0).getAuthnContext() .getAuthnContextClassRef().getAuthnContextClassRef(); moaSession.setQAALevel(authQaaStr); } catch (Throwable e) { Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level"); moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel()); authQaaStr = PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel(); } if (authQaaStr != null)//Check value only if set { authQaa = Integer.valueOf(authQaaStr.substring(PVPConstants.STORK_QAA_PREFIX.length())); // authQaa = Integer.valueOf(authQaaStr); if (reqQaa > authQaa) { Logger.warn("Requested QAA level does not match to authenticated QAA level"); throw new MOAIDException("stork.21", new Object[] { reqQaa, authQaa }); } } } catch (MOAIDException e) { throw e; } catch (Exception e) { if (Logger.isDebugEnabled()) Logger.warn("STORK QAA Level evaluation error", e); else Logger.warn("STORK QAA Level evaluation error (ErrorMessage=" + e.getMessage() + ")"); throw new MOAIDException("stork.21", new Object[] { reqQaa, authQaa }); } //================== Check QAA level end ==================== Logger.debug("Found a preceeding STORK AuthnRequest to this MOA session: " + moaSessionID); ////////////// incorporate gender from parameters if not in stork response IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList(); // but first, check if we have a representation case if (STORKResponseProcessor.hasAttribute("mandateContent", attributeList) || STORKResponseProcessor.hasAttribute("representative", attributeList) || STORKResponseProcessor.hasAttribute("represented", attributeList)) { // in a representation case... moaSession.setUseMandate("true"); // and check if we have the gender value PersonalAttribute gender = attributeList.get("gender"); // TODO Do we need to check gender value if there is no representation case? if (null == gender) { String gendervalue = (String) request.getParameter("gender"); if (null != gendervalue) { gender = new PersonalAttribute(); gender.setName("gender"); ArrayList<String> tmp = new ArrayList<String>(); tmp.add(gendervalue); gender.setValue(tmp); authnResponse.getPersonalAttributeList().add(gender); } } } ////////////////////////////////////////////////////////////////////////// Logger.debug("Starting extraction of signedDoc attribute"); //extract signed doc element and citizen signature String citizenSignature = null; try { String signatureInfo = authnResponse.getPersonalAttributeList().get("signedDoc").getValue().get(0); // TODO ERROR HANDLING Logger.debug("signatureInfo:" + signatureInfo); SignResponse dssSignResponse = (SignResponse) ApiUtils .unmarshal(new StreamSource(new java.io.StringReader(signatureInfo))); // fetch signed doc DataSource ds = null; try { ds = LightweightSourceResolver.getDataSource(dssSignResponse); } catch (Exception e) { e.printStackTrace(); } if (ds == null) { //Normal DocumentServices return a http-page, but the SI DocumentService returns HTTP error 500 //which results in an exception and ds==null //try to load document from documentservice citizenSignature = loadDocumentFromDocumentService(dssSignResponse); //throw new ApiUtilsException("No datasource found in response"); } else { InputStream incoming = ds.getInputStream(); citizenSignature = IOUtils.toString(incoming); incoming.close(); Logger.debug("citizenSignature:" + citizenSignature); if (isDocumentServiceUsed(citizenSignature) == true) { citizenSignature = loadDocumentFromDocumentService(dssSignResponse); // Logger.debug("Loading document from DocumentService."); // String url = getDtlUrlFromResponse(dssSignResponse); // //get Transferrequest // String transferRequest = getDocTransferRequest(dssSignResponse.getDocUI(), url); // //Load document from DocumentService // byte[] data = getDocumentFromDtl(transferRequest, url); // citizenSignature = new String(data, "UTF-8"); // Logger.debug("Overridung citizenSignature with:"+citizenSignature); } } JAXBContext ctx = JAXBContext.newInstance(SignatureType.class.getPackage().getName()); SignatureType root = ((JAXBElement<SignatureType>) ctx.createUnmarshaller() .unmarshal(IOUtils.toInputStream(citizenSignature))).getValue(); // memorize signature into authblock moaSession.setAuthBlock(citizenSignature); // extract certificate for (Object current : root.getKeyInfo().getContent()) if (((JAXBElement<?>) current).getValue() instanceof X509DataType) { for (Object currentX509Data : ((JAXBElement<X509DataType>) current).getValue() .getX509IssuerSerialOrX509SKIOrX509SubjectName()) { JAXBElement<?> casted = ((JAXBElement<?>) currentX509Data); if (casted.getName().getLocalPart().equals("X509Certificate")) { moaSession.setSignerCertificate( new X509Certificate(((String) casted.getValue()).getBytes("UTF-8"))); break; } } } } catch (Throwable e) { Logger.error("Could not extract citizen signature from C-PEPS", e); throw new MOAIDException("stork.09", null); } Logger.debug("Foregin Citizen signature successfully extracted from STORK Assertion (signedDoc)"); Logger.debug("Citizen signature will be verified by SZR Gateway!"); Logger.debug("fetching OAParameters from database"); // //read configuration paramters of OA // AuthenticationSession moasession; // try { // moasession = AuthenticationSessionStoreage.getSession(moaSessionID); // } catch (MOADatabaseException e2) { // Logger.error("could not retrieve moa session"); // throw new AuthenticationException("auth.01", null); // } // OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix()); // if (oaParam == null) // throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() }); // retrieve target //TODO: check in case of SSO!!! String targetType = null; if (oaParam.getBusinessService()) { String id = oaParam.getIdentityLinkDomainIdentifier(); if (id.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_)) targetType = id; else targetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_ + moaSession.getDomainIdentifier(); } else { targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget(); } IdentityLink identityLink = null; try { AuthConfigurationProvider config = AuthConfigurationProvider.getInstance(); if (config.isStorkFakeIdLActive() && config.getStorkFakeIdLCountries().contains(storkAuthnRequest.getCitizenCountryCode())) { // create fake IdL // - fetch IdL template from resources InputStream s = PEPSConnectorServlet.class .getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml"); Element idlTemplate = DOMUtils.parseXmlValidating(s); identityLink = new IdentityLinkAssertionParser(idlTemplate).parseIdentityLink(); // replace data Element idlassertion = identityLink.getSamlAssertion(); // - set bpk/wpbk; Node prIdentification = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); if (!STORKResponseProcessor.hasAttribute("eIdentifier", attributeList)) throw new STORKException("eIdentifier is missing"); String eIdentifier = STORKResponseProcessor.getAttributeValue("eIdentifier", attributeList, false); prIdentification.getFirstChild().setNodeValue(eIdentifier); // - set last name Node prFamilyName = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_FAMILY_NAME_XPATH); if (!STORKResponseProcessor.hasAttribute("surname", attributeList)) throw new STORKException("surname is missing"); String familyName = STORKResponseProcessor.getAttributeValue("surname", attributeList, false); prFamilyName.getFirstChild().setNodeValue(familyName); // - set first name Node prGivenName = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_GIVEN_NAME_XPATH); if (!STORKResponseProcessor.hasAttribute("givenName", attributeList)) throw new STORKException("givenName is missing"); String givenName = STORKResponseProcessor.getAttributeValue("givenName", attributeList, false); prGivenName.getFirstChild().setNodeValue(givenName); // - set date of birth Node prDateOfBirth = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_DATE_OF_BIRTH_XPATH); if (!STORKResponseProcessor.hasAttribute("dateOfBirth", attributeList)) throw new STORKException("dateOfBirth is missing"); String dateOfBirth = STORKResponseProcessor.getAttributeValue("dateOfBirth", attributeList, false); prDateOfBirth.getFirstChild().setNodeValue(dateOfBirth); identityLink = new IdentityLinkAssertionParser(idlassertion).parseIdentityLink(); //resign IDL IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance(); Element resignedilAssertion = identitylinkresigner.resignIdentityLink( identityLink.getSamlAssertion(), config.getStorkFakeIdLResigningKey()); identityLink = new IdentityLinkAssertionParser(resignedilAssertion).parseIdentityLink(); } else { //contact SZR Gateway Logger.debug("Starting connecting SZR Gateway"); identityLink = STORKResponseProcessor.connectToSZRGateway( authnResponse.getPersonalAttributeList(), oaParam.getFriendlyName(), targetType, null, oaParam.getMandateProfiles(), citizenSignature); } } catch (STORKException e) { // this is really nasty but we work against the system here. We are supposed to get the gender attribute from // stork. If we do not, we cannot register the person in the ERnP - we have to have the // gender for the represented person. So here comes the dirty hack. if (e.getCause() instanceof STORKException && e.getCause().getMessage().equals("gender not found in response")) { try { Logger.trace("Initialize VelocityEngine..."); VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html"); VelocityContext context = new VelocityContext(); context.put("SAMLResponse", request.getParameter("SAMLResponse")); context.put("action", request.getRequestURL()); StringWriter writer = new StringWriter(); template.merge(context, writer); response.getOutputStream().write(writer.toString().getBytes("UTF-8")); } catch (Exception e1) { Logger.error("Error sending gender retrival form.", e1); // httpSession.invalidate(); throw new MOAIDException("stork.10", null); } return; } Logger.error("Error connecting SZR Gateway", e); throw new MOAIDException("stork.10", null); } Logger.debug("SZR communication was successfull"); if (identityLink == null) { Logger.error("SZR Gateway did not return an identity link."); throw new MOAIDException("stork.10", null); } moaSession.setForeigner(true); Logger.info("Received Identity Link from SZR Gateway"); moaSession.setIdentityLink(identityLink); Logger.debug("Adding addtional STORK attributes to MOA session"); moaSession.setStorkAttributes(authnResponse.getPersonalAttributeList()); Logger.debug("Add full STORK AuthnResponse to MOA session"); moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse")); //We don't have BKUURL, setting from null to "Not applicable" moaSession.setBkuURL("Not applicable (STORK Authentication)"); // free for single use moaSession.setAuthenticatedUsed(false); // stork did the authentication step moaSession.setAuthenticated(true); // //TODO: found better solution, but QAA Level in response could be not supported yet // try { // // moaSession.setQAALevel(authnResponse.getAssertions().get(0). // getAuthnStatements().get(0).getAuthnContext(). // getAuthnContextClassRef().getAuthnContextClassRef()); // // } catch (Throwable e) { // Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level"); // moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel()); // // } //session is implicit stored in changeSessionID!!!! String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID); //redirect String redirectURL = null; redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(), ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID), newMOASessionID); redirectURL = response.encodeRedirectURL(redirectURL); // response.setContentType("text/html"); // response.setStatus(302); // response.addHeader("Location", redirectURL); response.sendRedirect(redirectURL); Logger.info("REDIRECT TO: " + redirectURL); } catch (AuthenticationException e) { handleError(null, e, request, response, pendingRequestID); } catch (MOAIDException e) { handleError(null, e, request, response, pendingRequestID); } catch (Exception e) { Logger.error("PEPSConnector has an interal Error.", e); } finally { ConfigurationDBUtils.closeSession(); } }