List of usage examples for org.dom4j Element getTextTrim
String getTextTrim();
From source file:edu.ku.brc.specify.plugins.ipadexporter.VerifyCollectionDlg.java
License:Open Source License
/** * /*w w w . j a va 2s . co m*/ */ private void processResults() { //loadAndPushResourceBundle("stats"); RelationshipType paleoRelType = isCollectionPaleo ? ExportPaleo.discoverPaleRelationshipType() : RelationshipType.eTypeError; boolean hasCritical = false; UIRegistry.setDoShowAllResStrErors(false); //logMsg("Verifying the Collection..."); File tmpFile = ipadExporter.getConfigFile(VERIFY_XML); if (tmpFile != null && tmpFile.exists()) { Statement stmt0 = null; try { Element root = XMLHelper.readFileToDOM4J(tmpFile); if (root != null) { ArrayList<String> okMsgs = new ArrayList<String>(); ArrayList<String> warnMsgs = new ArrayList<String>(); ArrayList<String> criticalMsgs = new ArrayList<String>(); int issueCnt = 0; String mainFont = "<font face='verdana' color='black'>"; String headHTML = "<htmL><head></head><body bgcolor='#EEEEEE'>" + mainFont; StringBuilder sb = new StringBuilder(headHTML); htmlPane.setText(sb.toString() + "<BR><BR>Verifying collection...</font></body></html>"); List<?> items = root.selectNodes("eval"); //$NON-NLS-1$ stmt0 = DBConnection.getInstance().getConnection() .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt0.setFetchSize(Integer.MIN_VALUE); for (Iterator<?> capIter = items.iterator(); capIter.hasNext();) { Element fieldNode = (Element) capIter.next(); //String name = fieldNode.attributeValue("name"); //$NON-NLS-1$ String desc = fieldNode.attributeValue("desc"); //$NON-NLS-1$ String sql = fieldNode.getTextTrim(); String cond = fieldNode.attributeValue("cond"); String vStr = fieldNode.attributeValue("val"); String isFmt = fieldNode.attributeValue("fmt"); String stop = fieldNode.attributeValue("stop"); boolean doStop = stop != null && stop.equals("true"); String display = fieldNode.attributeValue("display"); boolean doDsp = display == null || display.equals("true"); String paleo = fieldNode.attributeValue("isPaleo"); boolean isPaleo = paleo != null && paleo.equals("true"); if (isPaleo && !isCollectionPaleo) continue; String paleoTypeStr = fieldNode.attributeValue("paleotype"); //$NON-NLS-1$ if (isCollectionPaleo && StringUtils.isNotEmpty(paleoTypeStr)) { if (paleoRelType != paleoLookupHash.get(paleoTypeStr)) { continue; } } sql = ipadExporter.adjustSQL(sql); Object rv = BasicSQLUtils.querySingleObj(sql); Integer retVal = cnvToInt(rv); boolean isError = false; if (retVal != null && StringUtils.isNotEmpty(cond) && StringUtils.isNotEmpty(vStr)) { Integer value = cnvToInt(vStr); if (value != null) { if (cond.equals(">")) { isError = retVal.intValue() > value.intValue(); } else if (cond.equals("=")) { isError = retVal.intValue() == value.intValue(); } else if (cond.equals("<")) { isError = retVal.intValue() < value.intValue(); } } } /* String fontSt = isError ? "<font color='"+(doStop ? "red" : "orange")+"'>" : ""; String fontEn = isError ? "</font>" : ""; if (StringUtils.isNotEmpty(isFmt) && isFmt.equalsIgnoreCase("true")) { sb.append(String.format("<LI>%s%s%s</LI>", fontSt, String.format(desc, retVal), fontEn)); issueCnt++; } else { sb.append(String.format("<LI>%s%s%s</LI>", fontSt, desc, fontEn)); issueCnt++; } */ String fullMsg; if (StringUtils.isNotEmpty(isFmt) && isFmt.equalsIgnoreCase("true")) { fullMsg = String.format(desc, retVal); } else { fullMsg = desc; } if (isError) { if (doStop) { criticalMsgs.add(fullMsg); hasCritical = true; } else { warnMsgs.add(fullMsg); } } else if (doDsp) { okMsgs.add(fullMsg); } issueCnt++; //worker.firePropertyChange(PROGRESS, 0, cnt); } stmt0.close(); sb = new StringBuilder(headHTML); if (issueCnt == 0) { sb.append("<BR><BR>There were no issues to report."); } else { listMsgs(sb, "Passed", okMsgs, "green", true); listMsgs(sb, "Warnings", warnMsgs, "yellow", true); listMsgs(sb, "Critical Errors - Cannot proceed.", criticalMsgs, "red", true); } sb.append(mainFont + "<BR>Verification Complete.<BR><BR></font></body></html>"); htmlPane.setText(sb.toString()); // For external report sb = new StringBuilder("<htmL><head><title>Collection Verification</title></head><body>"); listMsgs(sb, "Passed", okMsgs, "green", false); listMsgs(sb, "Warnings", warnMsgs, "yellow", false); listMsgs(sb, "Critical Errors - Cannot proceed.", criticalMsgs, "red", false); sb.append("</body></html>"); try { TableWriter tblWriter = new TableWriter(reportPath, "Collection Verification Report", true); tblWriter.println(sb.toString()); tblWriter.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (stmt0 != null) stmt0.close(); } catch (Exception ex) { } } } okBtn.setEnabled(!hasCritical); }
From source file:edu.ku.brc.specify.tools.datamodelgenerator.DatamodelGenerator.java
License:Open Source License
/** * Reads in file that provides listing of tables with their respective Id's and default views. * @return boolean true if reading of tableId file was successful. *///from ww w. j a va 2 s .c om private boolean readTableMetadataFromFile(final String tableIdListingFilePath) { Hashtable<String, Boolean> abbrvHashLocal = new Hashtable<String, Boolean>(); log.info("Preparing to read in Table and TableID listing from file: " + tableIdListingFilePath); try { File tableIdFile = new File(tableIdListingFilePath); FileInputStream fileInputStream = new FileInputStream(tableIdFile); SAXReader reader = new SAXReader(); reader.setValidation(false); org.dom4j.Document doc = reader.read(fileInputStream); Element root = doc.getRootElement(); Element dbNode = (Element) root.selectSingleNode("database"); if (dbNode != null) { for (Iterator<?> i = dbNode.elementIterator("table"); i.hasNext();) { Element element = (Element) i.next(); String tablename = element.attributeValue("name"); String defaultView = element.attributeValue("view"); String id = element.attributeValue("id"); String abbrv = XMLHelper.getAttr(element, "abbrev", null); boolean isSearchable = XMLHelper.getAttr(element, "searchable", false); if (StringUtils.isNotEmpty(abbrv)) { if (abbrvHashLocal.get(abbrv) == null) { abbrvHashLocal.put(abbrv, true); } else { throw new RuntimeException( "`abbrev` [" + abbrv + "] or table[" + tablename + "] ids already in use."); } } else { throw new RuntimeException("`abbrev` is missing or empty for table[" + tablename + "]"); } String busRule = ""; Element brElement = (Element) element.selectSingleNode("businessrule"); if (brElement != null) { busRule = brElement.getTextTrim(); } //log.debug("Creating TableMetaData and putting in tblMetaDataHashtable for name: " + tablename + " id: " + id + " defaultview: " + defaultView); TableMetaData tblMetaData = new TableMetaData(id, defaultView, createDisplay(element), createFieldAliases(element), isSearchable, busRule, abbrv); tblMetaDataHash.put(tablename, tblMetaData); for (Iterator<?> ir = element.elementIterator("relationship"); ir.hasNext();) { Element relElement = (Element) ir.next(); String relName = relElement.attributeValue("relationshipname"); boolean isLike = XMLHelper.getAttr(relElement, "likemanytoone", false); tblMetaData.setIsLikeManyToOne(relName, isLike); } } } else { log.debug("Ill-formatted file for reading in Table and TableID listing. Filename:" + tableIdFile.getAbsolutePath()); } fileInputStream.close(); return true; } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DatamodelGenerator.class, ex); ex.printStackTrace(); log.fatal(ex); } return false; }
From source file:edu.ku.brc.specify.web.SpecifyExplorer.java
License:Open Source License
/** * //from w w w . ja v a 2s . c o m */ protected void loadFieldsToSkip() { ClassDisplayInfo.setPackageName(packageName); try { Element root = XMLHelper.readFileToDOM4J( new File(UIRegistry.getDefaultWorkingPath() + File.separator + "config/ClassDisplayInfo.xml")); for (Object cls : root.selectNodes("/classes/class")) { Element clsElement = (Element) cls; String clsName = XMLHelper.getAttr(clsElement, "name", null); if (StringUtils.isNotEmpty(clsName)) { ClassDisplayInfo cdi = null; String linkField = XMLHelper.getAttr(clsElement, "linkfield", ""); String indexField = XMLHelper.getAttr(clsElement, "indexfield", ""); boolean useIdent = XMLHelper.getAttr(clsElement, "useindentity", false); try { String fullName = packageName + clsName; Class<?> clsObj = Class.forName(fullName); Class<?> indexClass = getClassForField(clsObj, indexField); cdi = new ClassDisplayInfo(clsName, clsObj, indexField, indexClass, linkField, useIdent); classHash.put(clsName, cdi); } catch (Exception ex) { ex.printStackTrace(); continue; } Element titleEl = (Element) clsElement.selectSingleNode("title"); if (titleEl != null) { String getterStr = XMLHelper.getAttr(titleEl, "getter", null); if (getterStr != null) { try { Class<?> getterCls = Class.forName(getterStr); TitleGetterIFace titleGetter = (TitleGetterIFace) getterCls.newInstance(); cdi.setTitleGetter(titleGetter); } catch (Exception ex) { } } else { cdi.setTitleField(XMLHelper.getAttr(titleEl, "field", null)); } } for (Object fld : clsElement.selectNodes("skip/field")) { Element fldElement = (Element) fld; boolean isAvailForSearch = XMLHelper.getAttr(fldElement, "search", false); cdi.addSkipped(new FieldDisplayInfo(fldElement.getTextTrim(), false, isAvailForSearch)); } int inx = 0; for (Object fld : clsElement.selectNodes("order/field")) { Element fldElement = (Element) fld; String pickList = XMLHelper.getAttr(clsElement, "pl", ""); //boolean isAvailForSearch = XMLHelper.getAttr(fldElement, "skip", false); boolean isForDisplay = XMLHelper.getAttr(fldElement, "display", true); cdi.addOrdered( new FieldDisplayInfo(inx, fldElement.getTextTrim(), pickList, isForDisplay, true)); inx++; } for (Object fld : clsElement.selectNodes("additional/field")) { Element fldElement = (Element) fld; String name = fldElement.getTextTrim(); String type = XMLHelper.getAttr(fldElement, "type", ""); String label = XMLHelper.getAttr(fldElement, "label", ""); String level = XMLHelper.getAttr(fldElement, "labellevel", ""); AdditionalDisplayField adf = new AdditionalDisplayField(inx, type, label, level, name); cdi.addAdditional(adf); inx++; } for (Object st : clsElement.selectNodes("stats/stat")) { Element statElement = (Element) st; String url = XMLHelper.getAttr(statElement, "url", null); if (StringUtils.isNotEmpty(url)) { cdi.addStat(new StatsDisplayInfo(url, statElement.getTextTrim())); } } } } sortedClassList = new Vector<ClassDisplayInfo>(classHash.values()); Collections.sort(sortedClassList); } catch (Exception ex) { log.error(ex); System.out.println(ex.toString()); } }
From source file:edu.ku.brc.stats.StatsMgr.java
License:Open Source License
/** * // ww w . j av a2 s .co m */ @SuppressWarnings("unchecked") private static void loadStatTooltips() { nameToToolTipHash.clear(); boolean hasResBundle = false; if (StringUtils.isNotEmpty(StatsMgr.getResourceName())) { hasResBundle = UIRegistry.loadAndPushResourceBundle(StatsMgr.getResourceName()) != null; } try { Element dom = getDOM(); if (dom != null) { for (Element element : (List<Element>) (dom.selectNodes("/statistics/stat"))) { String name = XMLHelper.getAttr(element, "name", null); if (name != null) { String tooltipName = null; Element el = (Element) element.selectSingleNode("chartinfo/tooltip"); if (el != null) { tooltipName = el.getTextTrim(); } else { el = (Element) element.selectSingleNode("tooltip"); if (el != null) { tooltipName = el.getTextTrim(); } } if (tooltipName != null) { nameToToolTipHash.put(name, UIRegistry.getResourceString(tooltipName)); } } } } } finally { if (hasResBundle) { UIRegistry.popResourceBundle(); } } }
From source file:edu.ku.brc.stats.StatsMgr.java
License:Open Source License
/** * Looks up statName and creates the appropriate SubPane. * @param statName the name of the stat to be displayed *///from www . j a v a 2 s. co m private JPanel createStatPaneInternal(final String statName) { if (StringUtils.isNotEmpty(resourceName)) { resBundle = UIRegistry.loadAndPushResourceBundle(resourceName); } try { String nameStr; String idStr = null; int inx = statName.indexOf(','); if (inx == -1) { nameStr = statName; } else { nameStr = statName.substring(0, inx); idStr = statName.substring(inx + 4, statName.length()); } Element dom = getDOM(); if (dom != null) { Element element = (Element) dom.selectSingleNode("/statistics/stat[@name='" + nameStr + "']"); if (element != null) { String displayType = element.attributeValue(DISPLAY).toLowerCase(); if (displayType.equalsIgnoreCase(BAR_CHART)) { BarChartPanel barChart = new BarChartPanel(); createChart(nameStr, element, barChart, barChart, barChart); return barChart; } else if (displayType.equalsIgnoreCase(PIE_CHART)) { PieChartPanel pieChart = new PieChartPanel(); createChart(nameStr, element, pieChart, pieChart, pieChart); return pieChart; } else if (displayType.equalsIgnoreCase(FORM)) { createView(element, idStr); } else if (displayType.equals(TABLE)) { Element sqlElement = (Element) element.selectSingleNode("sql"); if (sqlElement == null) { throw new RuntimeException("sql element is null!"); } Element titleElement = (Element) element.selectSingleNode("title"); if (titleElement == null) { throw new RuntimeException("sql element is null!"); } String tooltip = XMLHelper.getAttr((Element) element.selectSingleNode("tooltip"), "tooltip", null); if (tooltip != null) { nameToToolTipHash.put(statName, tooltip); } StatsTask statTask = (StatsTask) ContextMgr.getTaskByName(StatsTask.STATISTICS); SQLQueryPane queryPane = new SQLQueryPane(titleElement.getTextTrim(), statTask, true, true); String sqlStr = sqlElement.getTextTrim(); if (idStr != null) { int substInx = sqlStr.lastIndexOf("%s"); if (substInx > -1) { sqlStr = sqlStr.substring(0, substInx - 1) + idStr + sqlStr.substring(substInx + 2, sqlStr.length()); } else { log.error("Couldn't find the substitue string \"%s\" in [" + sqlStr + "]"); } //sqlStr = String.format(sqlStr, new Object[] {idStr}); } //System.out.println(sqlStr); queryPane.setSQLStr(sqlStr); queryPane.doQuery(); SubPaneMgr.getInstance().addPane(queryPane); } else { // error log.error("Wrong type of display [" + displayType + "] this type is not supported!"); } } } else { log.error("DOM is NULL!!"); } } finally { if (resBundle != null) { UIRegistry.popResourceBundle(); } } return null; }
From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java
License:Open Source License
/** * @param webAssetFile/*w ww . j a v a 2s.com*/ * @return */ private boolean getURLSFromStr(final String data) { try { Element root = XMLHelper.readStrToDOM4J(data); if (root != null) { for (Iterator<?> i = root.elementIterator("url"); i.hasNext();) //$NON-NLS-1$ { Element urlNode = (Element) i.next(); String type = urlNode.attributeValue("type"); //$NON-NLS-1$ String urlStr = urlNode.getTextTrim(); if (type.equals("read")) { readURLStr = urlStr; } else if (type.equals("write")) { writeURLStr = urlStr; } else if (type.equals("delete")) { delURLStr = urlStr; } else if (type.equals("fileget")) { fileGetURLStr = urlStr; } else if (type.equals("getmetadata")) { fileGetMetaDataURLStr = urlStr; } else if (type.equals("testkey")) { testKeyURLStr = urlStr; } } } return StringUtils.isNotEmpty(readURLStr) && StringUtils.isNotEmpty(writeURLStr) && StringUtils.isNotEmpty(delURLStr); } catch (Exception e) { e.printStackTrace(); } return false; }
From source file:edu.umd.cs.findbugs.PluginLoader.java
License:Open Source License
private void loadPluginComponents() throws PluginException { Document pluginDescriptor = getPluginDescriptor(); List<Document> messageCollectionList = getMessageDocuments(); List<Node> cloudNodeList = XMLUtil.selectNodes(pluginDescriptor, "/FindbugsPlugin/Cloud"); for (Node cloudNode : cloudNodeList) { String cloudClassname = cloudNode.valueOf("@cloudClass"); String cloudId = cloudNode.valueOf("@id"); String usernameClassname = cloudNode.valueOf("@usernameClass"); boolean onlineStorage = Boolean.valueOf(cloudNode.valueOf("@onlineStorage")); String propertiesLocation = cloudNode.valueOf("@properties"); boolean disabled = Boolean.valueOf(cloudNode.valueOf("@disabled")) && !cloudId.equals(CloudFactory.DEFAULT_CLOUD); if (disabled) { continue; }//from w w w . ja v a 2 s. c o m boolean hidden = Boolean.valueOf(cloudNode.valueOf("@hidden")) && !cloudId.equals(CloudFactory.DEFAULT_CLOUD); Class<? extends Cloud> cloudClass = getClass(classLoader, cloudClassname, Cloud.class); Class<? extends NameLookup> usernameClass = getClass(classLoader, usernameClassname, NameLookup.class); Node cloudMessageNode = findMessageNode(messageCollectionList, "/MessageCollection/Cloud[@id='" + cloudId + "']", "Missing Cloud description for cloud " + cloudId); String description = getChildText(cloudMessageNode, "Description").trim(); String details = getChildText(cloudMessageNode, "Details").trim(); PropertyBundle properties = new PropertyBundle(); if (propertiesLocation != null && propertiesLocation.length() > 0) { URL properiesURL = classLoader.getResource(propertiesLocation); if (properiesURL == null) { continue; } properties.loadPropertiesFromURL(properiesURL); } List<Node> propertyNodes = XMLUtil.selectNodes(cloudNode, "Property"); for (Node node : propertyNodes) { String key = node.valueOf("@key"); String value = node.getText().trim(); properties.setProperty(key, value); } CloudPlugin cloudPlugin = new CloudPluginBuilder().setFindbugsPluginId(plugin.getPluginId()) .setCloudid(cloudId).setClassLoader(classLoader).setCloudClass(cloudClass) .setUsernameClass(usernameClass).setHidden(hidden).setProperties(properties) .setDescription(description).setDetails(details).setOnlineStorage(onlineStorage) .createCloudPlugin(); plugin.addCloudPlugin(cloudPlugin); } // Create PluginComponents try { List<Node> componentNodeList = XMLUtil.selectNodes(pluginDescriptor, "/FindbugsPlugin/PluginComponent"); for (Node componentNode : componentNodeList) { @DottedClassName String componentKindname = componentNode.valueOf("@componentKind"); if (componentKindname == null) { throw new PluginException( "Missing @componentKind for " + plugin.getPluginId() + " loaded from " + loadedFrom); } @DottedClassName String componentClassname = componentNode.valueOf("@componentClass"); if (componentClassname == null) { throw new PluginException("Missing @componentClassname for " + plugin.getPluginId() + " loaded from " + loadedFrom); } String componentId = componentNode.valueOf("@id"); if (componentId == null) { throw new PluginException( "Missing @id for " + plugin.getPluginId() + " loaded from " + loadedFrom); } try { String propertiesLocation = componentNode.valueOf("@properties"); boolean disabled = Boolean.valueOf(componentNode.valueOf("@disabled")); Node filterMessageNode = findMessageNode(messageCollectionList, "/MessageCollection/PluginComponent[@id='" + componentId + "']", "Missing Cloud description for PluginComponent " + componentId); String description = getChildText(filterMessageNode, "Description").trim(); String details = getChildText(filterMessageNode, "Details").trim(); PropertyBundle properties = new PropertyBundle(); if (propertiesLocation != null && propertiesLocation.length() > 0) { URL properiesURL = classLoaderForResources.getResource(propertiesLocation); if (properiesURL == null) { AnalysisContext.logError("Could not load properties for " + plugin.getPluginId() + " component " + componentId + " from " + propertiesLocation); continue; } properties.loadPropertiesFromURL(properiesURL); } List<Node> propertyNodes = XMLUtil.selectNodes(componentNode, "Property"); for (Node node : propertyNodes) { String key = node.valueOf("@key"); String value = node.getText(); properties.setProperty(key, value); } Class<?> componentKind = classLoader.loadClass(componentKindname); loadComponentPlugin(plugin, componentKind, componentClassname, componentId, disabled, description, details, properties); } catch (RuntimeException e) { AnalysisContext.logError("Unable to load ComponentPlugin " + componentId + " : " + componentClassname + " implementing " + componentKindname, e); } } // Create FindBugsMains if (!FindBugs.isNoMains()) { List<Node> findBugsMainList = XMLUtil.selectNodes(pluginDescriptor, "/FindbugsPlugin/FindBugsMain"); for (Node main : findBugsMainList) { String className = main.valueOf("@class"); if (className == null) { throw new PluginException("Missing @class for FindBugsMain in plugin" + plugin.getPluginId() + " loaded from " + loadedFrom); } String cmd = main.valueOf("@cmd"); if (cmd == null) { throw new PluginException("Missing @cmd for for FindBugsMain in plugin " + plugin.getPluginId() + " loaded from " + loadedFrom); } String kind = main.valueOf("@kind"); boolean analysis = Boolean.valueOf(main.valueOf("@analysis")); Element mainMessageNode = (Element) findMessageNode(messageCollectionList, "/MessageCollection/FindBugsMain[@cmd='" + cmd // + " and @class='" + className + "']/Description", "Missing FindBugsMain description for cmd " + cmd); String description = mainMessageNode.getTextTrim(); try { Class<?> mainClass = classLoader.loadClass(className); plugin.addFindBugsMain(mainClass, cmd, description, kind, analysis); } catch (Exception e) { String msg = "Unable to load FindBugsMain " + cmd + " : " + className + " in plugin " + plugin.getPluginId() + " loaded from " + loadedFrom; PluginException e2 = new PluginException(msg, e); AnalysisContext.logError(msg, e2); } } } List<Node> detectorNodeList = XMLUtil.selectNodes(pluginDescriptor, "/FindbugsPlugin/Detector"); int detectorCount = 0; for (Node detectorNode : detectorNodeList) { String className = detectorNode.valueOf("@class"); String speed = detectorNode.valueOf("@speed"); String disabled = detectorNode.valueOf("@disabled"); String reports = detectorNode.valueOf("@reports"); String requireJRE = detectorNode.valueOf("@requirejre"); String hidden = detectorNode.valueOf("@hidden"); if (speed == null || speed.length() == 0) { speed = "fast"; } // System.out.println("Found detector: class="+className+", disabled="+disabled); // Create DetectorFactory for the detector Class<?> detectorClass = null; if (!FindBugs.isNoAnalysis()) { detectorClass = classLoader.loadClass(className); if (!Detector.class.isAssignableFrom(detectorClass) && !Detector2.class.isAssignableFrom(detectorClass)) { throw new PluginException( "Class " + className + " does not implement Detector or Detector2"); } } DetectorFactory factory = new DetectorFactory(plugin, className, detectorClass, !"true".equals(disabled), speed, reports, requireJRE); if (Boolean.valueOf(hidden).booleanValue()) { factory.setHidden(true); } factory.setPositionSpecifiedInPluginDescriptor(detectorCount++); plugin.addDetectorFactory(factory); // Find Detector node in one of the messages files, // to get the detail HTML. Node node = findMessageNode(messageCollectionList, "/MessageCollection/Detector[@class='" + className + "']/Details", "Missing Detector description for detector " + className); Element details = (Element) node; String detailHTML = details.getText(); StringBuilder buf = new StringBuilder(); buf.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); buf.append("<HTML><HEAD><TITLE>Detector Description</TITLE></HEAD><BODY>\n"); buf.append(detailHTML); buf.append("</BODY></HTML>\n"); factory.setDetailHTML(buf.toString()); } } catch (ClassNotFoundException e) { throw new PluginException("Could not instantiate detector class: " + e, e); } // Create ordering constraints Node orderingConstraintsNode = pluginDescriptor.selectSingleNode("/FindbugsPlugin/OrderingConstraints"); if (orderingConstraintsNode != null) { // Get inter-pass and intra-pass constraints List<Element> elements = XMLUtil.selectNodes(orderingConstraintsNode, "./SplitPass|./WithinPass"); for (Element constraintElement : elements) { // Create the selectors which determine which detectors are // involved in the constraint DetectorFactorySelector earlierSelector = getConstraintSelector(constraintElement, plugin, "Earlier"); DetectorFactorySelector laterSelector = getConstraintSelector(constraintElement, plugin, "Later"); // Create the constraint DetectorOrderingConstraint constraint = new DetectorOrderingConstraint(earlierSelector, laterSelector); // Keep track of which constraints are single-source constraint.setSingleSource(earlierSelector instanceof SingleDetectorFactorySelector); // Add the constraint to the plugin if ("SplitPass".equals(constraintElement.getName())) { plugin.addInterPassOrderingConstraint(constraint); } else { plugin.addIntraPassOrderingConstraint(constraint); } } } // register global Category descriptions List<Node> categoryNodeListGlobal = XMLUtil.selectNodes(pluginDescriptor, "/FindbugsPlugin/BugCategory"); for (Node categoryNode : categoryNodeListGlobal) { String key = categoryNode.valueOf("@category"); if ("".equals(key)) { throw new PluginException("BugCategory element with missing category attribute"); } BugCategory bc = plugin.addOrCreateBugCategory(key); boolean hidden = Boolean.valueOf(categoryNode.valueOf("@hidden")); if (hidden) { bc.setHidden(hidden); } } for (Document messageCollection : messageCollectionList) { List<Node> categoryNodeList = XMLUtil.selectNodes(messageCollection, "/MessageCollection/BugCategory"); if (DEBUG) { System.out.println("found " + categoryNodeList.size() + " categories in " + plugin.getPluginId()); } for (Node categoryNode : categoryNodeList) { String key = categoryNode.valueOf("@category"); if ("".equals(key)) { throw new PluginException("BugCategory element with missing category attribute"); } BugCategory bc = plugin.addOrCreateBugCategory(key); String shortDesc = getChildText(categoryNode, "Description"); bc.setShortDescription(shortDesc); try { String abbrev = getChildText(categoryNode, "Abbreviation"); if (bc.getAbbrev() == null) { bc.setAbbrev(abbrev); if (DEBUG) { System.out.println("category " + key + " abbrev -> " + abbrev); } } else if (DEBUG) { System.out.println( "rejected abbrev '" + abbrev + "' for category " + key + ": " + bc.getAbbrev()); } } catch (PluginException pe) { if (DEBUG) { System.out.println("missing Abbreviation for category " + key + "/" + shortDesc); // do nothing else -- Abbreviation is required, but handle // its omission gracefully } } try { String details = getChildText(categoryNode, "Details"); if (bc.getDetailText() == null) { bc.setDetailText(details); if (DEBUG) { System.out.println("category " + key + " details -> " + details); } } else if (DEBUG) { System.out.println("rejected details [" + details + "] for category " + key + ": [" + bc.getDetailText() + ']'); } } catch (PluginException pe) { // do nothing -- LongDescription is optional } } } // Create BugPatterns List<Node> bugPatternNodeList = XMLUtil.selectNodes(pluginDescriptor, "/FindbugsPlugin/BugPattern"); for (Node bugPatternNode : bugPatternNodeList) { String type = bugPatternNode.valueOf("@type"); String abbrev = bugPatternNode.valueOf("@abbrev"); String category = bugPatternNode.valueOf("@category"); boolean experimental = Boolean.parseBoolean(bugPatternNode.valueOf("@experimental")); // Find the matching element in messages.xml (or translations) String query = "/MessageCollection/BugPattern[@type='" + type + "']"; Node messageNode = findMessageNode(messageCollectionList, query, "messages.xml missing BugPattern element for type " + type); Node bugsUrlNode = messageNode.getDocument() .selectSingleNode("/MessageCollection/Plugin/" + (experimental ? "AllBugsUrl" : "BugsUrl")); String bugsUrl = bugsUrlNode == null ? null : bugsUrlNode.getText(); String shortDesc = getChildText(messageNode, "ShortDescription"); String longDesc = getChildText(messageNode, "LongDescription"); String detailText = getChildText(messageNode, "Details"); int cweid = 0; try { String cweString = bugPatternNode.valueOf("@cweid"); if (cweString.length() > 0) { cweid = Integer.parseInt(cweString); } } catch (RuntimeException e) { assert true; // ignore } BugPattern bugPattern = new BugPattern(type, abbrev, category, experimental, shortDesc, longDesc, detailText, bugsUrl, cweid); try { String deprecatedStr = bugPatternNode.valueOf("@deprecated"); boolean deprecated = deprecatedStr.length() > 0 && Boolean.valueOf(deprecatedStr).booleanValue(); if (deprecated) { bugPattern.setDeprecated(deprecated); } } catch (RuntimeException e) { assert true; // ignore } plugin.addBugPattern(bugPattern); } // Create BugCodes Set<String> definedBugCodes = new HashSet<String>(); for (Document messageCollection : messageCollectionList) { List<Node> bugCodeNodeList = XMLUtil.selectNodes(messageCollection, "/MessageCollection/BugCode"); for (Node bugCodeNode : bugCodeNodeList) { String abbrev = bugCodeNode.valueOf("@abbrev"); if ("".equals(abbrev)) { throw new PluginException("BugCode element with missing abbrev attribute"); } if (definedBugCodes.contains(abbrev)) { continue; } String description = bugCodeNode.getText(); String query = "/FindbugsPlugin/BugCode[@abbrev='" + abbrev + "']"; Node fbNode = pluginDescriptor.selectSingleNode(query); int cweid = 0; if (fbNode != null) { try { cweid = Integer.parseInt(fbNode.valueOf("@cweid")); } catch (RuntimeException e) { assert true; // ignore } } BugCode bugCode = new BugCode(abbrev, description, cweid); plugin.addBugCode(bugCode); definedBugCodes.add(abbrev); } } // If an engine registrar is specified, make a note of its classname Node node = pluginDescriptor.selectSingleNode("/FindbugsPlugin/EngineRegistrar"); if (node != null) { String engineClassName = node.valueOf("@class"); if (engineClassName == null) { throw new PluginException("EngineRegistrar element with missing class attribute"); } try { Class<?> engineRegistrarClass = classLoader.loadClass(engineClassName); if (!IAnalysisEngineRegistrar.class.isAssignableFrom(engineRegistrarClass)) { throw new PluginException( engineRegistrarClass + " does not implement IAnalysisEngineRegistrar"); } plugin.setEngineRegistrarClass( engineRegistrarClass.<IAnalysisEngineRegistrar>asSubclass(IAnalysisEngineRegistrar.class)); } catch (ClassNotFoundException e) { throw new PluginException("Could not instantiate analysis engine registrar class: " + e, e); } } try { URL bugRankURL = getResource(BugRanker.FILENAME); if (bugRankURL == null) { // see // https://sourceforge.net/tracker/?func=detail&aid=2816102&group_id=96405&atid=614693 // plugin can not have bugrank.txt. In this case, an empty // bugranker will be created if (DEBUG) { System.out.println("No " + BugRanker.FILENAME + " for plugin " + plugin.getPluginId()); } } BugRanker ranker = new BugRanker(bugRankURL); plugin.setBugRanker(ranker); } catch (IOException e) { throw new PluginException("Couldn't parse \"" + BugRanker.FILENAME + "\"", e); } }
From source file:edu.wustl.cab2b.common.util.ResultConfigurationParser.java
License:BSD License
/** * Method to parse Attribute values under entity tag and store them in map *///from ww w .j av a 2s . co m private void setElementData(List<Element> elementList, String parentMapKey) { for (Element entityElement : elementList) { String mapKey = parentMapKey; if (entityElement.attributeValue(NAME) != null) { mapKey = mapKey + KEY_DELIM + entityElement.attributeValue(NAME); } Element resultTransformer = entityElement.element(RESULT_TRANSFORMER); Element resultRenderer = entityElement.element(RESULT_RENDERER); Element dataListTransformer = entityElement.element(DATALIST_TRANSFORMERS); String resultTransformerValue = null; String resultRendererValue = null; if (resultTransformer != null) { resultTransformerValue = resultTransformer.getTextTrim(); } if (resultRenderer != null) { resultRendererValue = resultRenderer.getTextTrim(); } DataListTransformer dataListTransformerValue = null; if (dataListTransformer != null) { Element saverElem = dataListTransformer.element(DATALIST_SAVER); Element retrieverElem = dataListTransformer.element(DATALIST_RETRIEVER); dataListTransformerValue = new DataListTransformer(saverElem.getTextTrim(), retrieverElem.getTextTrim()); } EntityTransformerInfo entityAttributes = new EntityTransformerInfo(resultTransformerValue, resultRendererValue, dataListTransformerValue); applicationEntityNameMap.put(mapKey, entityAttributes); } }
From source file:edu.wustl.cab2b.server.multimodelcategory.MmcValidator.java
License:BSD License
/** * Gets paths/*from w w w.ja v a 2 s . co m*/ */ public void getPathsForPair(String pairsFileName, String consoleFile) { List<ClassPair> pairs = new ArrayList<ClassPair>(); try { FileInputStream fileInputStream = new FileInputStream(pairsFileName); Document document = new SAXReader().read(fileInputStream); Element pairsElement = document.getRootElement(); List<Element> pairElements = (List<Element>) pairsElement.elements("pair"); for (Element pairElement : pairElements) { Element source = pairElement.element("source"); Element target = pairElement.element("target"); pairs.add(new ClassPair(source.getTextTrim(), target.getTextTrim())); } } catch (FileNotFoundException e) { throw new RuntimeException("Given Pairs XML file not found: " + pairsFileName, e); } catch (DocumentException e) { throw new RuntimeException("Unable to parse pairs XML file: " + pairsFileName, e); } /* pairs.add(new ClassPair("edu.wustl.catissuecore.domain.Participant", "edu.wustl.catissuecore.domain.Race")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.Participant", "edu.wustl.catissuecore.domain.SpecimenCollectionGroup")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.TissueSpecimen","edu.wustl.catissuecore.domain.EmbeddedEventParameters")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.TissueSpecimen","edu.wustl.catissuecore.domain.FixedEventParameters")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.TissueSpecimen","edu.wustl.catissuecore.domain.FrozenEventParameters")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.MolecularSpecimen","edu.wustl.catissuecore.domain.FrozenEventParameters")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.CellSpecimen","edu.wustl.catissuecore.domain.FrozenEventParameters")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.CellSpecimen","edu.wustl.catissuecore.domain.FixedEventParameters")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.FluidSpecimen","edu.wustl.catissuecore.domain.FrozenEventParameters")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.SpecimenCollectionGroup","edu.wustl.catissuecore.domain.TissueSpecimen")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.SpecimenCollectionGroup","edu.wustl.catissuecore.domain.MolecularSpecimen")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.SpecimenCollectionGroup","edu.wustl.catissuecore.domain.CellSpecimen")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.SpecimenCollectionGroup", "edu.wustl.catissuecore.domain.FluidSpecimen")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.CollectionProtocolRegistration", "edu.wustl.catissuecore.domain.User")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.CollectionProtocolRegistration", "edu.wustl.catissuecore.domain.CollectionProtocol")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.CollectionProtocol", "edu.wustl.catissuecore.domain.User")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.TissueSpecimen", "edu.wustl.catissuecore.domain.QuantityInMicrogram")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.Participant", "edu.wustl.catissuecore.domain.CollectionProtocolRegistration")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.TissueSpecimen", "edu.wustl.catissuecore.domain.SpecimenCharacteristics")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.MolecularSpecimen", "edu.wustl.catissuecore.domain.SpecimenCharacteristics")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.CellSpecimen", "edu.wustl.catissuecore.domain.SpecimenCharacteristics")); pairs.add(new ClassPair("edu.wustl.catissuecore.domain.FluidSpecimen", "edu.wustl.catissuecore.domain.SpecimenCharacteristics")); pairs.add(new ClassPair("gov.nih.nci.caarray.domain.sample.Sample", "gov.nih.nci.caarray.domain.hybridization.Hybridization")); pairs.add(new ClassPair("gov.nih.nci.caarray.domain.hybridization.Hybridization", "gov.nih.nci.caarray.domain.data.RawArrayData")); pairs.add(new ClassPair("gov.nih.nci.caarray.domain.data.RawArrayData", "gov.nih.nci.caarray.domain.project.Experiment")); pairs.add(new ClassPair("gov.nih.nci.caarray.domain.project.Experimen", "gov.nih.nci.caarray.domain.sample.Source")); pairs.add(new ClassPair("gov.nih.nci.caarray.domain.sample.Source", "gov.nih.nci.caarray.domain.vocabulary.Term")); pairs.add(new ClassPair("gov.nih.nci.caarray.domain.project.Experiment", "edu.georgetown.pir.Organism")); pairs.add(new ClassPair("gov.nih.nci.caarray.domain.project.Experimen", "gov.nih.nci.caarray.domain.array.ArrayDesign")); pairs.add(new ClassPair("gov.nih.nci.caarray.domain.array.ArrayDesign", "gov.nih.nci.caarray.domain.contact.Organization")); pairs.add(new ClassPair("gov.nih.nci.caarray.domain.project.Experiment", "gov.nih.nci.caarray.domain.sample.Source")); pairs.add(new ClassPair("gov.nih.nci.caarray.domain.sample.Source", "gov.nih.nci.caarray.domain.vocabulary.Term")); pairs.add(new ClassPair("gov.nih.nci.caarray.domain.project.Experiment", "gov.nih.nci.caarray.domain.array.ArrayDesign")); */ try { redirectConsoleToFile(consoleFile); } catch (FileNotFoundException e) { throw new RuntimeException("Given path for console file in incorrect." + pairsFileName, e); } Collection<EntityGroupInterface> groups = cache.getEntityGroups(); for (EntityGroupInterface eg : groups) { for (ClassPair pair : pairs) { getPaths(eg, pair); } } }
From source file:eu.delving.metadata.RecordValidator.java
License:EUPL
private boolean validateElement(Element element, Path path, List<String> problems, Set<String> entries, Map<Path, Counter> counters) { path.push(Tag.create(element.getNamespacePrefix(), element.getName())); boolean hasElements = false; Iterator walk = element.elementIterator(); while (walk.hasNext()) { Element subelement = (Element) walk.next(); boolean remove = validateElement(subelement, path, problems, entries, counters); if (remove) { walk.remove();/*ww w. java 2 s.co m*/ } hasElements = true; } if (!hasElements) { boolean fieldRemove = validatePath(element.getTextTrim(), path, problems, entries, counters); path.pop(); return fieldRemove; } path.pop(); return false; }