List of usage examples for org.dom4j Element attributeIterator
Iterator<Attribute> attributeIterator();
From source file:darks.orm.core.config.sqlmap.DMLConfigReader.java
License:Apache License
/** * Read and parse update tags/*from w w w .j a v a 2 s . c om*/ * * @param element Update tag * @param namesp namespace * @throws Exception */ private DMLData readUpdate(Element element, String namesp) throws Exception { if (!"".equals(namesp)) { if (!namesp.endsWith(".")) namesp += "."; } DMLData dmlData = new DMLData(); String sql = element.getTextTrim(); dmlData.setType(DMLType.Update); DMLUpdateData updateData = new DMLUpdateData(); RootTag rootTag = new RootTag(); parseSqlTag(rootTag, element, namesp); dmlData.setSqlTag(rootTag); updateData.setSql(sql); for (Iterator<Attribute> it = element.attributeIterator(); it.hasNext();) { try { Attribute at = it.next(); String name = at.getName().trim(); String value = at.getValue().trim(); if ("id".equalsIgnoreCase(name)) { dmlData.setId(value); } } catch (Exception e) { logger.error(e.getMessage(), e); } } if (dmlData.getId() == null) return null; AspectData aspectData = parseAspectXml(element); updateData.setAspectData(aspectData); dmlData.setUpdateData(updateData); sqlMapConfig.addDMLData(namesp + dmlData.getId(), dmlData); return dmlData; }
From source file:de.innovationgate.wga.config.WGAConfigurationMigrator.java
License:Apache License
public static MigrationResult createFromWGAXML(InputStream wgaXML, String configPath) throws DocumentException, IOException, NoSuchAlgorithmException { MigrationResult migrationResult = new MigrationResult(); migrationResult.logInfo("Starting migration of 'wga.xml'."); SAXReader reader = new SAXReader(); Document doc = reader.read(wgaXML); WGAXML.normalize(doc);/*from ww w . j a va2s. com*/ WGAConfiguration config = new WGAConfiguration(); config.createDefaultResources(); // Add a file system design source that will register all design directories that are not at default location DesignSource fsDesignSource = new DesignSource( "de.innovationgate.wgpublisher.design.fs.FileSystemDesignSource"); fsDesignSource.setDescription("Migrated design directories that are not in the default folder"); fsDesignSource.setTitle("Migrated design directories"); String dir = System.getProperty(WGAConfiguration.SYSPROP_DESIGN_ROOT); if (dir == null) { dir = WGAConfiguration.DEFAULT_DESIGNROOT; } fsDesignSource.getOptions().put("Path", dir); config.getDesignConfiguration().getDesignSources().add(fsDesignSource); Element root = doc.getRootElement(); Iterator administrators = root.element("administrators").elementIterator("administrator"); while (administrators.hasNext()) { Element adminElement = (Element) administrators.next(); String name = adminElement.attributeValue("name"); String password = adminElement.attributeValue("password"); if (!adminElement.attributeValue("encode", "").equals("hash")) { password = WGUtils.hashPassword(password); } Administrator admin = new Administrator(name, password, SHA1HashingScheme.NAME); migrationResult.logInfo("Migrating admin login '" + name + "'."); config.add(admin); } migrationResult.logInfo("Migrating general configuration."); Element configuration = root.element("configuration"); Element defaultDB = configuration.element("defaultdb"); config.setDefaultDatabase(defaultDB.attributeValue("key")); config.setFavicon(defaultDB.attributeValue("favicon")); config.setCacheExpirationForStaticResources(Integer.parseInt(defaultDB.attributeValue("staticexpiration"))); config.setUsePermanentRedirect( Boolean.parseBoolean(defaultDB.attributeValue("permanentredirect", "false"))); Element warnings = configuration.element("warnings"); config.setWarningsEnabled(Boolean.parseBoolean(warnings.attributeValue("enabled"))); config.setWarningsOutputOnConsole(Boolean.parseBoolean(warnings.attributeValue("consoleOuput"))); config.setWarningsOutputViaTML( Boolean.parseBoolean(warnings.attributeValue("pageOutput")) == true ? Constants.WARNINGS_TML_AS_HTML : Constants.WARNINGS_TML_OFF); Element tml = configuration.element("tml"); String enc = tml.attributeValue("characterEncoding", null); if (enc != null && !enc.trim().equals("")) { config.setCharacterEncoding(enc); } Element tmlHeader = tml.element("tmlheader"); if (tmlHeader != null) { String tmlBufferStr = tmlHeader.attributeValue("buffer").toLowerCase(); if (tmlBufferStr.indexOf("kb") != -1) { tmlBufferStr = tmlBufferStr.substring(0, tmlBufferStr.indexOf("kb")); } try { int tmlBuffer = Integer.parseInt(tmlBufferStr); config.setTmlBuffer(tmlBuffer); } catch (NumberFormatException e) { migrationResult.logError( "Unable to parse WebTML output buffer size: " + tmlBufferStr + ". Falling back to default: " + WGAConfiguration.SERVEROPTIONDEFAULT_WEBTML_OUTPUT_BUFFER); } config.setTmlHeader(tmlHeader.getText()); } Element features = configuration.element("features"); /* Deprecated in WGA5 config.setAuthoringApplicationsEnabled(Boolean.parseBoolean(features.attributeValue("bi"))); config.setStartPageEnabled(Boolean.parseBoolean(features.attributeValue("startpage"))); */ config.setAdminPageEnabled(Boolean.parseBoolean(features.attributeValue("adminpage"))); config.setWebservicesEnabled(Boolean.parseBoolean(features.attributeValue("webservice"))); config.clearAdminToolsPortRestrictions(); String port = features.attributeValue("adminport"); if (port != null && !port.trim().equals("")) { config.addAdminToolsPortRestriction(Integer.parseInt(port)); } config.clearAuthoringDesignAccessPortRestrictions(); port = features.attributeValue("authoringport"); if (port != null && !port.trim().equals("")) { config.addAuthoringDesignAccessPortRestriction(Integer.parseInt(port)); } Element applog = configuration.element("applog"); config.setApplicationLogLevel(applog.attributeValue("level")); config.setApplicationLogDirectory(applog.attributeValue("dir", null)); Iterator listeners = configuration.element("listeners").elementIterator("listener"); while (listeners.hasNext()) { Element listener = (Element) listeners.next(); config.getCoreEventListeners().add(listener.attributeValue("class")); } // personalisation agent exclusions Element personalisation = configuration.element("personalisation"); Iterator agentExclusions = personalisation.elementIterator("agentexclusion"); while (agentExclusions.hasNext()) { Element agentExclusion = (Element) agentExclusions.next(); config.getPersonalisationConfiguration().getPersonalisationAgentExclusions() .add(agentExclusion.attributeValue("name")); } migrationResult.logInfo("Migrating global lucene configuration."); Element lucene = configuration.element("lucene"); config.getLuceneManagerConfiguration().setEnabled(Boolean.parseBoolean(lucene.attributeValue("enabled"))); config.getLuceneManagerConfiguration() .setPath(System.getProperty(WGAConfiguration.SYSPROP_LUCENE_ROOT, lucene.attributeValue("dir"))); config.getLuceneManagerConfiguration() .setMaxBooleanClauseCount(Integer.parseInt(lucene.attributeValue("booleanQueryMaxClauseCount"))); config.getLuceneManagerConfiguration() .setMaxDocsPerDBSession(Integer.parseInt(lucene.attributeValue("maxDocsPerDBSession"))); if (WGUtils.isEmpty(config.getLuceneManagerConfiguration().getPath())) { File lucenePath = new File(configPath, "lucene"); if (!lucenePath.exists()) { lucenePath.mkdir(); } config.getLuceneManagerConfiguration().setPath(lucenePath.getAbsolutePath()); } migrationResult.logInfo("Migrating global designsync configuration."); Element designSync = configuration.element("designsync"); config.getDesignConfiguration().setDefaultEncoding(designSync.attributeValue("fileEncoding")); config.getDesignConfiguration().setPollingInterval(Integer.parseInt(designSync.attributeValue("interval"))); config.getDesignConfiguration() .setThrottlingEnabled(Boolean.parseBoolean(designSync.attributeValue("throttling"))); config.getDesignConfiguration() .setThrottlingPeriodMinutes(Integer.parseInt(designSync.attributeValue("throttlingactivation"))); Iterator fileExclusions = designSync.elementIterator("fileexclusion"); while (fileExclusions.hasNext()) { Element fileExclusion = (Element) fileExclusions.next(); config.getDesignConfiguration().getFileExclusions().add(fileExclusion.attributeValue("name")); } migrationResult.logInfo("Migrating global database options."); Iterator defaultDBOptions = configuration.element("defaultdboptions").elementIterator("option"); while (defaultDBOptions.hasNext()) { Element option = (Element) defaultDBOptions.next(); config.getGlobalDatabaseOptions().put(option.attributeValue("name"), option.attributeValue("value")); } migrationResult.logInfo("Migrating global publishing options."); Iterator defaultPublisherOptions = configuration.element("defaultpublisheroptions") .elementIterator("option"); while (defaultPublisherOptions.hasNext()) { Element option = (Element) defaultPublisherOptions.next(); config.getGlobalPublisherOptions().put(option.attributeValue("name"), option.attributeValue("value")); } migrationResult.logInfo("Migrating global mail configuration."); Element mailconfig = configuration.element("mailconfig"); config.getMailConfiguration().setServer(mailconfig.attributeValue("mailHost")); config.getMailConfiguration().setUser(mailconfig.attributeValue("mailUser")); config.getMailConfiguration().setPassword(mailconfig.attributeValue("mailPassword")); config.getMailConfiguration().setFromAddress(mailconfig.attributeValue("mailFrom")); config.getMailConfiguration().setToAddress(mailconfig.attributeValue("mailTo")); config.getMailConfiguration().setEnableAdminNotifications( Boolean.parseBoolean(mailconfig.attributeValue("enableAdminNotifications"))); config.setRootURL(mailconfig.attributeValue("mailWGARootURL")); Element domains = root.element("domains"); migrateDomains(migrationResult, config, domains); // create dbservers & content dbs migrationResult.logInfo("Starting migration of content dbs ..."); int mysqlServerCount = 0; int hsqlServerCount = 0; int notesServerCount = 0; int oracleServerCount = 0; int jdbcServerCount = 0; int dummyServerCount = 0; Map<String, DatabaseServer> dbServersByUniqueID = new HashMap<String, DatabaseServer>(); Iterator dbPaths = root.selectNodes("//contentdb/dbpath").iterator(); while (dbPaths.hasNext()) { Element dbPathElement = (Element) dbPaths.next(); String dbType = dbPathElement.getParent().elementTextTrim("type"); String path = dbPathElement.getTextTrim(); String user = determineUser(dbPathElement.getParent()); String password = determinePassword(dbPathElement.getParent()); // migration for mysql dbs if (path.startsWith("jdbc:mysql")) { mysqlServerCount = createMySqlServerAndDB(configPath, migrationResult, config, mysqlServerCount, dbServersByUniqueID, dbPathElement, path, user, password, false, fsDesignSource); } else if (dbType.contains("domino.remote")) { notesServerCount = createDominoServerAndDB(configPath, migrationResult, config, notesServerCount, dbServersByUniqueID, dbPathElement, path, user, password, false, fsDesignSource); } else if (dbType.contains("de.innovationgate.webgate.api.hsql") || path.startsWith("jdbc:hsqldb:")) { hsqlServerCount = createHSQLServerAndDB(configPath, migrationResult, config, hsqlServerCount, dbServersByUniqueID, dbPathElement, path, user, password, false, fsDesignSource); } else if (path.startsWith("jdbc:oracle:")) { oracleServerCount = createOracleServerAndDB(configPath, migrationResult, config, oracleServerCount, dbServersByUniqueID, dbPathElement, path, user, password, false, fsDesignSource); } else if (dbType.contains(".jdbc.")) { jdbcServerCount = createJDBCServerAndDB(configPath, migrationResult, config, jdbcServerCount, dbServersByUniqueID, dbPathElement, path, user, password, false, fsDesignSource); } else { // migrate other dbs with same user/password combination to // "other sources" server DatabaseServer server = new DatabaseServer( "de.innovationgate.webgate.api.servers.OtherSourcesDatabaseServer"); server.setUid(WGAConfiguration.SINGLETON_SERVER_PREFIX + "de.innovationgate.webgate.api.servers.OtherSourcesDatabaseServer"); addContentDB(config, dbPathElement.getParent(), server, migrationResult, configPath, fsDesignSource, path); } } // migrate personalisation dbs migrationResult.logInfo("Starting migration of personalisation dbs ..."); Iterator persDBPaths = root.selectNodes("//personalisationdb/dbpath").iterator(); while (persDBPaths.hasNext()) { Element dbPathElement = (Element) persDBPaths.next(); String dbType = dbPathElement.getParent().elementTextTrim("type"); String domain = dbPathElement.getParent().elementTextTrim("domain"); String path = dbPathElement.getTextTrim(); String user = determineUser(dbPathElement.getParent()); String password = determinePassword(dbPathElement.getParent()); // migration for mysql dbs if (path.startsWith("jdbc:mysql")) { mysqlServerCount = createMySqlServerAndDB(configPath, migrationResult, config, mysqlServerCount, dbServersByUniqueID, dbPathElement, path, user, password, true, fsDesignSource); } else if (dbType.contains("domino.remote")) { mysqlServerCount = createDominoServerAndDB(configPath, migrationResult, config, notesServerCount, dbServersByUniqueID, dbPathElement, path, user, password, true, fsDesignSource); } else if (dbType.contains("de.innovationgate.webgate.api.hsql")) { hsqlServerCount = createHSQLServerAndDB(configPath, migrationResult, config, hsqlServerCount, dbServersByUniqueID, dbPathElement, path, user, password, true, fsDesignSource); } else if (path.startsWith("jdbc:oracle:")) { oracleServerCount = createOracleServerAndDB(configPath, migrationResult, config, oracleServerCount, dbServersByUniqueID, dbPathElement, path, user, password, false, fsDesignSource); } else { // migrate other dbs to "other sources" server // migrate other dbs with same user/password combination to // "other sources" server DatabaseServer server = new DatabaseServer( "de.innovationgate.webgate.api.servers.OtherSourcesDatabaseServer"); server.setUid(WGAConfiguration.SINGLETON_SERVER_PREFIX + "de.innovationgate.webgate.api.servers.OtherSourcesDatabaseServer"); addPersonalisationDB(config, dbPathElement.getParent(), server, migrationResult, null); } } // migrate first found access log migrationResult.logWarning("Accessloggers will not be migrated."); // migrate libraries migrationResult.logInfo("Migrating library mappings"); String libraries = root.element("mappings").attributeValue("libraries", null); if (libraries != null && !libraries.trim().equals("")) { config.getServerOptions().put(WGAConfiguration.SERVEROPTION_LIBRARIES, libraries); } // migrate mappings migrationResult.logInfo("Migrating filter mappings."); Iterator filterMappings = root.element("mappings").element("filtermappings") .elementIterator("filtermapping"); while (filterMappings.hasNext()) { Element filterMappingElement = (Element) filterMappings.next(); FilterMapping mapping = new FilterMapping(filterMappingElement.attributeValue("filtername"), filterMappingElement.attributeValue("class")); Iterator patterns = filterMappingElement.elementIterator("filterurlpattern"); while (patterns.hasNext()) { Element pattern = (Element) patterns.next(); mapping.getUrlPatterns().add(pattern.attributeValue("urlpattern")); } Iterator params = filterMappingElement.elementIterator("filterinitparam"); while (params.hasNext()) { Element param = (Element) params.next(); mapping.getInitParameters().put(param.attributeValue("name"), param.attributeValue("value")); } } // migrate jobs migrationResult.logInfo("Migrating configured jobs & schedules."); Element scheduler = (Element) root.element("scheduler"); if (scheduler != null) { config.getSchedulerConfiguration().setLoggingDir(scheduler.attributeValue("loggingdir", null)); Iterator jobs = scheduler.elementIterator("job"); while (jobs.hasNext()) { Element jobElement = (Element) jobs.next(); Job job = new Job(jobElement.attributeValue("name")); String desc = jobElement.attributeValue("description", null); if (desc != null && !desc.trim().equalsIgnoreCase("(Enter description here)")) { job.setDescription(desc); } Iterator options = jobElement.element("joboptions").elementIterator("option"); Element option; while (options.hasNext()) { option = (Element) options.next(); String value = option.attributeValue("value"); if (value != null && !value.trim().equalsIgnoreCase("(database containing the script module)") && !value.trim().equalsIgnoreCase("(Script module to execute)")) { job.getOptions().put(option.attributeValue("name"), option.attributeValue("value")); } } Iterator tasks = jobElement.element("tasks").elementIterator("task"); while (tasks.hasNext()) { Element taskElem = (Element) tasks.next(); Task task = new Task(taskElem.attributeValue("class")); Iterator taskOptions = taskElem.attributeIterator(); while (taskOptions.hasNext()) { Attribute attribute = (Attribute) taskOptions.next(); if (!attribute.getName().equals("name") && !attribute.getName().equals("class")) { String value = attribute.getValue(); if (value != null && !value.trim().equalsIgnoreCase("(database containing the script module)") && !value.trim().equalsIgnoreCase("(Script module to execute)")) { task.getOptions().put(attribute.getName(), attribute.getValue()); } } } job.getTasks().add(task); } Iterator schedules = jobElement.element("schedules").elementIterator("schedule"); SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy hh:mm"); while (schedules.hasNext()) { Element scheduleElement = (Element) schedules.next(); Schedule schedule = new Schedule(scheduleElement.attributeValue("type"), scheduleElement.getText()); schedule.setEnabled(Boolean.parseBoolean(scheduleElement.attributeValue("enabled", "true"))); String sStarting = scheduleElement.attributeValue("starting", null); if (sStarting != null && !sStarting.trim().equals("")) { try { schedule.setStartDate(df.parse(sStarting)); } catch (ParseException e) { migrationResult.logError("Unable to parse start date of job '" + job.getName() + "'.", e); } } String sEnding = scheduleElement.attributeValue("ending", null); if (sEnding != null && !sEnding.trim().equals("")) { try { schedule.setEndDate(df.parse(sEnding)); } catch (ParseException e) { migrationResult.logError("Unable to parse end date of job '" + job.getName() + "'.", e); } } job.getSchedules().add(schedule); } config.getSchedulerConfiguration().getJobs().add(job); } } List<ValidationError> errors = config.validate(); if (!errors.isEmpty()) { migrationResult.logError("Migration failed:"); Iterator<ValidationError> it = errors.iterator(); while (it.hasNext()) { migrationResult.logError(it.next().getMessage()); } } else { // write the config once to apply simple-xml-api validation try { ByteArrayOutputStream out = new ByteArrayOutputStream(); WGAConfiguration.write(config, out); out.close(); migrationResult.setConfig( (WGAConfiguration) WGAConfiguration.read(new ByteArrayInputStream(out.toByteArray()))); } catch (Exception e) { migrationResult.logError("Unable to serialize or deserialize configuration", e); if (e instanceof ConfigValidationException) { errors = ((ConfigValidationException) e).getValidationErrors(); if (errors != null) { Iterator<ValidationError> it = errors.iterator(); while (it.hasNext()) { migrationResult.logError(it.next().getMessage()); } } } } migrationResult.logInfo("Migrating of 'wga.xml' finished."); } return migrationResult; }
From source file:de.start.InitializeDB.java
License:Open Source License
public static void setupDB(int year) { try {/*w w w . j av a 2 s .c o m*/ String filename = "nvdcve-2008.xml"; Connection con = getConnection(); Statement sql = con.createStatement(); sql.execute("drop table if exists nvd"); //,primary key(id) sql.execute( "create table nvd(id varchar(20) not null,soft varchar(160) not null default 'ndefined',rng varchar(100) not null default 'undefined',lose_types varchar(100) not null default 'undefind',severity varchar(20) not null default 'unefined',access varchar(20) not null default 'unefined');"); SAXReader saxReader = new SAXReader(); for (int ct = 2002; ct <= year; ct++) { //String fname="/transient/mulval/oval/nvd/nvdcve-"+Integer.toString(ct)+".xml"; String fname = "nvd_xml_files/nvdcve-" + Integer.toString(ct) + ".xml"; Document document = saxReader.read(fname); List entry = document.selectNodes("/*[local-name(.)='nvd']/*[local-name(.)='entry']"); Iterator ent = entry.iterator(); int act = 0; while (ent.hasNext()) { // varchar(20) not null default 'name', Element id = (Element) ent.next(); String cveid = id.attributeValue("name"); String cvss = ""; String access = ""; // System.out.println(cveid + access); String sev = ""; String host = "localhost"; String sftw = ""; String rge = ""; String rge_tmp = ""; String lose_tmp = ""; String lose_types = ""; ArrayList<String> subele = new ArrayList<String>(); ArrayList<String> attr = new ArrayList<String>(); Iterator ei = id.elementIterator(); while (ei.hasNext()) { // put all of the subelements' // names(subelement of entry) to the // array list Element sube = (Element) ei.next(); subele.add(sube.getName()); } //System.out.println(id.getText()); Iterator i = id.attributeIterator(); while (i.hasNext()) { // put the attributes of the entries to // the arraylist Attribute att = (Attribute) i.next(); attr.add(att.getName()); } if (subele.contains("vuln_soft")) { Element vs = (Element) id.element("vuln_soft"); Iterator itr = vs.elementIterator("prod"); while (itr.hasNext()) { // record all of the softwares Element n = (Element) itr.next(); //sftw = sftw + n.attributeValue("name") + ","; sftw = n.attributeValue("name"); if (sftw.contains("'")) { sftw = sftw.replace("'", "''"); } break; } //int lsf = sftw.length(); //sftw = sftw.substring(0, lsf - 1);// delete the last comma } if (attr.contains("severity")) { sev = id.attributeValue("severity"); } if (attr.contains("CVSS_vector")) { cvss = id.attributeValue("CVSS_vector"); char ac = cvss.charAt(9); if (ac == 'L') access = "l"; else if (ac == 'M') access = "m"; else if (ac == 'H') access = "h"; else ; } if (subele.contains("range")) { // to get the range as a array Element vs = (Element) id.element("range"); Iterator rgi = vs.elementIterator(); while (rgi.hasNext()) { // record all of the softwares Element rg = (Element) rgi.next(); if (rg.getName().equals("user_init")) rge_tmp = "user_action_req"; else if (rg.getName().equals("local_network")) rge_tmp = "lan"; else if (rg.getName().equals("network")) rge_tmp = "remoteExploit"; else if (rg.getName().equals("local")) rge_tmp = "local"; else rge_tmp = "other"; rge = rge + "''" + rge_tmp + "'',"; } int lr = rge.length(); rge = rge.substring(0, lr - 1);// delete the last comma } if (subele.contains("loss_types")) { Element lt = (Element) id.element("loss_types"); Iterator lti = lt.elementIterator(); while (lti.hasNext()) { ArrayList<String> isecat = new ArrayList<String>(); Element ls = (Element) lti.next(); if (ls.getName().equals("avail")) lose_tmp = "availability_loss"; else if (ls.getName().equals("conf")) lose_tmp = "data_loss"; else if (ls.getName().equals("int")) lose_tmp = "data_modification"; else lose_tmp = "other"; lose_types = lose_types + "''" + lose_tmp + "'',"; } int ltp = lose_types.length(); lose_types = lose_types.substring(0, ltp - 1);// delete the // last // comma } //System.out.println(cveid + lose_types + rge + sftw + sev + access); String insert = "insert nvd values('" + cveid + "','" + sftw + "','" + rge + "','" + lose_types + "','" + sev + "','" + access + "')"; sql.execute(insert); } } sql.close(); con.close(); } catch (java.lang.ClassNotFoundException e) { System.err.println("ClassNotFoundException:" + e.getMessage()); } catch (SQLException ex) { System.err.println("SQLException:" + ex.getMessage()); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:de.thischwa.pmcms.view.renderer.VelocityUtils.java
License:LGPL
/** * Replace the img-tag and a-tag with the equivalent velocity macro. Mainly used before saving a field value to the database. * /*from w w w . j a va 2s.com*/ * @throws RenderingException * If any exception was thrown while replacing the tags. */ @SuppressWarnings("unchecked") public static String replaceTags(final Site site, final String oldValue) throws RenderingException { if (StringUtils.isBlank(oldValue)) return null; // 1. add a root element (to have a proper xml) and replace the ampersand String newValue = String.format("<dummytag>\n%s\n</dummytag>", StringUtils.replace(oldValue, "&", ampReplacer)); Map<String, String> replacements = new HashMap<String, String>(); try { Document dom = DocumentHelper.parseText(newValue); dom.setXMLEncoding(Constants.STANDARD_ENCODING); // 2. Collect the keys, identify the img-tags. List<Node> imgs = dom.selectNodes("//img", "."); for (Node node : imgs) { Element element = (Element) node; if (element.attributeValue("src").startsWith("/")) // only internal links have to replaced with a velocity macro replacements.put(node.asXML(), generateVelocityImageToolCall(site, element.attributeIterator())); } // 3. Collect the keys, identify the a-tags List<Node> links = dom.selectNodes("//a", "."); for (Node node : links) { Element element = (Element) node; if (element.attributeValue("href").startsWith("/")) // only internal links have to replaced with a velocity macro replacements.put(element.asXML(), generateVelocityLinkToolCall(site, element)); } // 4. Replace the tags with the velomacro. StringWriter stringWriter = new StringWriter(); XMLWriter writer = new XMLWriter(stringWriter, sourceFormat); writer.write(dom.selectSingleNode("dummytag")); writer.close(); newValue = stringWriter.toString(); for (String stringToReplace : replacements.keySet()) newValue = StringUtils.replace(newValue, stringToReplace, replacements.get(stringToReplace)); newValue = StringUtils.replace(newValue, "<dummytag>", ""); newValue = StringUtils.replace(newValue, "</dummytag>", ""); } catch (Exception e) { throw new RenderingException("While preprocessing the field value: " + e.getMessage(), e); } return StringUtils.replace(newValue, ampReplacer, "&"); }
From source file:de.thischwa.pmcms.view.renderer.VelocityUtils.java
License:LGPL
/** * Construct the {@link de.thischwa.pmcms.view.context.object.tagtool.LinkTagTool}-call. *///from w w w .ja v a2 s . c om @SuppressWarnings("unchecked") private static String generateVelocityLinkToolCall(final Site site, final Element tagElement) { StringBuilder veloMacro = new StringBuilder(); final Pattern aTagPattern = Pattern.compile("<a\\b[^>]*>(.*?)</a>"); Map<String, String> attr = new HashMap<String, String>(); veloMacro.append("$linktagtool"); for (Iterator<Attribute> iter = tagElement.attributeIterator(); iter.hasNext();) { Attribute attribute = iter.next(); attr.put(attribute.getName(), attribute.getValue()); } String href = attr.get("href"); Link link = InitializationManager.getBean(Link.class); link.init(href); if (link.isExternal()) { veloMacro.append(".setHref(\"").append(href).append("\")"); } else { VirtualFile fileResource = new VirtualFile(site, false); fileResource.consructFromTagFromView(href); veloMacro.append(".setHref(\"").append(fileResource.getTagSrcForPreview()).append("\")"); } String value; Matcher matcher = aTagPattern.matcher(tagElement.asXML()); if (matcher.matches()) value = matcher.group(1); else value = tagElement.getText(); veloMacro.append(".setTagValue(\"").append(value).append("\")"); for (String key : attr.keySet()) { if (!key.equals("href")) veloMacro.append(".setAttribute(\"").append(key).append("\", \"").append(attr.get(key)) .append("\")"); } return veloMacro.toString(); }
From source file:de.tud.kom.p2psim.impl.scenario.DefaultConfigurator.java
License:Open Source License
public void configureAttributes(Object component, Element elem, Set<String> consAttrs) { for (Iterator iter = elem.attributeIterator(); iter.hasNext();) { Attribute attr = (Attribute) iter.next(); String name = attr.getName(); if (!name.equals(CLASS_TAG) && !name.equals(STATIC_CREATION_METHOD_TAG) && !consAttrs.contains(name.toLowerCase()) && !name.equals(X_INCLUDE_ATTRIBUTE)) { try { // try to configure as boolean, int, double, String, or long String value = getAttributeValue(attr); Method method = null; String methodName = getMethodName(SET_METHOD_PREFIX_TAG, name); Class<? extends Object> classToConfigure = component.getClass(); Method[] methods = classToConfigure.getMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals(methodName) && methods[i].getParameterTypes().length == 1) { if (method == null) { method = methods[i]; } else { log.error("Found two possible methods " + method + " and " + methods[i]); throw new IllegalArgumentException("Cannot set property " + name + " as there are more than one matching methods in " + classToConfigure); }/* ww w . ja v a 2 s .c om*/ } } if (method == null) { throw new IllegalArgumentException("Cannot set property " + name + " as there are no matching methods in class " + classToConfigure); } Class typeClass = method.getParameterTypes()[0]; Object param = convertValue(value, typeClass); method.invoke(component, param); // TODO legal bool or int parameter could be string! // catch (NoSuchMethodException e) { invoke with string ... } catch (Exception e) { throw new ConfigurationException("Failed to set the property " + name + " in " + component, e); } } } }
From source file:de.tudarmstadt.ukp.lmf.transform.XMLToDBTransformer.java
License:Apache License
@Override public void onStart(ElementPath epath) { Element el = epath.getCurrent(); String n = el.getName();//from w w w . j av a2 s .c om // Remove empty attributes and invalid characters. Iterator<?> attrIter = el.attributeIterator(); while (attrIter.hasNext()) { Attribute attr = (Attribute) attrIter.next(); if ("NULL".equals(attr.getStringValue())) { attrIter.remove(); } else { attr.setValue(StringUtils.replaceNonUtf8(attr.getValue())); } } if ("LexicalResource".equals(n)) { // If no lexical resource exists yet, create a new one. if (lexicalResource == null) { lexicalResource = new LexicalResource(); lexicalResource.setName(el.attributeValue("name")); lexicalResource.setDtdVersion(el.attributeValue("dtdVersion")); session.save(lexicalResource); } else { externalLexicalResource = true; } } else if ("Lexicon".equals(n)) { // Create a new, empty lexicon. lexicon = new Lexicon(); lexicon.setId(el.attributeValue("id")); lexicon.setName(el.attributeValue("name")); lexicon.setLanguageIdentifier(el.attributeValue("languageIdentifier")); lexicalResource.addLexicon(lexicon); saveCascade(lexicon, lexicalResource); } // Save some global information if we're using a new lexical resource. else if ("GlobalInformation".equals(n) && !externalLexicalResource) { GlobalInformation glInformation = new GlobalInformation(); glInformation.setLabel(el.attributeValue("label")); lexicalResource.setGlobalInformation(glInformation); saveCascade(glInformation, lexicalResource); commit(); lexicalResource.setGlobalInformation(null); } }
From source file:edu.pitt.sis.FetchNE.java
/** * @param args//from w w w . j av a2 s . c o m */ public static void getNameEntity(long col_id) { //public static void main(String args[]){ //long col_id = 19; try { URL url = new URL("http://api.opencalais.com/enlighten/rest/"); String license = "t32k95r9k8n9ftdp256e8esw"; String paramsXML = "<c:params xmlns:c=\"http://s.opencalais.com/1/pred/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">" + "<c:processingDirectives c:contentType=\"text/txt\" c:enableMetadataType=\"GenericRelations\" c:outputFormat=\"text/simple\">" + "</c:processingDirectives>" + "<c:userDirectives c:allowDistribution=\"true\" c:allowSearch=\"true\" c:externalID=\"17cabs901\" c:submitter=\"jahn\">" + "</c:userDirectives>" + "<c:externalMetadata>" + "</c:externalMetadata>" + "</c:params>"; try { String sql = "SELECT c.col_id,c.title,s.name,h.host,c.location,c.detail " + "FROM colloquium c,speaker s,host h " + "WHERE c.speaker_id = s.speaker_id AND " + "c.host_id = h.host_id AND " + "c.col_id = " + col_id; connectDB conn = new connectDB(); ResultSet rs = conn.getResultSet(sql); try { if (rs.next()) { col_id = rs.getLong("col_id"); String content = rs.getString("title") + "\n" + rs.getString("name") + "\n" + rs.getString("host") + "\n" + rs.getString("location") + "\n" + rs.getString("detail"); if (content.length() > 100000) { content = content.substring(0, 99999); } String query = "licenseID=" + URLEncoder.encode(license, "UTF-8") + "&" + "content=" + URLEncoder.encode(content, "UTF-8") + "&" + "paramsXML=" + URLEncoder.encode(paramsXML, "UTF-8"); //make connection URLConnection urlc = url.openConnection(); //use post mode urlc.setDoOutput(true); urlc.setAllowUserInteraction(false); //send query PrintStream ps = new PrintStream(urlc.getOutputStream()); ps.print(query); ps.close(); //get result BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String line = null; String result = ""; while ((line = br.readLine()) != null) { System.out.println(line); result += line; } br.close(); //save opencalais response sql = "INSERT INTO opencalais (col_id,content,output,_date) VALUES (?,?,?,NOW())"; PreparedStatement pstmt = conn.conn.prepareStatement(sql); pstmt.setLong(1, col_id); pstmt.setString(2, content); pstmt.setString(3, result); pstmt.executeUpdate(); try { Document document = DocumentHelper.parseText(result); Element root = document.getRootElement(); //topics and topic tables were merged into entities and entity tables //sql = "DELETE FROM topics WHERE col_id = " + col_id; //conn.executeUpdate(sql); sql = "DELETE FROM entities WHERE col_id = " + col_id; conn.executeUpdate(sql); // iterate through child elements of root with element name "CalaisSimpleOutputFormat" for (Iterator i = root.elementIterator("CalaisSimpleOutputFormat"); i.hasNext();) { Element element = (Element) i.next(); for (Iterator j = element.elementIterator(); j.hasNext();) { Element e = (Element) j.next(); System.out.println(e.getName() + " : " + e.getText()); if (e.getName().trim().equalsIgnoreCase("topics")) {//Insert topics => entities for (Iterator l = e.elementIterator(); l.hasNext();) { Element ee = (Element) l.next(); System.out.println(ee.getName() + " : " + ee.getText()); sql = "SELECT entity_id FROM entity WHERE entity = ?"; pstmt = conn.conn.prepareStatement(sql); pstmt.setString(1, ee.getText().replaceAll("_", " ")); ResultSet rst = pstmt.executeQuery(); long entity_id = -1; if (rst.next()) { entity_id = rst.getLong("entity_id"); } else { sql = "INSERT INTO entity (entity,_type,_date) VALUES (?,'Topic',NOW())"; pstmt = conn.conn.prepareStatement(sql); pstmt.setString(1, ee.getText()); pstmt.executeUpdate(); sql = "SELECT LAST_INSERT_ID()"; ResultSet rsst = conn.getResultSet(sql); if (rsst.next()) { entity_id = rsst.getLong(1); } } sql = "INSERT INTO entities (entity_id,col_id) VALUES (?,?)"; pstmt = conn.conn.prepareStatement(sql); pstmt.setLong(1, entity_id); pstmt.setLong(2, col_id); pstmt.executeUpdate(); //for(Iterator m = e.attributeIterator();m.hasNext();){ // Attribute aa = (Attribute)m.next(); // System.out.println(aa.getName() + " : " + aa.getText()); //} } } else { String entity = e.getText(); String _type = e.getName(); String normalized = ""; String other = ""; int count = -1; double relevance = 0.0; for (Iterator k = e.attributeIterator(); k.hasNext();) { Attribute a = (Attribute) k.next(); System.out.println(a.getName() + " : " + a.getText()); if (a.getName().equalsIgnoreCase("count")) { count = Integer.parseInt(a.getText()); } else if (a.getName().equalsIgnoreCase("relevance")) { relevance = Double.parseDouble(a.getText()); } else if (a.getName().equalsIgnoreCase("normalized")) { normalized = a.getText(); } else { other += a.getText(); } } //Find an entity in db sql = "SELECT entity_id FROM entity WHERE entity = ?"; pstmt = conn.conn.prepareStatement(sql); pstmt.setString(1, entity); ResultSet rsEntity = pstmt.executeQuery(); long entity_id = -1; if (rsEntity.next()) { entity_id = rsEntity.getLong("entity_id"); } else { sql = "INSERT INTO entity (entity,_type,normalized,other,_date) VALUES (?,?,?,?,NOW())"; pstmt = conn.conn.prepareStatement(sql); pstmt.setString(1, entity); pstmt.setString(2, _type); pstmt.setString(3, normalized); pstmt.setString(4, other); pstmt.executeUpdate(); sql = "SELECT LAST_INSERT_ID()"; rsEntity = conn.getResultSet(sql); if (rsEntity.next()) { entity_id = rsEntity.getLong(1); } } sql = "INSERT INTO entities (entity_id,relevance,occur,col_id) VALUES (?,?,?,?)"; pstmt = conn.conn.prepareStatement(sql); pstmt.setLong(1, entity_id); pstmt.setDouble(2, relevance); pstmt.setInt(3, count); pstmt.setLong(4, col_id); pstmt.executeUpdate(); } } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } conn.conn.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { conn = null; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //return 1; }
From source file:edu.umd.cs.findbugs.xml.XPathFind.java
License:Open Source License
public static void main(String[] argv) throws Exception { if (argv.length != 2) { System.err.println("Usage: " + XPathFind.class.getName() + ": <filename> <xpath expression>"); System.exit(1);/* w w w. j av a 2 s . c om*/ } String fileName = argv[0]; String xpath = argv[1]; SAXReader reader = new SAXReader(); Document document = reader.read(fileName); XPathFind finder = new XPathFind(document) { @Override protected void match(Node node) { // System.out.println(node.toString()); if (node instanceof Element) { Element element = (Element) node; System.out.println("Element: " + element.getQualifiedName()); System.out.println("\tText: " + element.getText()); System.out.println("\tAttributes:"); for (Iterator<?> i = element.attributeIterator(); i.hasNext();) { Attribute attribute = (Attribute) i.next(); System.out.println("\t\t" + attribute.getName() + "=" + attribute.getValue()); } } else if (node instanceof Attribute) { Attribute attribute = (Attribute) node; System.out.println("Attribute: " + attribute.getName() + "=" + attribute.getValue()); } } }; finder.find(xpath); }
From source file:fr.gouv.culture.vitam.database.utils.swing.Dom4jTreeBuilder.java
License:Open Source License
public void addAttribute(Element curnode) { for (@SuppressWarnings("unchecked") Iterator<Attribute> it = curnode.attributeIterator(); it.hasNext();) { Attribute attr = it.next(); DefaultMutableTreeNode node = new DefaultMutableTreeNode(attr.getName() + "=" + attr.getText()); currentNode.add(node);/*from w ww . jav a 2 s . c om*/ } }