blob: bbf25b3f0d08682a3601817b455cf7fd026f1340 [file] [log] [blame]
//------------------------------------------------------------------------------
// Copyright (c) 2005, 2006 IBM Corporation and others.
// 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:
// IBM Corporation - initial implementation
//------------------------------------------------------------------------------
package org.eclipse.epf.library.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.edit.provider.DelegatingWrapperItemProvider;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
import org.eclipse.epf.common.utils.FileUtil;
import org.eclipse.epf.library.LibraryResources;
import org.eclipse.epf.library.edit.TransientGroupItemProvider;
import org.eclipse.epf.library.edit.navigator.ConfigurationsItemProvider;
import org.eclipse.epf.library.services.LibraryProcessor;
import org.eclipse.epf.persistence.MultiFileResourceSetImpl;
import org.eclipse.epf.persistence.MultiFileSaveUtil;
import org.eclipse.epf.resourcemanager.ResourceDescriptor;
import org.eclipse.epf.resourcemanager.ResourceManager;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.xml.sax.SAXException;
import com.ibm.uma.ContentElement;
import com.ibm.uma.Domain;
import com.ibm.uma.MethodConfiguration;
import com.ibm.uma.MethodElement;
import com.ibm.uma.MethodPlugin;
import com.ibm.uma.Process;
import com.ibm.uma.ProcessComponent;
import com.ibm.uma.Task;
import com.ibm.uma.TaskDescriptor;
public class ImportExportUtil {
public static final String NEW_LINE = System.getProperty(
"line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
/**
* gets a Logger for all import/export routines
*
* @param classname
* @param filename
* @return
*/
public static Logger getLogger(String classname, String filename) {
Logger logger = Logger.getLogger(classname);
try {
new File(filename).getParentFile().mkdirs();
FileHandler fh = new FileHandler(filename, false);
fh.setFormatter(new SimpleFormatter() {
public String format(LogRecord rec) {
StringBuffer buf = new StringBuffer(1000);
buf.append(new java.util.Date());
buf.append(' ');
// buf.append(rec.getLevel());
// buf.append(' ');
buf.append(formatMessage(rec));
buf.append('\n');
return buf.toString();
}
});
fh.setLevel(Level.ALL);
logger.addHandler(fh);
logger.setUseParentHandlers(false);
} catch (Exception ex) {
ex.printStackTrace();
}
return logger;
}
public static void closeLog(Logger logger) {
Handler[] handlers = logger.getHandlers();
for (int i = 0; i < handlers.length; i++)
handlers[i].close();
}
/**
* given a directory and extension, returns all files (recursively) whose
* extension startsWith the given extension
*
* @param f
* @param extension
* @return
*/
public static List fileList(File f, String extension) {
extension = extension.toUpperCase();
List returnList = new ArrayList();
try {
if (f.isDirectory()) { // if dir then recurse
String[] flist = f.list();
for (int i = 0; i < flist.length; ++i) {
File fc = new File(f.getPath(), flist[i]);
returnList.addAll(fileList(fc, extension));
}
} else { // ordinary file
if (extension != null) {
String name = f.getName().toUpperCase();
if (name.lastIndexOf(".") != -1) //$NON-NLS-1$
if (name
.substring(name.lastIndexOf(".") + 1).startsWith(extension)) { //$NON-NLS-1$
returnList.add(f);
}
} else
returnList.add(f);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return returnList;
}
/**
* given a directory and extension, returns all files (recursively)whose
* extension does not startsWith the given extension
*
* @param f
* @param extension
* @return
*/
public static List fileListExcludeExt(File f, String extension) {
List returnList = new ArrayList();
try {
if (f.isDirectory()) { // if dir then recurse
String[] flist = f.list();
for (int i = 0; i < flist.length; ++i) {
File fc = new File(f.getPath(), flist[i]);
returnList.addAll(fileListExcludeExt(fc, extension));
}
} else { // ordinary file
if (extension != null) {
String name = f.getName();
if (name.lastIndexOf(".") != -1) //$NON-NLS-1$
if (!(name.substring(name.lastIndexOf(".") + 1).startsWith(extension))) { //$NON-NLS-1$
returnList.add(f);
}
} else
returnList.add(f);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return returnList;
}
private static void addGuidsOfMethodElement(MethodElement element,
List list, List children) {
list.add(element.getGuid());
// now add stuff that is shown as children in lib nav
for (Iterator iter = element.eAdapters().iterator(); iter.hasNext();) {
Object adapter = iter.next();
if (adapter instanceof ItemProviderAdapter) {
children.addAll(((ItemProviderAdapter) adapter)
.getChildren(element));
break;
}
}
if (element instanceof Domain) {
children.addAll(((Domain) element).getWorkProducts());
} else if (element instanceof MethodConfiguration) {
children.addAll(((MethodConfiguration) element)
.getMethodPackageSelection());
// children.addAll(((MethodConfiguration)o).getMethodPluginSelection());
}
if (element instanceof ContentElement) {
children.addAll(((ContentElement) element).getAssets());
children.addAll(((ContentElement) element).getChecklists());
children.addAll(((ContentElement) element).getConceptsAndPapers());
children.addAll(((ContentElement) element).getExamples());
children.addAll(((ContentElement) element).getGuidelines());
children
.addAll(((ContentElement) element).getSupportingMaterials());
}
}
/**
* Given an object (from the library navigator), creates a list of children.
* Used by Internal export wizards to determine which elements to export
* based on user selection.
*
* @param o
* @return
*/
private static Collection getMethodElementChildren(Object o, Set visitedElements) {
List list = new ArrayList();
List children = new ArrayList();
if (o == null)
return list;
if (visitedElements.contains(o)) {
return list;
}
else
visitedElements.add(o);
if (o instanceof MethodElement) {
addGuidsOfMethodElement((MethodElement) o, list, children);
} else if (o instanceof TransientGroupItemProvider) {
children.addAll(((TransientGroupItemProvider) o).getChildren(o));
} else if (o instanceof ItemProviderAdapter) {
children.addAll(((ItemProviderAdapter) o).getChildren(o));
} else if (o instanceof DelegatingWrapperItemProvider) {
Object e = ((DelegatingWrapperItemProvider) o).getEditableValue(o);
if (e instanceof MethodElement)
addGuidsOfMethodElement((MethodElement) e, list, children);
children.addAll(((DelegatingWrapperItemProvider) o).getChildren(o));
} else if (o instanceof ConfigurationsItemProvider) {
children.addAll(((ConfigurationsItemProvider) o).getChildren(o));
}
if (children != null && children.size() > 0) {
Iterator iterator = children.iterator();
while (iterator.hasNext()) {
Object obj = (Object) iterator.next();
list.addAll(getMethodElementChildren(obj, visitedElements));
}
}
return list;
}
public static Collection getSelectedElements(IStructuredSelection selection) {
List exportList = new ArrayList();
if (selection != null && selection.size() > 0) {
Iterator iter = selection.iterator();
while (iter.hasNext()) {
Object o = iter.next();
if (o instanceof MethodPlugin) {
MethodPlugin e = (MethodPlugin) o;
// // initialize list of elements to export
exportList.add(e.getGuid());
} else
exportList.addAll(getMethodElementChildren(o, new HashSet()));
}
} else {
// selection is null, so export whole library
List pluginList = LibraryProcessor.getInstance().getMethodModels();
Iterator iter = pluginList.iterator();
while (iter.hasNext()) {
MethodPlugin plugin = (MethodPlugin) iter.next();
exportList.add(plugin.getGuid());
}
}
return exportList;
}
/**
* Escapes the given string to make it HTML friendly. Converts '&' to
* "&amp;"
*
* @param str
* The source string.
* @return The escaped string.
*/
public static String escapeHTML(String str) {
StringBuffer sb = new StringBuffer();
int len = (str == null) ? 0 : str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
switch (ch) {
case '&':
sb.append("&amp;"); //$NON-NLS-1$
break;
default:
sb.append(ch);
break;
}
}
return sb.toString();
}
/**
* The reverse of escapeHTML - converts "&amp;" to '&'
*
* @param str
* @return
*/
public static String unescapeHTML(String str) {
if (str == null)
return ""; //$NON-NLS-1$
str = str.replaceAll("&amp;", "&"); //$NON-NLS-1$ //$NON-NLS-2$
return str;
}
public static String findPresUri(ResourceManager resMgr, String guid)
throws RuntimeException {
String presUri = null;
try {
ResourceDescriptor resDesc = MultiFileSaveUtil
.findResourceDescriptor(resMgr, guid);
if (resDesc != null) {
presUri = resDesc.getResolvedURI().toFileString();
} else {
MethodElement e = LibraryProcessor.getInstance().getElement(
guid);
if (e != null)
presUri = e.eResource().getURI().toFileString();
}
return presUri;
} catch (RuntimeException e) {
throw e;
}
}
public static void replace(ProcessComponent procComp, String dir)
throws IOException, ParserConfigurationException,
FactoryConfigurationError, SAXException {
File newProcCompFile = new File(dir,
MultiFileSaveUtil.DEFAULT_MODEL_FILENAME);
if (!newProcCompFile.exists()) {
throw new FileNotFoundException(
MessageFormat
.format(
LibraryResources
.getString("Library.ImportExportUtil.MSG8"), new Object[] { newProcCompFile })); //$NON-NLS-1$
}
String oldModelFileStr = procComp.eResource().getURI().toFileString();
String oldProcCompDir = new File(oldModelFileStr).getParent();
String suffix = MultiFileSaveUtil.getBackupFileSuffix();
File tempDir = null;
try {
// copy dir a temp dir inside the target dir
//
tempDir = new File(oldProcCompDir, suffix);
if (!tempDir.mkdir()) {
throw new IOException(
MessageFormat
.format(
LibraryResources
.getString("Library.ImportExportUtil.MSG9"), new Object[] { tempDir })); //$NON-NLS-1$
}
FileUtil.copydirectory(new File(dir), tempDir);
newProcCompFile = new File(tempDir,
MultiFileSaveUtil.DEFAULT_MODEL_FILENAME);
// load the new model.xmi
//
MultiFileResourceSetImpl resourceSet = (MultiFileResourceSetImpl) procComp
.eResource().getResourceSet();
Resource newResource = resourceSet.getResource(URI
.createFileURI(newProcCompFile.getAbsolutePath()), true);
// fix configuration references
//
ProcessComponent newProcComp = (ProcessComponent) MultiFileSaveUtil
.getMethodElement(newResource);
Process newProc = newProcComp.getProcess();
newProc
.setDefaultContext(procComp.getProcess()
.getDefaultContext());
newProc.getValidContext().clear();
newProc.getValidContext().addAll(
procComp.getProcess().getValidContext());
// fix all steps
//
for (Iterator iter = newProcComp.eAllContents(); iter.hasNext();) {
Object element = iter.next();
if (element instanceof TaskDescriptor) {
TaskDescriptor taskDesc = (TaskDescriptor) element;
Task task = taskDesc.getTask();
String taskName = task == null ? "NONE" : "'" + task.getName() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
System.out.println("Task: " + taskName); //$NON-NLS-1$
if (task != null) {
taskDesc.getSelectedSteps().clear();
taskDesc.getSelectedSteps().addAll(task.getSteps());
}
}
}
// replace GUID of new ProcessComponent and its ResourceManager with
// old ones
//
// // read the model.xmi file
// DocumentBuilder builder =
// DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Document doc = builder.parse(newProcCompFile);
// set GUID of new ResourceManager to old GUID
ResourceManager resMgr = MultiFileSaveUtil
.getResourceManager(procComp.eResource());
if (resMgr != null) {
MultiFileSaveUtil.getResourceManager(newResource).setGuid(
resMgr.getGuid());
}
// NodeList list =
// doc.getElementsByTagName("com.ibm.uma.resourcemanager:ResourceManager");
// Element e = (Element) list.item(0);
// e.setAttribute("xmi:id", guid);
// e.setAttribute("guid", guid);
// set GUID of new ProcessComponent to old GUID
newProcComp.setGuid(procComp.getGuid());
// guid = procComp.getGuid();
// list = doc.getElementsByTagName("com.ibm.uma:ProcessComponent");
// e = (Element) list.item(0);
// e.setAttribute("xmi:id", guid);
// e.setAttribute("guid", guid);
// save the new model.xmi
//
newResource.save(LibraryProcessor.getInstance().getSaveOptions());
// back up old model.xmi
File file = new File(oldModelFileStr);
file.renameTo(new File(oldModelFileStr + ".bak" + suffix)); //$NON-NLS-1$
newProcCompFile.renameTo(new File(oldModelFileStr));
// XMLUtil.saveDocument(doc, oldModelFileStr);
File newContentFile = new File(tempDir,
MultiFileSaveUtil.DEFAULT_CONTENT_FILENAME);
// back up old content.xmi
String contentFileStr = oldProcCompDir + File.separator
+ MultiFileSaveUtil.DEFAULT_CONTENT_FILENAME;
File oldContentFile = new File(contentFileStr);
oldContentFile.renameTo(new File(contentFileStr + ".bak" + suffix)); //$NON-NLS-1$
// copy new content.xmi
if (newContentFile.exists()) {
newContentFile.renameTo(oldContentFile);
}
} finally {
if (tempDir != null) {
FileUtil.deleteAllFiles(tempDir.getAbsolutePath());
tempDir.delete();
}
}
}
}