List of usage examples for org.dom4j Attribute getValue
String getValue();
From source file:darks.orm.core.config.sqlmap.DDLConfigReader.java
License:Apache License
/** * DDL//from w w w.ja va2 s. com * * @param element */ public void reader(Element element) { // DDL for (Iterator<Attribute> it = element.attributeIterator(); it.hasNext();) { try { Attribute at = it.next(); String name = at.getName().trim(); String value = at.getValue().trim(); if ("schema".equalsIgnoreCase(name)) { sqlMapConfig.setSchema(value); } else if ("catalog".equalsIgnoreCase(name)) { sqlMapConfig.setCatalog(value); } } catch (Exception e) { e.printStackTrace(); } } // DDL for (Iterator<Element> it = element.elementIterator(); it.hasNext();) { try { Element el = it.next(); String name = el.getName().trim(); if ("create".equalsIgnoreCase(name)) { readCreate(el); } else if ("alter".equalsIgnoreCase(name)) { readAlter(el); } } catch (Exception e) { e.printStackTrace(); } } }
From source file:darks.orm.core.config.sqlmap.DDLConfigReader.java
License:Apache License
/** * /*from w w w . j a v a2 s.co m*/ * * @param element * @param type */ public void readLabel(Element element, DDLType type) { DDLData ddlData = new DDLData(); String sql = element.getTextTrim(); String strRndId = UUIDHelper.getUUID(); ddlData.setId(strRndId); ddlData.setSql(sql); ddlData.setType(type); 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)) { ddlData.setId(value); } else if ("tableName".equalsIgnoreCase(name)) { ddlData.setTableName(value); } else if ("checkTable".equalsIgnoreCase(name)) { if ("true".equalsIgnoreCase(value)) ddlData.setCheckTable(true); else if ("false".equalsIgnoreCase(value)) ddlData.setCheckTable(false); } else if ("autoRunable".equalsIgnoreCase(name)) { if ("true".equalsIgnoreCase(value)) ddlData.setAutoRunable(true); else if ("false".equalsIgnoreCase(value)) ddlData.setAutoRunable(false); } } catch (Exception e) { e.printStackTrace(); } } sqlMapConfig.addDDLData(ddlData.getId(), ddlData); }
From source file:darks.orm.core.config.sqlmap.DMLConfigReader.java
License:Apache License
private void readQueryAttribute(Attribute attr, DMLData dmlData, DMLQueryData queryData) throws Exception { String name = attr.getName().trim(); String value = attr.getValue().trim(); if ("id".equalsIgnoreCase(name)) { dmlData.setId(value);/* w w w .j av a2 s. co m*/ } else if ("resultType".equalsIgnoreCase(name)) { queryData.setResultType(value); Class<?> cls = TransformFactory.getInstance().stringToEntityClass(value); if (cls == null) { throw new ConfigException(value + " does not exists"); } queryData.setResultClass(cls); } else if ("autoCascade".equalsIgnoreCase(name)) { if ("true".equalsIgnoreCase(value)) queryData.setAutoCascade(true); else if ("false".equalsIgnoreCase(value)) queryData.setAutoCascade(false); } else if ("alias".equalsIgnoreCase(name)) { queryData.setAlias(value); } else if ("attribute".equalsIgnoreCase(name)) { queryData.setAttribute(value); } else if ("queryType".equalsIgnoreCase(name)) { if ("object".equalsIgnoreCase(value)) queryData.setQueryType(QueryEnumType.Object); else if ("list".equalsIgnoreCase(value)) queryData.setQueryType(QueryEnumType.List); else if ("page".equalsIgnoreCase(value)) queryData.setQueryType(QueryEnumType.Page); else queryData.setQueryType(QueryEnumType.Auto); } else if ("cache".equalsIgnoreCase(name)) { if ("auto".equalsIgnoreCase(value)) dmlData.setAutoCache(true); else if ("manual".equalsIgnoreCase(value)) dmlData.setAutoCache(false); } else if ("cacheId".equalsIgnoreCase(name)) { dmlData.setCacheId(value); } else if ("values".equalsIgnoreCase(name)) { queryData.setValuesParam(StringHelper.parseParamFlag(value)); } else if ("page".equalsIgnoreCase(name)) { queryData.setPageParam(StringHelper.parseParamFlag(value)); } else if ("pageSize".equalsIgnoreCase(name)) { queryData.setPageSizeParam(StringHelper.parseParamFlag(value)); } }
From source file:darks.orm.core.config.sqlmap.DMLConfigReader.java
License:Apache License
/** * Read and parse update tags// ww w. j a v a 2 s . co m * * @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:darks.orm.core.config.sqlmap.DMLConfigReader.java
License:Apache License
/** * Read and parse aspect XMLs file/*from w w w.j av a2 s. c o m*/ * * @param element Aspect tags * @return Aspect data */ private AspectData parseAspectXml(Element element) { Element aspectEl = element.element("aspect"); if (aspectEl == null) return null; AspectData aspectData = new AspectData(); boolean isNext = false; Element jythonEl = aspectEl.element("jython"); if (jythonEl != null) { aspectData.setAspectType(AspectType.JYTHON); Attribute attr = jythonEl.attribute("className"); if (attr == null) return null; aspectData.setClassName(attr.getValue().trim()); String text = jythonEl.getText(); if (text == null || "".equals(text.trim())) { String before = jythonEl.elementText("before"); String after = jythonEl.elementText("after"); if (before == null || "".equals(before.trim())) { if (after == null || "".equals(after.trim())) return null; } text = PythonBuilder.buildBody(aspectData.getClassName(), before, after); } aspectData.setContent(text); isNext = true; } Element pyfileEl = aspectEl.element("pyfile"); if (pyfileEl != null && isNext == false) { aspectData.setAspectType(AspectType.PYFILE); Attribute attr = pyfileEl.attribute("className"); if (attr == null) return null; aspectData.setClassName(attr.getValue().trim()); aspectData.setContent(pyfileEl.getTextTrim()); isNext = true; } Element javaClassEl = aspectEl.element("javaClass"); if (javaClassEl != null && isNext == false) { aspectData.setAspectType(AspectType.JAVACLASS); aspectData.setClassName(javaClassEl.getTextTrim()); isNext = true; } Element jsEl = aspectEl.element("javascript"); if (jsEl != null && isNext == false) { aspectData.setAspectType(AspectType.JAVASCRIPT); aspectData.setContent(jsEl.getTextTrim()); isNext = true; } Element jsfileEl = aspectEl.element("jsfile"); if (jsfileEl != null && isNext == false) { aspectData.setAspectType(AspectType.JSFILE); aspectData.setContent(jsfileEl.getTextTrim()); isNext = true; } if (isNext) { return aspectData; } return null; }
From source file:Data.Storage.java
License:Apache License
/** * helper for adding xml/* w ww . j a v a 2 s . c om*/ * @param path where the xml will be added * @param xmlData the data as an xml Element */ private void addXmlWithPath(ArrayList<String> path, Element xmlData) { boolean isXml = xmlData.elements().size() > 0; //set the key String[] thePath = new String[path.size()]; path.toArray(thePath); //put either the value or an imbeded object if (isXml && !has(thePath)) { put(thePath, new Storage()); } else { put(thePath, xmlData.getStringValue()); } for (int i = 0; i < xmlData.attributeCount(); ++i) { //get attribute data Attribute attr = xmlData.attribute(i); //save attribute putAttribute(thePath, attr.getName(), attr.getValue()); } //if it is xml need to see all children if (isXml) { recurseOverElements(path, xmlData); } }
From source file:de.bps.onyx.plugin.course.nodes.iq.IQEditController.java
License:Apache License
/** * Update the module configuration from the qti file: read min/max/cut values * //w w w .j a v a 2s . c o m * @param res */ public void updateModuleConfigFromQTIFile(final OLATResource res) { final FileResourceManager frm = FileResourceManager.getInstance(); final File unzippedRoot = frm.unzipFileResource(res); // with VFS FIXME:pb:c: remove casts to LocalFileImpl and LocalFolderImpl if no longer needed. final VFSContainer vfsUnzippedRoot = new LocalFolderImpl(unzippedRoot); final VFSItem vfsQTI = vfsUnzippedRoot.resolve("qti.xml"); if (vfsQTI == null) { throw new AssertException("qti file did not exist even it should be guaranteed by repositor check-in " + ((LocalFileImpl) vfsQTI).getBasefile().getAbsolutePath()); } // ensures that InputStream is closed in every case. final Document doc = QTIHelper.getDocument((LocalFileImpl) vfsQTI); if (doc == null) { // error reading qti file (existence check was made before) throw new AssertException( "qti file could not be read " + ((LocalFileImpl) vfsQTI).getBasefile().getAbsolutePath()); } // Extract min, max and cut value Float minValue = null, maxValue = null, cutValue = null; final Element decvar = (Element) doc .selectSingleNode("questestinterop/assessment/outcomes_processing/outcomes/decvar"); if (decvar != null) { final Attribute minval = decvar.attribute("minvalue"); if (minval != null) { final String mv = minval.getValue(); try { minValue = new Float(Float.parseFloat(mv)); } catch (final NumberFormatException e1) { // if not correct in qti file -> ignore } } final Attribute maxval = decvar.attribute("maxvalue"); if (maxval != null) { final String mv = maxval.getValue(); try { maxValue = new Float(Float.parseFloat(mv)); } catch (final NumberFormatException e1) { // if not correct in qti file -> ignore } } final Attribute cutval = decvar.attribute("cutvalue"); if (cutval != null) { final String cv = cutval.getValue(); try { cutValue = new Float(Float.parseFloat(cv)); } catch (final NumberFormatException e1) { // if not correct in qti file -> ignore } } } // Put values to module configuration moduleConfiguration.set(CONFIG_KEY_MINSCORE, minValue); moduleConfiguration.set(CONFIG_KEY_MAXSCORE, maxValue); moduleConfiguration.set(CONFIG_KEY_CUTVALUE, cutValue); }
From source file:de.innovationgate.wga.common.WGAXML.java
License:Apache License
/** * Automatically sorts design providers in wga.xml to be the first to be connected. * By that way the situation that a design consumer is connected earlier than its provider will be avoided * @param doc The wga.xml document/*from w w w. j a v a 2s . c o m*/ */ public static void pullupDesignProviders(Document doc) { // Collect keys of used provider dbs Element contentdbs = (Element) doc.selectSingleNode("/wga/contentdbs"); Iterator providerKeysElems = contentdbs.selectNodes("contentdb/design[@provider='db']/@key").iterator(); Set providerKeys = new LinkedHashSet(); while (providerKeysElems.hasNext()) { Attribute providerKeyAttr = (Attribute) providerKeysElems.next(); String key = providerKeyAttr.getValue(); providerKeys.add(key); } // Move them up Iterator keysIt = providerKeys.iterator(); int insertIdx = 0; while (keysIt.hasNext()) { String key = (String) keysIt.next(); Element contentdb = (Element) contentdbs.selectSingleNode("contentdb[dbkey='" + key + "']"); if (contentdb != null) { contentdbs.content().remove(contentdb); contentdbs.content().add(insertIdx, contentdb); insertIdx++; } } }
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);// w ww .j ava2 s . co m 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.thischwa.pmcms.view.renderer.VelocityUtils.java
License:LGPL
/** * Construct the {@link de.thischwa.pmcms.view.context.object.tagtool.LinkTagTool}-call. */// ww w .j a v a2 s . c o m @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(); }