/*******************************************************************************
* Copyright (c) 2009, 2010 Innovation Gate GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Innovation Gate GmbH - initial API and implementation
******************************************************************************/
package de.innovationgate.eclipse.wgadesigner.natures;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.ResourceAttributes;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PartInitException;
import de.innovationgate.eclipse.editors.Plugin;
import de.innovationgate.eclipse.utils.FileUtils;
import de.innovationgate.eclipse.utils.WorkbenchUtils;
import de.innovationgate.eclipse.utils.wga.WGADesignStructureHelper;
import de.innovationgate.eclipse.wgadesigner.ResourceIDs;
import de.innovationgate.eclipse.wgadesigner.WGADesignerPlugin;
import de.innovationgate.eclipse.wgadesigner.editors.helpers.WGADeployment;
import de.innovationgate.eclipse.wgadesigner.models.DesignTemplate;
import de.innovationgate.eclipse.wgadesigner.models.WGARemoteServer;
import de.innovationgate.eclipse.wgadesigner.preferences.PreferenceConstants;
import de.innovationgate.utils.WGUtils;
import de.innovationgate.wga.common.Constants;
import de.innovationgate.wga.config.ContentDatabase;
import de.innovationgate.wga.config.ContentStore;
import de.innovationgate.wga.config.Design;
import de.innovationgate.wga.config.Domain;
import de.innovationgate.wga.config.WGAConfiguration;
import de.innovationgate.wgaservices.WGACoreServices;
import de.innovationgate.wgaservices.WGAServices;
public class WGARuntime implements IProjectNature, IResourceChangeListener {
private Set<WGARuntimeListener> _listeners = new HashSet<WGARuntimeListener>();
public IContainer getDesignRoot() {
return _designRoot;
}
public IContainer getHsqlRoot() {
return _hsqlRoot;
}
public IFolder getPluginRoot() {
return _developerPluginsRoot;
}
private static final String DBS_FOLDERNAME = "#dbs";
private static final String LUCENE_FOLDERNAME = "#lucene";
private static final String PLUGIN_DBS_FOLDERNAME = "#dbs";
private static final String PLUGIN_WORKSPACE_FOLDERNAME = "#workspace";
private IProject _project = null;
private IContainer _catalinaBase;
private IContainer _catalinaConf;
private IContainer _catalinaLibdir;
private IContainer _wgaBase;
private IContainer _designRoot;
private static final String CATALINA_CONF_DIRNAME = "conf";
private WGARuntimeConfiguration _config;
private IFolder _wgaData;
private IFolder _workflowRoot;
private IFolder _luceneRoot;
private IFolder _hsqlRoot;
private IFolder _developerPluginsRoot;
private Object _wgaConfigLock = new Object();
public WGARuntime() {
ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE);
}
public void configure() throws CoreException {
_designRoot = FileUtils.createFolder(_project, "designs");
_developerPluginsRoot = FileUtils.createFolder(_project, "plugins");
_wgaBase = FileUtils.createFolder(_project, "wga");
_wgaData = FileUtils.createFolder(_wgaBase, "wgadata");
IFolder plugins = FileUtils.createFolder(_wgaData, "plugins");
IFolder pluginDBs = FileUtils.createFolder(plugins, PLUGIN_DBS_FOLDERNAME);
pluginDBs.setDerived(true);
IFolder pluginWorkspace = FileUtils.createFolder(plugins, PLUGIN_WORKSPACE_FOLDERNAME);
pluginWorkspace.setDerived(true);
_hsqlRoot = _wgaData.getFolder(new Path(DBS_FOLDERNAME));
IFolder oldHSQLRoot = _wgaData.getFolder(new Path("dbs"));
if (oldHSQLRoot.exists()) {
try {
oldHSQLRoot.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
oldHSQLRoot.move(new Path(DBS_FOLDERNAME), false, new NullProgressMonitor());
} catch (CoreException e) {
WGADesignerPlugin.getDefault().logError("Unable to migrate existing dbs folder.", e);
}
}
if (!_hsqlRoot.exists()) {
_hsqlRoot.create(false, true, new NullProgressMonitor());
}
_hsqlRoot.setDerived(true);
_luceneRoot = _wgaData.getFolder(new Path(LUCENE_FOLDERNAME));
IFolder oldLuceneRoot = _wgaData.getFolder(new Path("lucene"));
if (oldLuceneRoot.exists()) {
try {
oldLuceneRoot.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
oldLuceneRoot.move(new Path(LUCENE_FOLDERNAME), false, new NullProgressMonitor());
} catch (CoreException e) {
WGADesignerPlugin.getDefault().logError("Unable to migrate existing lucene folder.", e);
}
}
if (!_luceneRoot.exists()) {
_luceneRoot.create(false, true, new NullProgressMonitor());
}
_luceneRoot.setDerived(true);
_workflowRoot = FileUtils.createFolder(_wgaData, "workflows");
_catalinaBase = FileUtils.createFolder(_project, "tomcat");
_catalinaLibdir = FileUtils.createFolder(_catalinaBase, "lib");
_catalinaConf = FileUtils.createFolder(_catalinaBase, CATALINA_CONF_DIRNAME);
// create default auth.xml
Document auth = DocumentFactory.getInstance().createDocument();
Element users = auth.addElement("users");
users.addAttribute("allowanonymous", "true");
Element designer = users.addElement("user");
designer.addAttribute("name", "designer");
designer.addAttribute("password", "wga");
designer.addAttribute("mail", "designer@example.com");
designer.addAttribute("aliases", "");
Element managers = users.addElement("group");
managers.addAttribute("name", "managers");
managers.addAttribute("members", "designer");
XMLWriter writer = null;
try {
writer = new XMLWriter(OutputFormat.createPrettyPrint());
writer.setOutputStream(new FileOutputStream(new File(getWGABase().getLocation().toFile(), "auth.xml")));
writer.write(auth);
} catch (Exception e) {
throw new CoreException(new Status(Status.ERROR, WGADesignerPlugin.PLUGIN_ID, "Unable to generate default auth configuration.", e));
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
}
}
FileOutputStream configFileStream = null;
try {
_config = WGARuntimeConfiguration.createDefaultConfig();
synchronized (_wgaConfigLock) {
configFileStream = new FileOutputStream(getConfigFile().getLocation().toFile());
WGARuntimeConfiguration.write(_config, configFileStream);
}
} catch (Exception e) {
throw new CoreException(new Status(Status.ERROR, WGADesignerPlugin.PLUGIN_ID, "Unable to generate default runtime configuration.", e));
} finally {
if (configFileStream != null) {
try {
configFileStream.close();
} catch (IOException e) {
}
}
}
// create wga.xml defaults
try {
retrieveWGAConfig(true);
} catch (IncompatibleWGAConfigVersion e) {
// should not happen bc. config file does not exist yet - but for
// sure we generate a notice
throw new CoreException(new Status(Status.ERROR, WGADesignerPlugin.PLUGIN_ID, "Unable to generate default wga configuration.", e));
} catch (IOException e) {
throw new CoreException(new Status(Status.ERROR, WGADesignerPlugin.PLUGIN_ID, "Unable to generate default wga configuration.", e));
}
_project.refreshLocal(IResource.DEPTH_INFINITE, null);
}
public void deconfigure() throws CoreException {
}
public IProject getProject() {
return _project;
}
public String getName() {
return _project.getName();
}
public void setProject(IProject project) {
_project = project;
if (isConfigured()) {
init();
}
}
private void init() {
_catalinaBase = _project.getFolder("tomcat");
_catalinaConf = _catalinaBase.getFolder(new Path(CATALINA_CONF_DIRNAME));
_catalinaLibdir = _catalinaBase.getFolder(new Path("lib"));
if(!_catalinaLibdir.exists()){
try {
FileUtils.createFolder(_catalinaBase, "lib");
}
catch (CoreException e) {
Plugin.getDefault().logError("Unable to create folder : " + _catalinaLibdir.toString(), e);
}
}
_wgaBase = _project.getFolder("wga");
_wgaData = _wgaBase.getFolder(new Path("wgadata"));
if(!_wgaData.exists()){
try {
FileUtils.createFolder(_wgaBase,"wgadata");
}
catch (CoreException e) {
Plugin.getDefault().logError("Unable to create folder : " + _wgaData.toString(), e);
}
}
IFolder plugins = _wgaData.getFolder(new Path("plugins"));
if (plugins.exists()) {
IFolder pluginDBs = plugins.getFolder(PLUGIN_DBS_FOLDERNAME);
if (pluginDBs.exists()) {
try {
pluginDBs.setDerived(true);
} catch (CoreException e1) {
WGADesignerPlugin.getDefault().logError("Unable to set derived flag on folder '" + pluginDBs.getLocation() + "'.", e1);
}
}
IFolder pluginWorkspace = plugins.getFolder(PLUGIN_WORKSPACE_FOLDERNAME);
if (pluginWorkspace.exists()) {
try {
pluginWorkspace.setDerived(true);
} catch (CoreException e1) {
WGADesignerPlugin.getDefault().logError("Unable to set derived flag on folder '" + pluginWorkspace.getLocation() + "'.", e1);
}
}
}
_workflowRoot = _wgaData.getFolder(new Path("workflows"));
_designRoot = _project.getFolder("designs");
_hsqlRoot = _wgaData.getFolder(new Path(DBS_FOLDERNAME));
IFolder oldHSQLRoot = _wgaData.getFolder(new Path("dbs"));
if (oldHSQLRoot.exists() && !_hsqlRoot.exists()) {
try {
oldHSQLRoot.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
oldHSQLRoot.move(new Path(DBS_FOLDERNAME), false, new NullProgressMonitor());
} catch (CoreException e) {
WGADesignerPlugin.getDefault().logError("Unable to migrate existing dbs folder.", e);
}
}
try {
if(!_hsqlRoot.exists()){
FileUtils.createFolder(_wgaData, DBS_FOLDERNAME);
}
_hsqlRoot.setDerived(true);
} catch (CoreException e1) {
WGADesignerPlugin.getDefault().logError("Unable to set derived flag on folder '" + _hsqlRoot.getLocation() + "'.", e1);
}
_luceneRoot = _wgaData.getFolder(new Path(LUCENE_FOLDERNAME));
IFolder oldLuceneRoot = _wgaData.getFolder(new Path("lucene"));
if (oldLuceneRoot.exists() && !_luceneRoot.exists()) {
try {
oldLuceneRoot.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
oldLuceneRoot.move(new Path(LUCENE_FOLDERNAME), false, new NullProgressMonitor());
} catch (CoreException e) {
WGADesignerPlugin.getDefault().logError("Unable to migrate existing lucene folder.", e);
}
}
try {
if(!_luceneRoot.exists()){
FileUtils.createFolder(_wgaData, LUCENE_FOLDERNAME);
}
_luceneRoot.setDerived(true);
} catch (CoreException e1) {
WGADesignerPlugin.getDefault().logError("Unable to set derived flag on folder '" + _luceneRoot.getLocation() + "'.", e1);
}
_developerPluginsRoot = _project.getFolder("plugins");
if (!_developerPluginsRoot.exists()) {
try {
_developerPluginsRoot.create(false, true, new NullProgressMonitor());
} catch (CoreException e) {
WGADesignerPlugin.getDefault().logError("Unable to create folder for developer plugins.", e);
}
}
try {
reloadConfig();
} catch (Exception e) {
WGADesignerPlugin.getDefault().logError("Unable to load runtime configuration.", e);
}
}
public WGARuntimeConfiguration reloadConfig() throws FileNotFoundException, Exception {
FileInputStream configFileStream = null;
try {
configFileStream = new FileInputStream(getConfigFile().getLocation().toFile());
_config = WGARuntimeConfiguration.read(configFileStream);
} finally {
if (configFileStream != null) {
try {
configFileStream.close();
} catch (IOException e) {
}
}
}
return _config;
}
/**
* checks if the nature has been configured yet
*
* @return
*/
private boolean isConfigured() {
if (getProject() != null) {
return getConfigFile().exists();
} else {
return false;
}
}
public IContainer getWGABase() {
return _wgaBase;
}
public IContainer getCatalinaBase() {
return _catalinaBase;
}
public IContainer getCatalinaConf() {
return _catalinaConf;
}
/**
*
* @return
* @throws IncompatibleWGAConfigVersion
* @throws IOException
*/
public Map<String, IContainer> getConnectedDesignContainers() throws IncompatibleWGAConfigVersion, IOException {
Map<String, IContainer> contentDesign = new HashMap<String, IContainer>();
Iterator<ContentStore> itCS = retrieveWGAConfig(false).getContentStores().iterator();
while (itCS.hasNext()) {
ContentStore currentContentStore = itCS.next();
Design currentDesign = currentContentStore.getDesign();
if (currentDesign != null && currentDesign.getSource() != null && currentContentStore.isEnabled() && currentDesign.getSource().equals(Constants.DESIGNCOL_FILESYSTEM)) {
IFolder designFolder = getDesignRoot().getFolder(new Path(currentDesign.getName()));
if (WGADesignStructureHelper.isDirlinkFolder(designFolder)) {
contentDesign.put(currentContentStore.getKey(), (WGADesignStructureHelper.dirLinkFolderToContainer(designFolder)));
} else {
contentDesign.put(currentContentStore.getKey(), designFolder);
}
}
}
return contentDesign;
}
public IFolder[] getDesignsAsFolder() {
return getDesignsAsFolder(true);
}
public IFolder[] getDesignsAsFolder(boolean resolveDirlinks) {
List<IFolder> folders = new ArrayList<IFolder>();
IFolder designroot = (IFolder) getDesignRoot();
try {
IResource resources[] = designroot.members(IFolder.FOLDER);
for (int i = 0; i < resources.length; i++) {
if (resources[i] instanceof IFolder) {
IFolder current = (IFolder) resources[i];
if (WGADesignStructureHelper.isDirlinkFolder(current) && resolveDirlinks) {
current = (IFolder) WGADesignStructureHelper.dirLinkFolderToContainer(current);
}
folders.add(current);
}
}
} catch (CoreException e) {
WGADesignerPlugin.getDefault().logError("Unable to lookup designs of runtime '" + getName() + "'.", e);
}
return folders.toArray(new IFolder[0]);
}
// public IFolder[] getPluginsAsFolder() {
// return getDesignsAsFolder(true);
// }
public IFolder[] getPluginsAsFolder(boolean resolveDirlinks) {
List<IFolder> folders = new ArrayList<IFolder>();
IFolder pluginroot = (IFolder) getPluginRoot();
try {
IResource resources[] = pluginroot.members(IFolder.FOLDER);
for (int i = 0; i < resources.length; i++) {
if (resources[i] instanceof IFolder) {
IFolder current = (IFolder) resources[i];
if (WGADesignStructureHelper.isDirlinkFolder(current) && resolveDirlinks) {
current = (IFolder) WGADesignStructureHelper.dirLinkFolderToContainer(current);
}
folders.add(current);
}
}
} catch (CoreException e) {
WGADesignerPlugin.getDefault().logError("Unable to lookup plugins of runtime '" + getName() + "'.", e);
}
return folders.toArray(new IFolder[0]);
}
public boolean hasDesign(String designName) {
if (designName == null || designName.equals(""))
return false;
IFolder folders[] = getDesignsAsFolder();
for (int i = 0; i < folders.length; i++) {
String existingDesignName = WGADesignStructureHelper.getDesignNameByFolder(folders[i]);
if (existingDesignName != null && existingDesignName.equals(designName)) {
return true;
}
}
return false;
}
public boolean hasDesigns() {
return getDesignsAsFolder().length > 0;
}
/**
* checks if the runtime has a registered development plugin with given name
* - folder with plugin name exists under <runtime>/plugins
*
* @param name
* @return
*/
public boolean hasPlugin(String name) {
return getPluginRoot().getFolder(name).exists();
}
/**
*
* @param contentStore
* @param source
* @return
* @throws IncompatibleWGAConfigVersion
* @throws IOException
*/
public List<ContentStore> getContentStoresWithDesign(WGAConfiguration wgaConf, String designName) throws IncompatibleWGAConfigVersion, IOException {
List<ContentStore> css = new ArrayList<ContentStore>();
Iterator<ContentDatabase> contentDbs = wgaConf.getContentDatabases().iterator();
while (contentDbs.hasNext()) {
ContentDatabase currentDB = contentDbs.next();
if (currentDB instanceof ContentStore) {
ContentStore currentCS = (ContentStore) currentDB;
if (currentCS.getDesign() != null && currentCS.getDesign().getName().equals(designName)) {
css.add(currentCS);
}
}
}
return css;
}
/**
* unregisters a design form runtime by designname only file system design
*
* @param contentDbName
* @throws IOException
* @throws IncompatibleWGAConfigVersion
*/
public void unregisterDesign(String dbKey) throws IncompatibleWGAConfigVersion, IOException {
if (getWGAConfigFile().exists()) {
WGAConfiguration wgaConf = retrieveWGAConfig(false);
List<ContentDatabase> contentDbs = wgaConf.getContentDatabases();
ContentStore currentCS = wgaConf.getContentStore(dbKey);
if (currentCS.getDesign().getSource().equals(Constants.DESIGNCOL_FILESYSTEM)) {
contentDbs.remove(currentCS);
currentCS.setDesign(null);
currentCS.setEnabled(false);
contentDbs.add(currentCS);
}
saveWGAConfig(wgaConf);
}
}
public void changeDesignNameInContentStores(String designNameFrom, String designNameTo) throws IncompatibleWGAConfigVersion, IOException {
WGAConfiguration wgaConf = retrieveWGAConfig(false);
List<ContentDatabase> contentDbs = wgaConf.getContentDatabases();
Iterator<ContentStore> css = getContentStoresWithDesign(wgaConf, designNameFrom).iterator();
while (css.hasNext()) {
ContentStore currentCS = css.next();
if (currentCS.getDesign().getSource().equals(Constants.DESIGNCOL_FILESYSTEM)) {
contentDbs.remove(currentCS);
currentCS.getDesign().setName(designNameTo);
currentCS.setTitle(designNameTo);
contentDbs.add(currentCS);
}
}
saveWGAConfig(wgaConf);
}
/**
* register an internal WGA design in the runtime configuration
*
* @param design
* @param createDB
* create database on embedded server
* @param databaseKey
* dbkey / null will use design name
* @param databaseTitle
* dbtitle / null will use design name
* @param domain
* domain / null will be default domain
*/
public void register(IFolder design, boolean createDB, String databaseKey, String databaseTitle, Domain domain) throws CoreException {
innerRegister(design, createDB, databaseKey, databaseTitle, domain, null);
}
/**
* register an internal WGA design in the runtime configuration
*
* @param design
* @param createDB
* create database on embedded server
* @param databaseKey
* dbkey / null will use design name
* @param databaseTitle
* dbtitle / null will use design name
* @param domain
* domain / null will be default domain
* @param properties
* additional properties for registration
*/
public void register(IFolder design, boolean createDB, String databaseKey, String databaseTitle, Domain domain, Properties properties) throws CoreException {
innerRegister(design, createDB, databaseKey, databaseTitle, domain, properties);
}
/**
* register an external design
*
* @param design
* @param createDB
* create database on embedded server
* @param databaseKey
* dbkey / null will use design name
* @param databaseTitle
* dbtitle / null will use design name
* @param domain
* domain / null will be default domain
* @throws CoreException
*/
public void register(WGADesign design, boolean createDB, String databaseKey, String databaseTitle, Domain domain) throws CoreException {
innerRegister(design, createDB, databaseKey, databaseTitle, domain, null);
}
/**
* register an external design
*
* @param design
* @param createDB
* create database on embedded server
* @param databaseKey
* dbkey / null will use design name
* @param databaseTitle
* dbtitle / null will use design name
* @param domain
* domain / null will be default domain
* @param properties
* additional properties for registration
* @throws CoreException
*/
public void register(WGADesign design, boolean createDB, String databaseKey, String databaseTitle, Domain domain, Properties properties) throws CoreException {
innerRegister(design, createDB, databaseKey, databaseTitle, domain, properties);
}
/**
* register an external or internal WGA design in the runtime configuration
*
* @param design
* either an {@Link WGADesign} or an local design folder
* {@Link IFolder}
*/
private void innerRegister(Object design, boolean createdb, String dbkey, String title, Domain domain, Properties properties) throws CoreException {
if (!(design instanceof WGADesign) && !(design instanceof IFolder)) {
throw new IllegalArgumentException("Illegal design container '" + design.getClass().getName() + "'");
}
if (design instanceof IFolder) {
// check if design folder is local
if (!((IFolder) design).getParent().equals(getDesignRoot())) {
throw new IllegalArgumentException("Given design is not placed in design root '" + getDesignRoot().getLocation().toFile().getAbsolutePath() + "'.");
}
}
if (design instanceof WGADesign) {
WGADesign wgaDesign = (WGADesign) design;
// create new folder and dirlink in design-root
try {
registerExternalDesign(wgaDesign);
} catch (IOException e) {
throw new CoreException(new Status(Status.ERROR, WGADesignerPlugin.PLUGIN_ID, "Unable to register external design.", e));
}
}
if (createdb) {
IContainer container = null;
if (design instanceof WGADesign) {
container = ((WGADesign) design).getProject();
} else {
container = (IFolder) design;
}
WGAConfiguration wgaConfig = null;
try {
wgaConfig = retrieveWGAConfig(true);
} catch (IncompatibleWGAConfigVersion e) {
MessageDialog.openWarning(Display.getDefault().getActiveShell(), "Warning",
"Unable to register design in runtime. WGA Version seams to be incompatible. Please ensure you are using the latest version of WGADevelopmentStudio.");
WGADesignerPlugin.getDefault().logError(e.getMessage(), e);
} catch (IOException e) {
throw new CoreException(new Status(Status.ERROR, WGADesignerPlugin.PLUGIN_ID, "Unable to create default wga configuration.", e));
}
if (wgaConfig != null) {
if (dbkey == null) {
dbkey = container.getName();
}
dbkey = dbkey.toLowerCase();
if (title == null) {
title = container.getName();
}
if (domain == null) {
domain = wgaConfig.getDefaultDomain();
}
// check if db already exists
boolean csExists = wgaConfig.hasContentDatabase(dbkey);
if (csExists) {
throw new CoreException(new Status(Status.ERROR, WGADesignerPlugin.PLUGIN_ID, "A database with key '" + dbkey + "' already exists."));
} else {
int existingDbs = wgaConfig.getContentDatabases().size();
ContentStore cs = wgaConfig.createContentStoreOnEmbeddedServer(dbkey, container.getName());
cs.setDomain(domain.getUid());
cs.setTitle(title);
if (properties != null) {
cs.setDefaultLanguage(properties.getProperty(DesignTemplate.PROP_DEFAULT_LANGUAGE, Locale.getDefault().getLanguage()));
} else {
cs.setDefaultLanguage(Locale.getDefault().getLanguage());
}
// if this is the first autocreated db - make it the default
// db
if (wgaConfig.getDefaultDatabase() == null && existingDbs == 0) {
wgaConfig.setDefaultDatabase(cs.getKey());
}
}
try {
saveWGAConfig(wgaConfig);
} catch (Exception e) {
throw new CoreException(new Status(Status.ERROR, WGADesignerPlugin.PLUGIN_ID, "Unable to update wga configfile.", e));
}
}
}
}
public void registerExternalDesign(WGADesign wgaDesign) throws IOException, CoreException {
IFolder designFolder = getDesignRoot().getFolder(new Path(wgaDesign.getName()));
if (!designFolder.exists()) {
designFolder.create(false, true, new NullProgressMonitor());
createDirlink(wgaDesign, designFolder);
getDesignRoot().refreshLocal(IResource.DEPTH_INFINITE, null);
}
}
public void registerExternalPlugin(WGADesign wgaDesign) throws IOException, CoreException {
IFolder pluginFolder = getPluginRoot().getFolder(wgaDesign.getName());
if (!pluginFolder.exists()) {
pluginFolder.create(false, true, new NullProgressMonitor());
createDirlink(wgaDesign, pluginFolder);
getPluginRoot().refreshLocal(IResource.DEPTH_INFINITE, null);
}
}
public void createDirlink(WGADesign design, IFolder folder) throws IOException {
String relativePrefix = "";
String pathTokens[] = folder.getFullPath().toPortableString().split("/");
for (int i = 0; i < pathTokens.length - 1; i++) {
relativePrefix += "../";
}
String linkTarget = design.getDesignFolder().getFullPath().toPortableString();
if (linkTarget.startsWith("/")) {
linkTarget = linkTarget.substring(1);
}
WGUtils.createDirLink(folder.getLocation().toFile(), relativePrefix + linkTarget);
}
/*
* public void unregister(String design) throws CoreException{ Document
* wgaConfig = null; try { wgaConfig = retrieveWGAConfig(); } catch
* (Exception e) { throw new CoreException(new Status(Status.ERROR,
* WGADesignerPlugin.PLUGIN_ID, "Unable to read wga configfile.", e)); }
*
* List list = wgaConfig.selectNodes("//design[@key='"+design+"']");
* Iterator iter = list.iterator(); if(iter.hasNext()){ Element element =
* (Element) iter.next();
* element.getParent().getParent().remove(element.getParent()); } try {
* saveWGAConfig(wgaConfig); } catch (IOException e) { throw new
* CoreException(new Status(Status.ERROR, WGADesignerPlugin.PLUGIN_ID,
* "Unable to update wga configfile.", e)); }
*
*
* }
*/
/**
* @param createDefaultIfMissing
* @return WGAConfiguration or 'null'
* @throws IncompatibleWGAConfigVersion
* @throws IOException
* - when createDefaultIsMissing is true and default config
* cannot be created
*/
public WGAConfiguration retrieveWGAConfig(boolean createDefaultIfMissing) throws IncompatibleWGAConfigVersion, IOException {
IFile wgaXML = getWGAConfigFile();
if (wgaXML == null) {
// this nature is not configured yet
return null;
}
if (!wgaXML.exists()) {
if (!createDefaultIfMissing) {
return null;
} else {
// create default config
WGAConfiguration config = WGAConfiguration.createDefaultConfig();
// int segmentCount =
// _wgaBase.getLocation().matchingFirstSegments(_luceneRoot.getLocation());
// IPath relativeLucenePath =
// _luceneRoot.getLocation().removeFirstSegments(segmentCount);
// config.getLuceneManagerConfiguration().setPath(relativeLucenePath.toString());
// config.getDesignConfiguration().getDesignSource(Constants.DESIGNCOL_FILESYSTEM).getOptions().put("path",
// "../designs");
Domain defaultDomain = config.getDefaultDomain();
defaultDomain.setDefaultManager("managers");
defaultDomain.createFileBasedAuthentication("auth.xml");
config.getServerOptions().put(WGAConfiguration.SERVEROPTION_SERVER_NAME, getName());
if (getRootURL() != null) {
config.getServerOptions().put(WGAConfiguration.SERVEROPTION_ROOT_URL, getRootURL().toString());
}
// disable install wizard
config.setRunWizard(false);
saveWGAConfig(config);
return config;
}
} else {
synchronized (_wgaConfigLock) {
FileInputStream wgaXMLStream = null;
try {
wgaXMLStream = new FileInputStream(wgaXML.getLocation().toFile());
WGAConfiguration conf = WGAConfiguration.read(wgaXMLStream);
return conf;
} catch (Exception e) {
IncompatibleWGAConfigVersion notConfigurable = new IncompatibleWGAConfigVersion("Unable to read wga configuration.", e);
throw notConfigurable;
} finally {
if (wgaXMLStream != null) {
try {
wgaXMLStream.close();
} catch (IOException e) {
}
}
}
}
}
}
public void saveWGAConfig(WGAConfiguration config) throws IOException {
synchronized (_wgaConfigLock) {
FileOutputStream wgaxmlstream = null;
try {
IFile wgaConfig = getWGABase().getFile(new Path("wgaconfig.xml"));
if (wgaConfig.exists() && wgaConfig.isReadOnly()) {
ResourceAttributes attributes = wgaConfig.getResourceAttributes();
attributes.setReadOnly(false);
wgaConfig.setResourceAttributes(attributes);
}
wgaxmlstream = new FileOutputStream(wgaConfig.getLocation().toFile());
WGAConfiguration.write(config, wgaxmlstream);
_wgaBase.refreshLocal(IResource.DEPTH_ONE, null);
} catch (Exception e) {
IOException ioe = new IOException("Unable to save wga configuration.");
ioe.setStackTrace(e.getStackTrace());
throw ioe;
} finally {
if (wgaxmlstream != null) {
try {
wgaxmlstream.close();
} catch (IOException e) {
}
}
}
}
}
public IFile getWGAConfigFile() {
if (getWGABase() != null) {
return getWGABase().getFile(new Path("wgaconfig.xml"));
} else {
return null;
}
}
public URL getAdminPageURL() {
try {
URL root = getRootURL();
if (root != null) {
return new URL(root.toString() + "/plugin-admin");
} else {
return null;
}
} catch (MalformedURLException e) {
return null;
}
}
public URL getContentManagerURL() {
try {
URL root = getRootURL();
if (root != null) {
return new URL(root.toString() + "/plugin-contentmanager");
} else {
return null;
}
} catch (MalformedURLException e) {
return null;
}
}
public URL getRootURL() {
try {
WGADeployment deployment = WGADesignerPlugin.getDefault().getWGADeploymentManager().getDeployment(getWGADistributionName());
if (deployment != null) {
int port = WGADesignerPlugin.getDefault().getPreferenceStore().getInt(PreferenceConstants.TOMCAT_HTTP_PORT);
return new URL("http://localhost:" + port + deployment.getContextPath());
} else {
return null;
}
} catch (MalformedURLException e) {
return null;
}
}
public URL getVersionURL() {
URL root = getRootURL();
if (root != null) {
WGADeployment deployment = WGADesignerPlugin.getDefault().getWGADeploymentManager().getDeployment(getWGADistributionName());
try {
if (deployment.getWGAVersion().isAtLeast(5, 0)) {
return new URL(root.toString() + "/version.jsp");
} else {
return new URL(root.toString() + "/wgadmin.jsp");
}
} catch (Exception e) {
}
}
return null;
}
public static WGARuntime fromSelection(ISelection selection) {
if (selection instanceof IStructuredSelection) {
IStructuredSelection structSelection = (IStructuredSelection) selection;
Object selectedElement = structSelection.getFirstElement();
IProject project = null;
if (selectedElement instanceof IProject) {
project = (IProject) selectedElement;
} else if (selectedElement instanceof IResource) {
project = ((IResource) selectedElement).getProject();
}
try {
if (project != null && project.hasNature(WGADesignerPlugin.NATURE_WGA_RUNTIME)) {
return (WGARuntime) project.getNature(WGADesignerPlugin.NATURE_WGA_RUNTIME);
}
} catch (Exception e) {
}
}
return null;
}
public List<String> getWGALaunchVMArguments() {
List<String> vmArgs = new ArrayList<String>();
IPreferenceStore store = WGADesignerPlugin.getDefault().getPreferenceStore();
vmArgs.add("-Xms" + store.getInt(PreferenceConstants.JAVA_MIN_HEAP_SIZE) + "m");
vmArgs.add("-Xmx" + store.getInt(PreferenceConstants.JAVA_MAX_HEAP_SIZE) + "m");
vmArgs.add("-XX:PermSize=" + store.getInt(PreferenceConstants.JAVA_MIN_PERMGEN_SIZE) + "m");
vmArgs.add("-XX:MaxPermSize=" + store.getInt(PreferenceConstants.JAVA_MAX_PERMGEN_SIZE) + "m");
String wgaBasePath = getWGABase().getLocation().toFile().getAbsolutePath();
vmArgs.add("-Dde.innovationgate.wga.configpath=\"" + wgaBasePath + "\"");
vmArgs.add("-Dde.innovationgate.wga.auth.folder=\"" + wgaBasePath + "\"");
vmArgs.add("-Dde.innovationgate.wga.wfdefinitions=\"" + getWorkflowRoot().getLocation().toFile().getAbsolutePath() + "\"");
vmArgs.add("-Dde.innovationgate.wga.hsql.root=\"" + getHsqlRoot().getLocation().toFile().getAbsolutePath() + "\"");
vmArgs.add("-D" + WGAConfiguration.SYSPROP_DESIGN_ROOT + "=\"../designs\"");
vmArgs.add("-Dde.innovationgate.wga.devplugins=\"" + _developerPluginsRoot.getLocation().toFile().getAbsolutePath() + "\"");
int segmentCount = _wgaBase.getLocation().matchingFirstSegments(_luceneRoot.getLocation());
vmArgs.add("-D" + WGAConfiguration.SYSPROP_LUCENE_ROOT + "=\"" + _luceneRoot.getLocation().removeFirstSegments(segmentCount) + "\"");
vmArgs.add("-Dde.innovationgate.wga.tmlscript.debug=\"" + Boolean.toString(store.getBoolean(PreferenceConstants.TMLSCRIPT_DEBUG)) + "\"");
WGADeployment deployment = WGADesignerPlugin.getDefault().getWGADeploymentManager().getDeployment(getWGADistributionName());
if (deployment != null) {
vmArgs.add("-Dde.innovationgate.wga.defaultplugins=\"" + deployment.getDefaultPluginsDir().getAbsolutePath() + "\"");
}
vmArgs.add("-Dde.innovationgate.wga.skipLocalAdminLogins=true");
vmArgs.add("-Dde.innovationgate.wga.outputWarningsOnConsole=true");
// enable jmx - necessary for development mode check
vmArgs.add("-Dcom.sun.management.jmxremote");
vmArgs.add("-Dde.innovationgate.license.DevelopmentModeEnabled=true");
if (deployment != null) {
vmArgs.add("-Dde.innovationgate.license.WGAContextPath=\"" + deployment.getContextPath() + "\"");
}
if (_config.getJvmOptions() != null) {
Iterator<String> options = WGUtils.deserializeCollection(_config.getJvmOptions(), "\n").iterator();
while (options.hasNext()) {
String option = options.next();
option = option.replaceAll("\\{\\$cfg.dir\\}", getWGABase().getLocation().toString());
option = option.replaceAll("\\{\\$project.dir\\}", getProject().getLocation().toString());
vmArgs.add(option);
}
}
return vmArgs;
}
public String getWGADistributionName() {
return _config.getWgaDistribution();
}
public IContainer getCatalinaLibDir() {
return _catalinaLibdir;
}
public IFile getConfigFile() {
return _project.getFile("runtime.xml");
}
public WGARuntimeConfiguration getConfiguration() {
return _config;
}
public void flushConfig() throws CoreException {
FileOutputStream configFileStream = null;
try {
IFile configFile = getConfigFile();
if (configFile.isReadOnly()) {
ResourceAttributes attributes = configFile.getResourceAttributes(); // ResourceAttributes.fromFile(configFile.getLocation().toFile());
attributes.setReadOnly(false);
configFile.setResourceAttributes(attributes);
}
// we might have to update root url bc. of distribution changes
if (getRootURL() != null) {
WGAConfiguration wgaConfig = retrieveWGAConfig(false);
if (wgaConfig != null) {
wgaConfig.getServerOptions().put(WGAConfiguration.SERVEROPTION_ROOT_URL, getRootURL().toString());
saveWGAConfig(wgaConfig);
}
}
configFileStream = new FileOutputStream(configFile.getLocation().toFile());
WGARuntimeConfiguration.write(_config, configFileStream);
_project.refreshLocal(IResource.DEPTH_ONE, null);
} catch (Exception e) {
WGADesignerPlugin.getDefault().logError("Unable to save config of runtime '" + getName() + "'.", e);
throw new CoreException(new Status(Status.ERROR, WGADesignerPlugin.PLUGIN_ID, "Unable to save config of runtime '" + getName() + "'.", e));
} finally {
try {
if (configFileStream != null) {
configFileStream.close();
}
} catch (IOException e) {
}
}
}
public IEditorPart openEditor() throws PartInitException {
return WorkbenchUtils.openEditor(WGADesignerPlugin.getDefault().getWorkbench(), getConfigFile(), ResourceIDs.EDITOR_WGA_RUNTIME);
}
public IFolder getWgaData() {
return _wgaData;
}
public IFolder getWorkflowRoot() {
return _workflowRoot;
}
@Override
protected void finalize() throws Throwable {
ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
super.finalize();
}
public void resourceChanged(IResourceChangeEvent event) {
if (event.getDelta() != null) {
IFile wgaconfig = getWGAConfigFile();
if (wgaconfig != null && wgaconfig.isAccessible()) {
IResourceDelta delta = event.getDelta().findMember(getWGAConfigFile().getFullPath());
if (delta != null) {
// wga config changed
fireWGAConfigurationChanged();
}
}
}
}
private void fireWGAConfigurationChanged() {
for (WGARuntimeListener listener : _listeners) {
try {
listener.wgaConfigurationChanged(retrieveWGAConfig(false));
} catch (Throwable e) {
WGADesignerPlugin.getDefault().logError("Unable to notify WGARuntimListener '" + listener.getClass().getName() + "'.", e);
}
}
}
public void addListener(WGARuntimeListener o) {
_listeners.add(o);
}
public void removeListener(Object o) {
_listeners.remove(o);
}
public URL getContentManagerURL(ContentStore contentStore) {
try {
return new URL(getContentManagerURL() + "/html/contentstore?dbkey=" + contentStore.getKey() + "&username=designer&password=wga");
} catch (MalformedURLException e) {
return null;
}
}
public URL getDefaultURL(ContentStore contentStore) {
try {
return new URL(getRootURL() + "/" + contentStore.getKey());
} catch (MalformedURLException e) {
return null;
}
}
public URL getAdminClientURL(ContentStore contentStore) {
try {
return new URL(getAdminPageURL() + "/html/home?app=webprojects&uid=" + contentStore.getUid());
} catch (MalformedURLException e) {
return null;
}
}
public WGARemoteServer createRemoteServer() throws Exception {
return new WGARemoteServer("local", getRootURL(), "unused", "unused");
}
public IContainer getDesignContainer(ContentStore contentStore) throws IncompatibleWGAConfigVersion, IOException {
return getConnectedDesignContainers().get(contentStore.getKey());
}
}