import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
import org.argeo.cms.auth.AuthConstants;
import org.argeo.cms.auth.HttpRequestCallbackHandler;
import org.argeo.eclipse.ui.specific.UiContext;
loginContext = new LoginContext(AuthConstants.LOGIN_CONTEXT_ANONYMOUS, subject);
loginContext.login();
} catch (LoginException e1) {
- throw new ArgeoException("Cannot log as anonymous", e);
+ throw new CmsException("Cannot log as anonymous", e);
}
} catch (LoginException e) {
- throw new ArgeoException("Cannot initialize subject", e);
+ throw new CmsException("Cannot initialize subject", e);
}
authChange(loginContext);
package org.argeo.cms;
-import org.argeo.ArgeoException;
-
/** CMS specific exceptions. */
-public class CmsException extends ArgeoException {
+public class CmsException extends RuntimeException {
private static final long serialVersionUID = -5341764743356771313L;
public CmsException(String message) {
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.eclipse.ui.specific.UiContext;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
if (options.containsKey("anonymous"))
isAnonymous = Boolean.parseBoolean(options.get("anonymous").toString());
} catch (Exception e) {
- throw new ArgeoException("Cannot initialize login module", e);
+ throw new CmsException("Cannot initialize login module", e);
}
}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
import org.argeo.cms.CmsEditable;
import org.argeo.cms.CmsException;
import org.argeo.cms.CmsImageManager;
section.layout();
section.getParent().layout();
} catch (RepositoryException re) {
- throw new ArgeoException("unable to refresh "
+ throw new CmsException("unable to refresh "
+ "image section for " + context);
}
}
});
} catch (RepositoryException re) {
- throw new ArgeoException("unable to upload image " + name
+ throw new CmsException("unable to upload image " + name
+ " at " + context);
}
}
refresh(parSection);
layout(parSection);
} catch (RepositoryException re) {
- throw new ArgeoException("Unable to delete "
+ throw new CmsException("Unable to delete "
+ sessionNode, re);
}
edit(emsp, 0);
cancelEdit();
} catch (RepositoryException e1) {
- throw new ArgeoException(
+ throw new CmsException(
"Unable to remove value " + obj, e1);
}
layout(emsp);
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.CmsView;
import org.argeo.cms.util.CmsUtils;
import org.argeo.eclipse.ui.EclipseUiUtils;
try {
cmsView.navigateTo(node.getPath());
} catch (RepositoryException e) {
- throw new ArgeoException("Unable to get path for node "
+ throw new CmsException("Unable to get path for node "
+ node + " before calling navigateTo(path)", e);
}
}
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
/** Callback handler to be used with a command line UI. */
public class ConsoleCallbackHandler implements CallbackHandler {
UnsupportedCallbackException {
Console console = System.console();
if (console == null)
- throw new ArgeoException("No console available");
+ throw new CmsException("No console available");
PrintWriter writer = console.writer();
for (int i = 0; i < callbacks.length; i++) {
import javax.security.auth.callback.LanguageCallback;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
/** Choose in a list of locales. TODO: replace with {@link LanguageCallback} */
public class LocaleChoice {
defaultIndex = i;
if (defaultIndex == null)
- throw new ArgeoException("Default locale " + defaultLocale + " is not in available locales " + locales);
+ throw new CmsException("Default locale " + defaultLocale + " is not in available locales " + locales);
this.defaultIndex = defaultIndex;
this.selectedIndex = defaultIndex;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
/**
* Simplify atomic backups implementation, especially by managing VFS.
public void init() {
if (name == null)
- throw new ArgeoException("Atomic backup name must be set");
+ throw new CmsException("Atomic backup name must be set");
}
public void destroy() {
String backupsBase, BackupContext backupContext,
FileSystemOptions opts) {
if (name == null)
- throw new ArgeoException("Atomic backup name must be set");
+ throw new CmsException("Atomic backup name must be set");
FileObject targetFo = null;
try {
+ '/' + backupContext.getRelativeFolder() + '/' + name
+ ".gz" + "!" + name, opts);
else
- throw new ArgeoException("Unsupported compression "
+ throw new CmsException("Unsupported compression "
+ compression);
writeBackup(targetFo);
return targetFo.toString();
} catch (Exception e) {
- throw new ArgeoException("Cannot backup " + name + " to "
+ throw new CmsException("Cannot backup " + name + " to "
+ targetFo, e);
} finally {
BackupUtils.closeFOQuietly(targetFo);
import org.apache.commons.vfs2.provider.ram.RamFileProvider;
import org.apache.commons.vfs2.provider.sftp.SftpFileProvider;
import org.apache.commons.vfs2.provider.url.UrlFileProvider;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
/**
* Programatically configured VFS file system manager which can be declared as a
addProvider("ram", new RamFileProvider());
setDefaultProvider(new UrlFileProvider());
} catch (FileSystemException e) {
- throw new ArgeoException("Cannot configure backup file provider", e);
+ throw new CmsException("Cannot configure backup file provider", e);
}
}
}
package org.argeo.cms.internal.backup;
import org.apache.commons.vfs2.FileObject;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
/** Backups an OpenLDAP server using slapcat */
public class OpenLdapBackup extends OsCallBackup {
@Override
public void writeBackup(FileObject targetFo) {
if (baseDn == null)
- throw new ArgeoException("Base DN must be set");
+ throw new CmsException("Base DN must be set");
if (getCommand() == null)
setCommand(slapcatLocation
import org.apache.commons.logging.LogFactory;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileObject;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
/**
* Runs an OS command and save its standard output as a file. Typically used for
// stdout
FileContent targetContent = targetFo.getContent();
// stderr
- ExecuteStreamHandler streamHandler = new PumpStreamHandler(
- targetContent.getOutputStream(), errBos);
+ ExecuteStreamHandler streamHandler = new PumpStreamHandler(targetContent.getOutputStream(), errBos);
executor.setStreamHandler(streamHandler);
executor.execute(commandLine, environment);
} catch (ExecuteException e) {
byte[] err = errBos.toByteArray();
String errStr = new String(err);
- throw new ArgeoException("Process " + commandLine + " failed ("
- + e.getExitValue() + "): " + errStr, e);
+ throw new CmsException("Process " + commandLine + " failed (" + e.getExitValue() + "): " + errStr, e);
} catch (Exception e) {
byte[] err = errBos.toByteArray();
String errStr = new String(err);
- throw new ArgeoException("Process " + commandLine + " failed: "
- + errStr, e);
+ throw new CmsException("Process " + commandLine + " failed: " + errStr, e);
} finally {
IOUtils.closeQuietly(errBos);
}
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.joda.time.DateTime;
import org.joda.time.Period;
log.debug("Deleted backup " + backupFo);
}
} catch (Exception e) {
- throw new ArgeoException("Could not purge previous backups", e);
+ throw new CmsException("Could not purge previous backups", e);
}
}
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.UserAuthenticator;
import org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
+import org.argeo.util.LangUtils;
/**
* Combines multiple backups and transfer them to a remote location. Purges
@Override
public void run() {
if (atomicBackups.size() == 0)
- throw new ArgeoException("No atomic backup listed");
+ throw new CmsException("No atomic backup listed");
List<String> failures = new ArrayList<String>();
- SimpleBackupContext backupContext = new SimpleBackupContext(
- fileSystemManager, backupsBase, systemName);
+ SimpleBackupContext backupContext = new SimpleBackupContext(fileSystemManager, backupsBase, systemName);
// purge older backups
FileSystemOptions opts = new FileSystemOptions();
try {
- DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(
- opts, userAuthenticator);
+ DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, userAuthenticator);
} catch (FileSystemException e) {
- throw new ArgeoException("Cannot create authentication", e);
+ throw new CmsException("Cannot create authentication", e);
}
try {
- backupPurge.purge(fileSystemManager, backupsBase, systemName,
- backupContext.getDateFormat(), opts);
+ backupPurge.purge(fileSystemManager, backupsBase, systemName, backupContext.getDateFormat(), opts);
} catch (Exception e) {
failures.add("Purge " + backupsBase + " failed: " + e.getMessage());
log.error("Purge of " + backupsBase + " failed", e);
// perform backup
for (AtomicBackup atomickBackup : atomicBackups) {
try {
- String target = atomickBackup.backup(fileSystemManager,
- backupsBase, backupContext, opts);
+ String target = atomickBackup.backup(fileSystemManager, backupsBase, backupContext, opts);
if (log.isDebugEnabled())
log.debug("Performed backup " + target);
} catch (Exception e) {
- String msg = "Atomic backup " + atomickBackup.getName()
- + " failed: " + ArgeoException.chainCausesMessages(e);
+ String msg = "Atomic backup " + atomickBackup.getName() + " failed: "
+ + LangUtils.chainCausesMessages(e);
failures.add(msg);
log.error(msg);
if (log.isTraceEnabled())
- log.trace(
- "Stacktrace of atomic backup "
- + atomickBackup.getName() + " failure.", e);
+ log.trace("Stacktrace of atomic backup " + atomickBackup.getName() + " failure.", e);
}
}
// authentication
FileSystemOptions remoteOpts = new FileSystemOptions();
try {
- DefaultFileSystemConfigBuilder.getInstance()
- .setUserAuthenticator(remoteOpts, auth);
- backupPurge.purge(fileSystemManager, remoteBase, systemName,
- backupContext.getDateFormat(), remoteOpts);
+ DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(remoteOpts, auth);
+ backupPurge.purge(fileSystemManager, remoteBase, systemName, backupContext.getDateFormat(), remoteOpts);
} catch (Exception e) {
- failures.add("Purge " + remoteBase + " failed: "
- + e.getMessage());
+ failures.add("Purge " + remoteBase + " failed: " + e.getMessage());
log.error("Cannot purge " + remoteBase, e);
}
try {
- localBaseFo = fileSystemManager.resolveFile(backupsBase + '/'
- + backupContext.getRelativeFolder(), opts);
- remoteBaseFo = fileSystemManager.resolveFile(remoteBase + '/'
- + backupContext.getRelativeFolder(), remoteOpts);
+ localBaseFo = fileSystemManager.resolveFile(backupsBase + '/' + backupContext.getRelativeFolder(),
+ opts);
+ remoteBaseFo = fileSystemManager.resolveFile(remoteBase + '/' + backupContext.getRelativeFolder(),
+ remoteOpts);
remoteBaseFo.copyFrom(localBaseFo, Selectors.SELECT_ALL);
if (log.isDebugEnabled())
- log.debug("Copied backup to " + remoteBaseFo + " from "
- + localBaseFo);
+ log.debug("Copied backup to " + remoteBaseFo + " from " + localBaseFo);
// }
} catch (Exception e) {
- failures.add("Dispatch to " + remoteBase + " failed: "
- + e.getMessage());
- log.error(
- "Cannot dispatch backups from "
- + backupContext.getRelativeFolder() + " to "
- + remoteBase, e);
+ failures.add("Dispatch to " + remoteBase + " failed: " + e.getMessage());
+ log.error("Cannot dispatch backups from " + backupContext.getRelativeFolder() + " to " + remoteBase, e);
}
BackupUtils.closeFOQuietly(localBaseFo);
BackupUtils.closeFOQuietly(remoteBaseFo);
if (failures.size() > 0) {
StringBuffer buf = new StringBuffer();
for (String failure : failures) {
- buf.append('\n').append(failureCount).append(" - ")
- .append(failure);
+ buf.append('\n').append(failureCount).append(" - ").append(failure);
failureCount++;
}
- throw new ArgeoException(failureCount
- + " error(s) when running the backup,"
- + " check the logs and the backups as soon as possible."
- + buf);
+ throw new CmsException(failureCount + " error(s) when running the backup,"
+ + " check the logs and the backups as soon as possible." + buf);
}
}
this.remoteBases = remoteBases;
}
-// public static void main(String args[]) {
-// while (true) {
-// try {
-// StandardFileSystemManager fsm = new StandardFileSystemManager();
-// fsm.init();
-//
-// SystemBackup systemBackup = new SystemBackup();
-// systemBackup.setSystemName("mySystem");
-// systemBackup
-// .setBackupsBase("/home/mbaudier/dev/src/commons/server/runtime/org.argeo.server.core/target");
-// systemBackup.setFileSystemManager(fsm);
-//
-// List<AtomicBackup> atomicBackups = new ArrayList<AtomicBackup>();
-//
-// MySqlBackup mySqlBackup = new MySqlBackup("root", "", "test");
-// atomicBackups.add(mySqlBackup);
-// PostgreSqlBackup postgreSqlBackup = new PostgreSqlBackup(
-// "argeo", "argeo", "gis_template");
-// atomicBackups.add(postgreSqlBackup);
-// SvnBackup svnBackup = new SvnBackup(
-// "/home/mbaudier/tmp/testsvnrepo");
-// atomicBackups.add(svnBackup);
-//
-// systemBackup.setAtomicBackups(atomicBackups);
-//
-// Map<String, UserAuthenticator> remoteBases = new HashMap<String, UserAuthenticator>();
-// StaticUserAuthenticator userAuthenticator = new StaticUserAuthenticator(
-// null, "demo", "demo");
-// remoteBases.put("sftp://localhost/home/mbaudier/test",
-// userAuthenticator);
-// systemBackup.setRemoteBases(remoteBases);
-//
-// systemBackup.run();
-//
-// fsm.close();
-// } catch (FileSystemException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// System.exit(1);
-// }
-//
-// // wait
-// try {
-// Thread.sleep(120 * 1000);
-// } catch (InterruptedException e) {
-// e.printStackTrace();
-// }
-// }
-// }
+ // public static void main(String args[]) {
+ // while (true) {
+ // try {
+ // StandardFileSystemManager fsm = new StandardFileSystemManager();
+ // fsm.init();
+ //
+ // SystemBackup systemBackup = new SystemBackup();
+ // systemBackup.setSystemName("mySystem");
+ // systemBackup
+ // .setBackupsBase("/home/mbaudier/dev/src/commons/server/runtime/org.argeo.server.core/target");
+ // systemBackup.setFileSystemManager(fsm);
+ //
+ // List<AtomicBackup> atomicBackups = new ArrayList<AtomicBackup>();
+ //
+ // MySqlBackup mySqlBackup = new MySqlBackup("root", "", "test");
+ // atomicBackups.add(mySqlBackup);
+ // PostgreSqlBackup postgreSqlBackup = new PostgreSqlBackup(
+ // "argeo", "argeo", "gis_template");
+ // atomicBackups.add(postgreSqlBackup);
+ // SvnBackup svnBackup = new SvnBackup(
+ // "/home/mbaudier/tmp/testsvnrepo");
+ // atomicBackups.add(svnBackup);
+ //
+ // systemBackup.setAtomicBackups(atomicBackups);
+ //
+ // Map<String, UserAuthenticator> remoteBases = new HashMap<String,
+ // UserAuthenticator>();
+ // StaticUserAuthenticator userAuthenticator = new StaticUserAuthenticator(
+ // null, "demo", "demo");
+ // remoteBases.put("sftp://localhost/home/mbaudier/test",
+ // userAuthenticator);
+ // systemBackup.setRemoteBases(remoteBases);
+ //
+ // systemBackup.run();
+ //
+ // fsm.close();
+ // } catch (FileSystemException e) {
+ // // TODO Auto-generated catch block
+ // e.printStackTrace();
+ // System.exit(1);
+ // }
+ //
+ // // wait
+ // try {
+ // Thread.sleep(120 * 1000);
+ // } catch (InterruptedException e) {
+ // e.printStackTrace();
+ // }
+ // }
+ // }
}
import javax.security.auth.login.LoginContext;
import org.apache.jackrabbit.core.security.SecurityConstants;
-import org.argeo.ArgeoException;
import org.argeo.cms.CmsException;
import org.argeo.cms.auth.AuthConstants;
import org.argeo.jcr.ArgeoJcrConstants;
return userProfile;
} catch (RepositoryException e) {
JcrUtils.discardQuietly(session);
- throw new ArgeoException("Cannot sync node security model for " + username, e);
+ throw new CmsException("Cannot sync node security model for " + username, e);
}
}
try {
dn = new LdapName(username);
} catch (InvalidNameException e) {
- throw new ArgeoException("Invalid name " + username, e);
+ throw new CmsException("Invalid name " + username, e);
}
String userId = dn.getRdn(dn.size() - 1).getValue().toString();
int atIndex = userId.indexOf('@');
return base + '/' + JcrUtils.firstCharsToPath(domain, 2) + '/' + domain + '/'
+ JcrUtils.firstCharsToPath(name, 2) + '/' + name;
} else if (atIndex == 0 || atIndex == (userId.length() - 1)) {
- throw new ArgeoException("Unsupported username " + userId);
+ throw new CmsException("Unsupported username " + userId);
} else {
return base + '/' + JcrUtils.firstCharsToPath(userId, 2) + '/' + userId;
}
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.spi.LoggingEvent;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.auth.CurrentUser;
import org.argeo.node.ArgeoLogListener;
import org.argeo.node.ArgeoLogger;
logDispatcherThread = new LogDispatcherThread();
logDispatcherThread.start();
} catch (Exception e) {
- throw new ArgeoException("Cannot initialize log4j");
+ throw new CmsException("Cannot initialize log4j");
}
}
public synchronized void register(ArgeoLogListener listener, Integer numberOfPreviousEvents) {
String username = CurrentUser.getUsername();
if (username == null)
- throw new ArgeoException("Only authenticated users can register a log listener");
+ throw new CmsException("Only authenticated users can register a log listener");
if (!userListeners.containsKey(username)) {
List<ArgeoLogListener> lst = Collections.synchronizedList(new ArrayList<ArgeoLogListener>());
if (username == null)// FIXME
return;
if (!userListeners.containsKey(username))
- throw new ArgeoException("No user listeners " + listener + " registered for user " + username);
+ throw new CmsException("No user listeners " + listener + " registered for user " + username);
if (!userListeners.get(username).contains(listener))
- throw new ArgeoException("No user listeners " + listener + " registered for user " + username);
+ throw new CmsException("No user listeners " + listener + " registered for user " + username);
userListeners.get(username).remove(listener);
if (userListeners.get(username).isEmpty())
userListeners.remove(username);
import javax.security.auth.x500.X500Principal;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
keyStore.setKeyEntry(x500Principal.getName(), pair.getPrivate(), keyPassword, new Certificate[] { cert });
return cert;
} catch (Exception e) {
- throw new ArgeoException("Cannot generate self-signed certificate", e);
+ throw new CmsException("Cannot generate self-signed certificate", e);
}
}
}
return store;
} catch (Exception e) {
- throw new ArgeoException("Cannot load keystore " + keyStoreFile, e);
+ throw new CmsException("Cannot load keystore " + keyStoreFile, e);
}
}
keyStore.store(fis, keyStorePassword);
}
} catch (Exception e) {
- throw new ArgeoException("Cannot save keystore " + keyStoreFile, e);
+ throw new CmsException("Cannot save keystore " + keyStoreFile, e);
}
}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jackrabbit.core.RepositoryContext;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.jcr.ArgeoJcrConstants;
import org.argeo.node.NodeConstants;
import org.argeo.util.LangUtils;
@Override
public void updated(String pid, Dictionary<String, ?> properties) throws ConfigurationException {
if (repositories.containsKey(pid))
- throw new ArgeoException("Already a repository registered for " + pid);
+ throw new CmsException("Already a repository registered for " + pid);
if (properties == null)
return;
}
bc.registerService(RepositoryContext.class, repositoryContext, props);
} catch (Exception e) {
- throw new ArgeoException("Cannot create Jackrabbit repository " + pid, e);
+ throw new CmsException("Cannot create Jackrabbit repository " + pid, e);
}
}
import javax.jcr.RepositoryException;
import javax.jcr.Value;
-import org.argeo.ArgeoException;
import org.argeo.cms.CmsException;
import org.argeo.cms.CmsTypes;
import org.argeo.cms.CmsUiProvider;
e.doit = false;
}
} catch (RepositoryException e1) {
- throw new ArgeoException(
+ throw new CmsException(
"Unexpected error in key management for "
+ currEdited + "with filter "
+ filterTxt.getText(), e1);
refreshFilters(node);
refreshBrowser(node);
} catch (RepositoryException re) {
- throw new ArgeoException("Unable to update browser for " + node, re);
+ throw new CmsException("Unable to update browser for " + node, re);
}
}
try {
return node.getPath();
} catch (RepositoryException e) {
- throw new ArgeoException("Unable to get path for node " + node, e);
+ throw new CmsException("Unable to get path for node " + node, e);
}
}
NodeIterator nit = context.getNodes(filter);
refreshFilteredList(nit);
} catch (RepositoryException e) {
- throw new ArgeoException("Unable to filter " + getNode()
+ throw new CmsException("Unable to filter " + getNode()
+ " children with filter " + filter, e);
}
}
}
} catch (RepositoryException ie) {
- throw new ArgeoException("Error while managing arrow "
+ throw new CmsException("Error while managing arrow "
+ "events in the browser for " + selected, ie);
}
}
try {
return curr.getName();
} catch (RepositoryException e) {
- throw new ArgeoException("Unable to get name for"
+ throw new CmsException("Unable to get name for"
+ curr);
}
}
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
-import org.argeo.ArgeoException;
import org.argeo.cms.CmsException;
import org.argeo.cms.CmsImageManager;
import org.argeo.cms.CmsView;
// }
}
} catch (LoginException e) {
- throw new ArgeoException("Cannot log in", e);
+ throw new CmsException("Cannot log in", e);
}
if (CurrentUser.getUsername() == null)
import java.util.Date;
import org.apache.commons.io.IOUtils;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.CmsStyles;
import org.eclipse.rap.rwt.RWT;
import org.eclipse.swt.SWT;
Label lbl = new Label(pane, SWT.NONE);
lbl.setText(exception.getLocalizedMessage()
- + (exception instanceof ArgeoException ? "" : "("
+ + (exception instanceof CmsException ? "" : "("
+ exception.getClass().getName() + ")") + "\n");
lbl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
lbl.addMouseListener(this);
import javax.security.auth.Subject;
import javax.security.auth.x500.X500Principal;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.CmsView;
import org.argeo.cms.auth.AuthConstants;
import org.argeo.cms.auth.CurrentUser;
else
return false;
} catch (InvalidNameException e) {
- throw new ArgeoException("User " + user + " has an unvalid dn: "
+ throw new CmsException("User " + user + " has an unvalid dn: "
+ userName, e);
}
}
|| last.getType().toLowerCase().equals(LdifName.cn.name()))
return (String) last.getValue();
else
- throw new ArgeoException("Cannot retrieve user uid, "
+ throw new CmsException("Cannot retrieve user uid, "
+ "non valid dn: " + dn);
}
}
return dname;
} catch (InvalidNameException e) {
- throw new ArgeoException("Unable to get domain name for " + dn, e);
+ throw new CmsException("Unable to get domain name for " + dn, e);
}
}
try {
return new LdapName(dn);
} catch (InvalidNameException e) {
- throw new ArgeoException("Cannot parse LDAP name " + dn, e);
+ throw new CmsException("Cannot parse LDAP name " + dn, e);
}
}
}
\ No newline at end of file
import javax.transaction.Status;
import javax.transaction.UserTransaction;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.auth.AuthConstants;
import org.argeo.osgi.useradmin.UserAdminConf;
import org.osgi.framework.ServiceReference;
}
return userTransaction;
} catch (Exception e) {
- throw new ArgeoException("Unable to begin transaction", e);
+ throw new CmsException("Unable to begin transaction", e);
}
}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
/** Provides base method for executing code with system authorization. */
public abstract class AbstractSystemExecution {
LoginContext lc = new LoginContext(loginModule, subject);
lc.login();
} catch (LoginException e) {
- throw new ArgeoException("Cannot login as system", e);
+ throw new CmsException("Cannot login as system", e);
} finally {
Thread.currentThread().setContextClassLoader(origClassLoader);
}
LoginContext lc = new LoginContext(loginModule, subject);
lc.logout();
} catch (LoginException e) {
- throw new ArgeoException("Cannot logout as system", e);
+ throw new CmsException("Cannot logout as system", e);
} finally {
Thread.currentThread().setContextClassLoader(origClassLoader);
}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.osgi.service.useradmin.Role;
import org.osgi.service.useradmin.UserAdmin;
} catch (Exception e1) {
log.error("Cannot rollback", e1);
}
- throw new ArgeoException("Cannot add roles", e);
+ throw new CmsException("Cannot add roles", e);
}
}
try {
return new LdapName("cn=" + name + ",ou=roles,ou=node");
} catch (InvalidNameException e) {
- throw new ArgeoException("Badly formatted role name " + name, e);
+ throw new CmsException("Badly formatted role name " + name, e);
}
}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
ApplicationContext applicationContext = ApplicationContextTracker
.getApplicationContext(bundleSymbolicName);
if (applicationContext == null)
- throw new ArgeoException("No application context found for "
+ throw new EclipseUiException("No application context found for "
+ bundleSymbolicName);
// retrieve the command via its id
*/\r
package org.argeo.eclipse.spring;\r
\r
-import org.argeo.ArgeoException;\r
+import org.argeo.eclipse.ui.EclipseUiException;\r
import org.eclipse.core.runtime.CoreException;\r
import org.eclipse.core.runtime.IConfigurationElement;\r
import org.eclipse.core.runtime.IExecutableExtension;\r
\r
public Object create() throws CoreException {\r
if (bean == null)\r
- throw new ArgeoException("No underlying bean for extension");\r
+ throw new EclipseUiException("No underlying bean for extension");\r
return bean;\r
}\r
\r
ApplicationContext applicationContext = ApplicationContextTracker\r
.getApplicationContext(bundleSymbolicName);\r
if (applicationContext == null)\r
- throw new ArgeoException(\r
+ throw new EclipseUiException(\r
"Cannot find application context for bundle "\r
+ bundleSymbolicName);\r
\r
String beanName = getBeanName(data, config);\r
if (beanName == null)\r
- throw new ArgeoException("Cannot find bean name for extension "\r
+ throw new EclipseUiException("Cannot find bean name for extension "\r
+ config);\r
\r
if (!applicationContext.containsBean(beanName)) {\r
}\r
\r
if (!applicationContext.containsBean(beanName))\r
- throw new ArgeoException("No bean with name '" + beanName + "'");\r
+ throw new EclipseUiException("No bean with name '" + beanName + "'");\r
\r
this.bean = applicationContext.getBean(beanName);\r
if (this.bean instanceof IExecutableExtension) {\r
import java.util.HashMap;
import java.util.Map;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.Parameterization;
import org.eclipse.core.commands.ParameterizedCommand;
// execute the command
handlerService.executeCommand(pc, null);
} catch (Exception e) {
- throw new ArgeoException("Unexpected error while"
+ throw new EclipseUiException("Unexpected error while"
+ " calling the command " + commandID, e);
}
}
import javax.jcr.Node;
import javax.jcr.RepositoryException;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.TreeParent;
import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
import org.argeo.eclipse.ui.workbench.WorkbenchUiPlugin;
dialog.open();
return null;
} catch (RepositoryException re) {
- throw new ArgeoException("Unable to retrieve "
+ throw new EclipseUiException("Unable to retrieve "
+ "path or JCR session to add privilege on "
+ jcrParentNode, re);
}
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
import org.argeo.eclipse.ui.workbench.CommandUtils;
import org.argeo.eclipse.ui.workbench.WorkbenchConstants;
Node remote = home.hasNode(ARGEO_REMOTE) ? home
.getNode(ARGEO_REMOTE) : home.addNode(ARGEO_REMOTE);
if (remote.hasNode(name.getText()))
- throw new ArgeoException(
+ throw new EclipseUiException(
"There is already a remote repository named "
+ name.getText());
Node remoteRepository = remote.addNode(name.getText(),
import javax.jcr.Node;
import javax.jcr.RepositoryException;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.TreeParent;
import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
import org.argeo.eclipse.ui.workbench.internal.jcr.model.SingleJcrNodeElem;
else
return A.getNode().getDepth() <= B.getNode().getDepth() ? A : B;
} catch (RepositoryException re) {
- throw new ArgeoException("Cannot find ancestor", re);
+ throw new EclipseUiException("Cannot find ancestor", re);
}
}
}
import javax.jcr.RepositoryException;
import javax.jcr.Session;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.workbench.CommandUtils;
import org.argeo.eclipse.ui.workbench.WorkbenchUiPlugin;
import org.argeo.eclipse.ui.workbench.internal.jcr.model.SingleJcrNodeElem;
+ JcrUtils.replaceInvalidChars(node.getName())
+ "-" + dateVal + ".xml");
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unable to perform SystemExport on " + node, e);
} catch (IOException e) {
- throw new ArgeoException("Unable to SystemExport " + node,
+ throw new EclipseUiException("Unable to SystemExport " + node,
e);
}
}
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.EclipseUiUtils;
import org.argeo.eclipse.ui.workbench.WorkbenchUiPlugin;
import org.argeo.eclipse.ui.workbench.internal.jcr.model.SingleJcrNodeElem;
fos.close();
}
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unable to perform SystemExport on " + node, e);
} catch (IOException e) {
- throw new ArgeoException("Unable to SystemExport "
+ throw new EclipseUiException("Unable to SystemExport "
+ node, e);
}
}
page = new BasicPage("Main page");
addPage(page);
} catch (Exception e) {
- throw new ArgeoException("Cannot add page to wizard", e);
+ throw new EclipseUiException("Cannot add page to wizard", e);
}
}
import javax.jcr.Node;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.workbench.WorkbenchUiPlugin;
import org.argeo.eclipse.ui.workbench.internal.jcr.parts.JcrQueryEditorInput;
import org.argeo.eclipse.ui.workbench.internal.jcr.parts.NodeEditorInput;
activePage.openEditor(editorInput, editorId);
}
} catch (PartInitException e) {
- throw new ArgeoException("Cannot open editor of ID " + editorId, e);
+ throw new EclipseUiException("Cannot open editor of ID " + editorId, e);
}
return null;
}
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.Privilege;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.EclipseUiUtils;
import org.argeo.eclipse.ui.TreeParent;
import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
dialog.open();
return null;
} catch (RepositoryException re) {
- throw new ArgeoException("Unable to retrieve "
+ throw new EclipseUiException("Unable to retrieve "
+ "path or JCR session to add privilege on " + jcrNode,
re);
}
IMessageProvider.INFORMATION);
}
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unable to list privileges on " + path, e);
}
body.layout(true, true);
session.save();
refreshContent();
} catch (RepositoryException re) {
- throw new ArgeoException("Unable to "
+ throw new EclipseUiException("Unable to "
+ "remove privilege for "
+ currPrincipalName + " on " + path, re);
}
import javax.jcr.RepositoryException;
import javax.jcr.Session;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.dialogs.SingleValue;
import org.argeo.eclipse.ui.workbench.WorkbenchUiPlugin;
import org.argeo.eclipse.ui.workbench.internal.jcr.model.SingleJcrNodeElem;
if (iwp.getActivePart() instanceof JcrBrowserView)
((JcrBrowserView) iwp.getActivePart()).refresh(sjn);
} catch (RepositoryException e) {
- throw new ArgeoException("Unable to rename " + node
+ throw new EclipseUiException("Unable to rename " + node
+ " to " + newName, e);
}
}
import javax.jcr.version.VersionIterator;
import javax.jcr.version.VersionManager;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
}
return result.toArray();
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected error while getting version elements", re);
}
}
return tmp.toArray();
}
} catch (RepositoryException re) {
- throw new ArgeoException("Unexpected error while getting child "
+ throw new EclipseUiException("Unexpected error while getting child "
+ "node for version element", re);
}
return null;
else
return false;
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot check children of " + element, e);
+ throw new EclipseUiException("Cannot check children of " + element, e);
}
}
import javax.jcr.RepositoryException;
import javax.jcr.nodetype.NodeType;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.workbench.WorkbenchUiPlugin;
import org.argeo.eclipse.ui.workbench.internal.jcr.model.RepositoryElem;
import org.argeo.eclipse.ui.workbench.internal.jcr.model.SingleJcrNodeElem;
.getActiveWorkbenchWindow().getActivePage()
.openEditor(gnei, DefaultNodeEditor.ID);
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Repository error while getting node info", re);
} catch (PartInitException pie) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexepected exception while opening node editor", pie);
}
}
import javax.jcr.Node;
import javax.jcr.RepositoryException;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.TreeParent;
import org.argeo.eclipse.ui.workbench.internal.jcr.model.RepositoriesElem;
import org.argeo.eclipse.ui.workbench.internal.jcr.model.RepositoryElem;
element.getChildren();
}
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected error while synchronising the UI with the JCR repository",
re);
}
import javax.jcr.nodetype.NodeType;
import org.argeo.eclipse.ui.TreeParent;
+import org.argeo.eclipse.ui.workbench.internal.jcr.model.RepositoriesElem;
+import org.argeo.eclipse.ui.workbench.internal.jcr.model.SingleJcrNodeElem;
import org.argeo.jcr.ArgeoJcrConstants;
import org.argeo.jcr.RepositoryRegister;
import org.argeo.jcr.UserJcrUtils;
-import org.argeo.eclipse.ui.workbench.internal.jcr.model.RepositoriesElem;
-import org.argeo.eclipse.ui.workbench.internal.jcr.model.SingleJcrNodeElem;
import org.argeo.util.security.Keyring;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.workbench.internal.jcr.model.RemoteRepositoryElem;
import org.argeo.eclipse.ui.workbench.internal.jcr.model.RepositoriesElem;
import org.argeo.eclipse.ui.workbench.internal.jcr.model.RepositoryElem;
} else
return super.getText(element);
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected JCR error while getting node name.");
}
}
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.jcr.utils.JcrItemsComparator;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;
}
return new Object[] {};
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get element for " + inputElement,
+ throw new EclipseUiException("Cannot get element for " + inputElement,
e);
}
}
import javax.jcr.RepositoryException;
import javax.jcr.Value;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.workbench.WorkbenchConstants;
import org.argeo.jcr.JcrUtils;
import org.eclipse.jface.viewers.ColumnLabelProvider;
}
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexepected error while getting property values", re);
}
return null;
strValue = value.getString();
return strValue;
} catch (RepositoryException e) {
- throw new ArgeoException("unexpected error while formatting value",
+ throw new EclipseUiException("unexpected error while formatting value",
e);
}
}
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.jcr.utils.JcrItemsComparator;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
return result.toArray();
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected error while getting child nodes for children editor page ",
re);
}
try {
return ((Node) element).hasNodes();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot check children of " + element, e);
+ throw new EclipseUiException("Cannot check children of " + element, e);
}
}
Arrays.sort(arr, itemComparator);
return arr;
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot list children of " + parentNode, e);
+ throw new EclipseUiException("Cannot list children of " + parentNode, e);
}
}
}
import javax.jcr.RepositoryException;
import javax.jcr.version.Version;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.eclipse.jface.viewers.ColumnLabelProvider;
/**
return ((Node) element).getName();
}
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected error while getting element name", re);
}
return super.getText(element);
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.TreeParent;
import org.argeo.jcr.ArgeoJcrUtils;
import org.argeo.jcr.ArgeoNames;
remoteNode.remove();
remoteNode.getSession().save();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot remove " + remoteNodePath, e);
+ throw new EclipseUiException("Cannot remove " + remoteNodePath, e);
}
}
import javax.jcr.RepositoryFactory;
import javax.jcr.Session;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.TreeParent;
import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
import org.argeo.jcr.ArgeoNames;
try {
addRemoteRepositories(keyring);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot browse remote repositories", e);
+ throw new EclipseUiException("Cannot browse remote repositories", e);
}
}
return super.getChildren();
import javax.jcr.RepositoryException;
import javax.jcr.Session;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.TreeParent;
/**
addChild(new WorkspaceElem(this, wkpName));
}
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot connect to repository " + alias, e);
+ throw new EclipseUiException("Cannot connect to repository " + alias, e);
}
}
try {
return defaultSession.getWorkspace().getAccessibleWorkspaceNames();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot retrieve workspace names", e);
+ throw new EclipseUiException("Cannot retrieve workspace names", e);
}
}
try {
defaultSession.getWorkspace().createWorkspace(workspaceName);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot create workspace", e);
+ throw new EclipseUiException("Cannot create workspace", e);
}
}
import javax.jcr.RepositoryException;
import javax.jcr.Workspace;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.TreeParent;
/**
}
return super.getChildren();
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexcpected error while initializing children SingleJcrNode",
re);
}
else
return false;
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected error while checking children node existence",
re);
}
import javax.jcr.RepositoryException;
import javax.jcr.Session;
// import javax.jcr.Workspace;
+import javax.jcr.Workspace;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.TreeParent;
import org.argeo.jcr.JcrUtils;
else
return null;
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get root node of workspace "
+ throw new EclipseUiException("Cannot get root node of workspace "
+ getName(), e);
}
}
try {
session = ((RepositoryElem) getParent()).repositoryLogin(getName());
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot connect to repository "
+ throw new EclipseUiException("Cannot connect to repository "
+ getName(), e);
}
}
else
return false;
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected error while checking children node existence",
re);
}
}
return super.getChildren();
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Cannot initialize WorkspaceNode UI object."
+ getName(), e);
}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.GenericTableComparator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
}
viewer.setInput(rows);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot read query result", e);
+ throw new EclipseUiException("Cannot read query result", e);
}
} catch (RepositoryException e) {
try {
return row.getValue(columnName).getString();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot display row " + row, e);
+ throw new EclipseUiException("Cannot display row " + row, e);
}
}
// }
return rows.toArray();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot read query result", e);
+ throw new EclipseUiException("Cannot read query result", e);
}
}
import javax.jcr.Session;
import javax.jcr.security.Privilege;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.EclipseUiUtils;
import org.argeo.eclipse.ui.workbench.internal.users.UsersUtils;
import org.argeo.eclipse.ui.workbench.users.PickUpUserDialog;
page = new DefinePrivilegePage(userAdmin, targetPath);
addPage(page);
} catch (Exception e) {
- throw new ArgeoException("Cannot add page to wizard ", e);
+ throw new EclipseUiException("Cannot add page to wizard ", e);
}
}
JcrUtils.addPrivilege(currentSession, targetPath,
chosenUser.getName(), jcrPrivilege);
} catch (RepositoryException re) {
- throw new ArgeoException("Cannot set " + jcrPrivilege + " for "
+ throw new EclipseUiException("Cannot set " + jcrPrivilege + " for "
+ chosenUser.getName() + " on " + targetPath, re);
}
return true;
import javax.jcr.Node;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.EclipseUiUtils;
import org.argeo.eclipse.ui.workbench.WorkbenchUiPlugin;
import org.argeo.eclipse.ui.workbench.internal.jcr.NodeLabelProvider;
nodesViewer.setInput(currentNode);
}
} catch (Exception e) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected error while creating child node page", e);
}
}
.getActiveWorkbenchWindow().getActivePage()
.openEditor(gnei, DefaultNodeEditor.ID);
} catch (PartInitException pie) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexepected exception while opening node editor",
pie);
}
import javax.jcr.Node;
import javax.jcr.RepositoryException;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPersistableElement;
uid = currentNode.getIdentifier();
path = currentNode.getPath();
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"unexpected error while getting node key values at creation time",
re);
}
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.workbench.WorkbenchConstants;
import org.argeo.jcr.JcrUtils;
import org.eclipse.swt.SWT;
currentNode.getSession().save();
}
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected error while saving properties", re);
}
}
getManagedForm().addPart(part);
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Error during creation of network details section", re);
}
} else
addModifyableValueWidget(parent, part, prop);
} catch (RepositoryException re) {
- throw new ArgeoException("Cannot get property " + prop, re);
+ throw new EclipseUiException("Cannot get property " + prop, re);
}
}
return strValue;
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected error while formatting read only property value",
re);
}
}
return null;
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected error while formatting read only property value",
re);
}
import javax.jcr.RepositoryException;
import javax.jcr.Value;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.workbench.WorkbenchConstants;
import org.argeo.eclipse.ui.workbench.WorkbenchUiPlugin;
import org.argeo.eclipse.ui.workbench.internal.jcr.PropertyLabelProvider;
// super.commit(onSave);
// }
// } catch (RepositoryException re) {
- // throw new ArgeoException(
+ // throw new EclipseUiException(
// "Unexpected error while saving properties", re);
// }
// }
//
// getManagedForm().addPart(part);
// } catch (RepositoryException re) {
- // throw new ArgeoException(
+ // throw new EclipseUiException(
// "Error during creation of network details section", re);
// }
//
// } else
// addModifyableValueWidget(parent, part, prop);
// } catch (RepositoryException re) {
- // throw new ArgeoException("Cannot get property " + prop, re);
+ // throw new EclipseUiException("Cannot get property " + prop, re);
// }
// }
//
//
// return strValue;
// } catch (RepositoryException re) {
- // throw new ArgeoException(
+ // throw new EclipseUiException(
// "Unexpected error while formatting read only property value",
// re);
// }
// }
// return null;
// } catch (RepositoryException re) {
- // throw new ArgeoException(
+ // throw new EclipseUiException(
// "Unexpected error while formatting read only property value",
// re);
// }
props = propList.toArray();
}
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected exception while listing node properties", e);
}
return props;
return values;
}
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected error getting multiple values property.",
e);
}
return true;
}
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected exception while checking if property is multiple",
e);
}
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
import org.argeo.eclipse.ui.specific.UploadFileWizardPage;
import org.eclipse.core.runtime.IProgressMonitor;
if (e instanceof RuntimeException)
throw (RuntimeException) e;
else
- throw new ArgeoException("Cannot import "
+ throw new EclipseUiException("Cannot import "
+ objectPath, e);
}
}
}
}
} catch (Exception e) {
- throw new ArgeoException("Cannot import " + dir + " to " + folder,
+ throw new EclipseUiException("Cannot import " + dir + " to " + folder,
e);
}
}
import javax.jcr.RepositoryException;
import javax.jcr.Value;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.workbench.WorkbenchUiPlugin;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.IStructuredContentProvider;
return node.getProperty("rep:principalName")
.getString();
} catch (RepositoryException e) {
- throw new ArgeoException("Unable to retrieve "
+ throw new EclipseUiException("Unable to retrieve "
+ "principal name on " + node, e);
}
return "";
}
} catch (RepositoryException e) {
- throw new ArgeoException("Unable to retrieve "
+ throw new EclipseUiException("Unable to retrieve "
+ "privileges on " + node, e);
}
return "";
try {
return node.getParent().getParent().getPath();
} catch (RepositoryException e) {
- throw new ArgeoException("Unable get path for " + node, e);
+ throw new EclipseUiException("Unable get path for " + node, e);
}
}
return privs.toArray();
} catch (Exception e) {
- throw new ArgeoException("Cannot retrieve authorization for "
+ throw new EclipseUiException("Cannot retrieve authorization for "
+ context, e);
}
}
String cname = context.getSession().getClass().getName();
return cname.startsWith("org.apache.jackrabbit");
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot check JCR implementation used on "
+ throw new EclipseUiException("Cannot check JCR implementation used on "
+ context, e);
}
}
import javax.jcr.version.VersionIterator;
import javax.jcr.version.VersionManager;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.workbench.WorkbenchConstants;
import org.argeo.eclipse.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.jcr.PropertyDiff;
-import org.argeo.jcr.VersionDiff;
import org.argeo.eclipse.ui.workbench.internal.jcr.FullVersioningTreeContentProvider;
import org.argeo.eclipse.ui.workbench.internal.jcr.GenericNodeDoubleClickListener;
import org.argeo.eclipse.ui.workbench.internal.jcr.VersionLabelProvider;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.jcr.PropertyDiff;
+import org.argeo.jcr.VersionDiff;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
createTreeSection(form.getBody());
}
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected error while checking if node is versionable", e);
}
}
}
styledText.setText(main.toString());
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot generate history for node", e);
+ throw new EclipseUiException("Cannot generate history for node", e);
}
}
}
return res;
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot generate history for node ");
+ throw new EclipseUiException("Cannot generate history for node ");
}
}
import javax.security.auth.Subject;
import javax.security.auth.x500.X500Principal;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.osgi.useradmin.LdifName;
import org.osgi.service.useradmin.Role;
import org.osgi.service.useradmin.User;
else
return false;
} catch (InvalidNameException e) {
- throw new ArgeoException("User " + user + " has an unvalid dn: "
+ throw new EclipseUiException("User " + user + " has an unvalid dn: "
+ userName, e);
}
}
try {
dn = new LdapName(name);
} catch (InvalidNameException e) {
- throw new ArgeoException("Invalid user dn " + name, e);
+ throw new EclipseUiException("Invalid user dn " + name, e);
}
return dn;
}
}
return dname;
} catch (InvalidNameException e) {
- throw new ArgeoException("Unable to get domain name for " + dn, e);
+ throw new EclipseUiException("Unable to get domain name for " + dn, e);
}
}
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.Privilege;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.workbench.WorkbenchUiPlugin;
import org.argeo.eclipse.ui.workbench.internal.jcr.parts.ChildNodesPage;
import org.argeo.eclipse.ui.workbench.internal.jcr.parts.GenericNodeEditorInput;
}
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get node info for " + currentNode,
+ throw new EclipseUiException("Cannot get node info for " + currentNode,
e);
} catch (PartInitException e) {
- throw new ArgeoException("Cannot add page " + "on node editor for "
+ throw new EclipseUiException("Cannot add page " + "on node editor for "
+ currentNode, e);
}
}
commitPages(true);
firePropertyChange(PROP_DIRTY);
} catch (Exception e) {
- throw new ArgeoException("Error while saving node", e);
+ throw new EclipseUiException("Error while saving node", e);
}
}
import javax.jcr.observation.EventListener;
import javax.jcr.observation.ObservationManager;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.TreeParent;
import org.argeo.eclipse.ui.jcr.AsyncUiEventListener;
import org.argeo.eclipse.ui.jcr.utils.NodeViewerComparer;
try {
this.userSession = this.nodeRepository.login();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot open user session", e);
+ throw new EclipseUiException("Cannot open user session", e);
}
nodeContentProvider = new NodeContentProvider(userSession, keyring,
Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED, "/",
true, null, null, false);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot register listeners", e);
+ throw new EclipseUiException("Cannot register listeners", e);
}
tmpNodeViewer
try {
return ((Property) element).getName();
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected exception in label provider", e);
}
}
} else
return property.getValue().getString();
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected exception in label provider", e);
}
}
return PropertyType.nameFromValue(((Property) element)
.getType());
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unexpected exception in label provider", e);
}
}
import javax.jcr.version.VersionManager;
import org.apache.commons.io.IOUtils;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.jcr.ArgeoNames;
import org.argeo.jcr.ArgeoTypes;
import org.argeo.jcr.JcrUtils;
session.save();
Node userHome = UserJcrUtils.getUserHome(session);
if (userHome == null)
- throw new ArgeoException("No user home for "
+ throw new EclipseUiException("No user home for "
+ session.getUserID());
Node preferences;
if (!userHome.hasNode(ARGEO_PREFERENCES)) {
} catch (RepositoryException e) {
e.printStackTrace();
JcrUtils.discardQuietly(session);
- throw new ArgeoException("Cannot retrieve preferences", e);
+ throw new EclipseUiException("Cannot retrieve preferences", e);
}
}
load(in);
} catch (Exception e) {
e.printStackTrace();
- throw new ArgeoException("Cannot load preferences", e);
+ throw new EclipseUiException("Cannot load preferences", e);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
vm.checkin(pluginPreferences.getPath());
} catch (Exception e) {
JcrUtils.discardUnderlyingSessionQuietly(pluginPreferences);
- throw new ArgeoException("Cannot save preferences", e);
+ throw new EclipseUiException("Cannot save preferences", e);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
try {
load();
} catch (IOException e) {
- throw new ArgeoException("Cannot initialize preference store", e);
+ throw new EclipseUiException("Cannot initialize preference store", e);
}
}
import java.util.ArrayList;
import java.util.List;
-import org.argeo.ArgeoException;
import org.argeo.eclipse.ui.ColumnDefinition;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.EclipseUiUtils;
import org.argeo.eclipse.ui.parts.LdifUsersTable;
import org.argeo.eclipse.ui.workbench.internal.users.UsersUtils;
}
roles = userAdmin.getRoles(builder.toString());
} catch (InvalidSyntaxException e) {
- throw new ArgeoException("Unable to get roles with filter: "
+ throw new EclipseUiException("Unable to get roles with filter: "
+ filter, e);
}
List<User> users = new ArrayList<User>();
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.workbench.internal.users.UsersImages;
import org.argeo.eclipse.ui.workbench.internal.users.UsersUtils;
-import org.argeo.osgi.useradmin.LdifName;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.swt.SWT;
return bold;
}
} catch (InvalidNameException e) {
- throw new ArgeoException("cannot parse dn for " + element, e);
+ throw new EclipseUiException("cannot parse dn for " + element, e);
}
// Disabled as Italic
org.eclipse.swt,\
org.eclipse.jface.window,\
org.eclipse.core.commands.common,\
+ org.argeo,\
*
*/
package org.argeo.eclipse.ui;
-import org.argeo.ArgeoMonitor;
import org.eclipse.core.runtime.IProgressMonitor;
/**
- * Wraps an Eclipse {@link IProgressMonitor} so that it can be passed to
- * framework agnostic Argeo routines.
+ * @deprecated use {@link EclipseJcrMonitor} instead
*/
-public class EclipseArgeoMonitor implements ArgeoMonitor {
- private final IProgressMonitor progressMonitor;
-
+@Deprecated
+public class EclipseArgeoMonitor extends EclipseJcrMonitor {
public EclipseArgeoMonitor(IProgressMonitor progressMonitor) {
- this.progressMonitor = progressMonitor;
- }
-
- public void beginTask(String name, int totalWork) {
- progressMonitor.beginTask(name, totalWork);
- }
-
- public void done() {
- progressMonitor.done();
- }
-
- public boolean isCanceled() {
- return progressMonitor.isCanceled();
- }
-
- public void setCanceled(boolean value) {
- progressMonitor.setCanceled(value);
- }
-
- public void setTaskName(String name) {
- progressMonitor.setTaskName(name);
- }
-
- public void subTask(String name) {
- progressMonitor.subTask(name);
- }
-
- public void worked(int work) {
- progressMonitor.worked(work);
+ super(progressMonitor);
}
}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.eclipse.ui;
+
+import org.argeo.jcr.JcrMonitor;
+import org.eclipse.core.runtime.IProgressMonitor;
+
+/**
+ * Wraps an Eclipse {@link IProgressMonitor} so that it can be passed to
+ * framework agnostic Argeo routines.
+ */
+public class EclipseJcrMonitor implements JcrMonitor {
+ private final IProgressMonitor progressMonitor;
+
+ public EclipseJcrMonitor(IProgressMonitor progressMonitor) {
+ this.progressMonitor = progressMonitor;
+ }
+
+ public void beginTask(String name, int totalWork) {
+ progressMonitor.beginTask(name, totalWork);
+ }
+
+ public void done() {
+ progressMonitor.done();
+ }
+
+ public boolean isCanceled() {
+ return progressMonitor.isCanceled();
+ }
+
+ public void setCanceled(boolean value) {
+ progressMonitor.setCanceled(value);
+ }
+
+ public void setTaskName(String name) {
+ progressMonitor.setTaskName(name);
+ }
+
+ public void subTask(String name) {
+ progressMonitor.subTask(name);
+ }
+
+ public void worked(int work) {
+ progressMonitor.worked(work);
+ }
+}
--- /dev/null
+package org.argeo.eclipse.ui;
+
+/** CMS specific exceptions. */
+public class EclipseUiException extends RuntimeException {
+ private static final long serialVersionUID = -5341764743356771313L;
+
+ public EclipseUiException(String message) {
+ super(message);
+ }
+
+ public EclipseUiException(String message, Throwable e) {
+ super(message, e);
+ }
+
+}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
public void open() {
if (shell != null)
- throw new ArgeoException("There is already a shell");
+ throw new EclipseUiException("There is already a shell");
shell = new Shell(getDisplay(), SWT.NO_TRIM | SWT.BORDER | SWT.ON_TOP);
shell.setLayout(new GridLayout());
// shell.setText("Error");
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
import org.argeo.eclipse.ui.AbstractTreeContentProvider;
+import org.argeo.eclipse.ui.EclipseUiException;
/** Canonical implementation of tree content provider manipulating JCR nodes. */
public abstract class AbstractNodeContentProvider extends
Node node = (Node) element;
children = getChildren(node);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get children of " + element, e);
+ throw new EclipseUiException("Cannot get children of " + element, e);
}
} else if (element instanceof WrappedNode) {
WrappedNode wrappedNode = (WrappedNode) element;
try {
children = getChildren(wrappedNode.getNode());
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get children of "
+ throw new EclipseUiException("Cannot get children of "
+ wrappedNode, e);
}
} else if (element instanceof NodesWrapper) {
}
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot check whether " + element
+ throw new EclipseUiException("Cannot check whether " + element
+ " has children", e);
}
return super.hasChildren(element);
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.eclipse.swt.widgets.Display;
/** {@link EventListener} which simplifies running actions within the UI thread. */
if (!willProcessInUiThread(events))
return;
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot test skip events " + events, e);
+ throw new EclipseUiException("Cannot test skip events " + events, e);
}
// Job job = new Job("JCR Events") {
try {
onEventInUiThread(events);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot process events "
+ throw new EclipseUiException("Cannot process events "
+ events, e);
}
}
import javax.jcr.RepositoryException;
import javax.jcr.nodetype.NodeType;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.swt.graphics.Image;
}
return super.getText(element);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get text for of " + element, e);
+ throw new EclipseUiException("Cannot get text for of " + element, e);
}
}
return getImage(((NodesWrapper) element).getNode());
}
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot retrieve image for " + element, e);
+ throw new EclipseUiException("Cannot retrieve image for " + element, e);
}
return super.getImage(element);
}
return getToolTipText(((NodesWrapper) element).getNode());
}
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get tooltip for " + element, e);
+ throw new EclipseUiException("Cannot get tooltip for " + element, e);
}
return super.getToolTipText(element);
}
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.jcr.lists.NodeViewerComparator;
import org.argeo.eclipse.ui.jcr.lists.RowViewerComparator;
import org.eclipse.jface.viewers.TableViewer;
}
default:
- throw new ArgeoException("Unimplemented property save");
+ throw new EclipseUiException("Unimplemented property save");
}
} catch (RepositoryException re) {
- throw new ArgeoException("Unexpected error while setting property",
+ throw new EclipseUiException("Unexpected error while setting property",
re);
}
}
import javax.jcr.Node;\r
import javax.jcr.RepositoryException;\r
\r
-import org.argeo.ArgeoException;\r
+import org.argeo.eclipse.ui.EclipseUiException;\r
import org.eclipse.jface.viewers.IElementComparer;\r
\r
/** Element comparer for JCR node, to be used in JFace viewers. */\r
return a.equals(b);\r
}\r
} catch (RepositoryException e) {\r
- throw new ArgeoException("Cannot compare nodes", e);\r
+ throw new EclipseUiException("Cannot compare nodes", e);\r
}\r
}\r
\r
return ((Node) element).getIdentifier().hashCode();\r
return element.hashCode();\r
} catch (RepositoryException e) {\r
- throw new ArgeoException("Cannot get hash code", e);\r
+ throw new EclipseUiException("Cannot get hash code", e);\r
}\r
}\r
\r
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
/**
* Element of tree which is based on a node, but whose children are not
try {
return getWrappedNodes().toArray();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get wrapped children", e);
+ throw new EclipseUiException("Cannot get wrapped children", e);
}
}
import javax.jcr.RepositoryException;
import javax.jcr.Session;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.jcr.JcrUtils;
/** Simple JCR node content provider taking a list of String as base path. */
baseNodes.add(getSession().getNode(basePath));
return baseNodes.toArray();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get base nodes for " + basePaths,
+ throw new EclipseUiException("Cannot get base nodes for " + basePaths,
e);
}
}
import javax.jcr.Value;
import javax.jcr.ValueFormatException;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
rc = d1.compareTo(d2);
break;
default:
- throw new ArgeoException(
+ throw new EclipseUiException(
"Unimplemented comparaison for PropertyType "
+ propertyType);
}
}
} catch (RepositoryException re) {
- throw new ArgeoException("Unexpected error "
+ throw new EclipseUiException("Unexpected error "
+ "while comparing nodes", re);
}
return rc;
import javax.jcr.RepositoryException;
import javax.jcr.query.Row;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.eclipse.jface.viewers.Viewer;
/**
Node n2 = ((Row) e2).getNode(selectorName);
return super.compare(viewer, n1, n2);
} catch (RepositoryException re) {
- throw new ArgeoException("Unexpected error "
+ throw new EclipseUiException("Unexpected error "
+ "while comparing nodes", re);
}
}
import javax.jcr.RepositoryException;
import javax.jcr.Value;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.eclipse.jface.viewers.ColumnLabelProvider;
/** Base implementation of a label provider for controls that display JCR Nodes */
} else
return "";
} catch (RepositoryException re) {
- throw new ArgeoException("Unable to get text from row", re);
+ throw new EclipseUiException("Unable to get text from row", re);
}
}
case PropertyType.NAME:
return value.getString();
default:
- throw new ArgeoException("Unimplemented label provider "
+ throw new EclipseUiException("Unimplemented label provider "
+ "for property type " + value.getType()
+ " while getting property " + propertyName + " - value: "
+ value.getString());
import javax.jcr.RepositoryException;
import javax.jcr.query.Row;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
/**
* Base implementation of a label provider for widgets that display JCR Rows.
Node currNode = currRow.getNode(selectorName);
return super.getText(currNode);
} catch (RepositoryException re) {
- throw new ArgeoException("Unable to get Node " + selectorName
+ throw new EclipseUiException("Unable to get Node " + selectorName
+ " from row " + element, re);
}
}
import javax.jcr.nodetype.NodeType;
import org.apache.commons.io.IOUtils;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.FileProvider;
/**
ba = IOUtils.toByteArray(fis);
} catch (Exception e) {
- throw new ArgeoException("Stream error while opening file", e);
+ throw new EclipseUiException("Stream error while opening file", e);
} finally {
IOUtils.closeQuietly(fis);
}
.getBinary().getStream();
return fis;
} catch (RepositoryException re) {
- throw new ArgeoException("Cannot get stream from file node for Id "
+ throw new EclipseUiException("Cannot get stream from file node for Id "
+ fileId, re);
}
}
// Sanity checks
if (result == null)
- throw new ArgeoException("File node not found for ID" + fileId);
+ throw new EclipseUiException("File node not found for ID" + fileId);
Node child = null;
}
if (!isValid)
- throw new ArgeoException(
+ throw new EclipseUiException(
"ERROR: In the current implemented model, '"
+ NodeType.NT_FILE
+ "' file node must have a child node named jcr:content "
return child;
} catch (RepositoryException re) {
- throw new ArgeoException("Erreur while getting file node of ID "
+ throw new EclipseUiException("Erreur while getting file node of ID "
+ fileId, re);
}
}
import javax.jcr.Item;
import javax.jcr.RepositoryException;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
/** Compares two JCR items (node or properties) based on their names. */
public class JcrItemsComparator implements Comparator<Item> {
// TODO: put folder before files
return o1.getName().compareTo(o2.getName());
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot compare " + o1 + " and " + o2, e);
+ throw new EclipseUiException("Cannot compare " + o1 + " and " + o2, e);
}
}
import javax.jcr.Node;
import javax.jcr.RepositoryException;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.eclipse.jface.viewers.IElementComparer;
/** Compare JCR nodes based on their JCR identifiers, for use in JFace viewers. */
String idB = ((Node) elementB).getIdentifier();
result = idA == null ? idB == null : idA.equals(idB);
} catch (RepositoryException re) {
- throw new ArgeoException("cannot compare nodes", re);
+ throw new EclipseUiException("cannot compare nodes", re);
}
return result;
import javax.jcr.nodetype.NodeType;
import org.apache.commons.io.IOUtils;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.FileProvider;
/**
ba = IOUtils.toByteArray(fis);
} catch (Exception e) {
- throw new ArgeoException("Stream error while opening file", e);
+ throw new EclipseUiException("Stream error while opening file", e);
} finally {
IOUtils.closeQuietly(fis);
}
.getBinary().getStream();
return fis;
} catch (RepositoryException re) {
- throw new ArgeoException("Cannot get stream from file node for Id "
+ throw new EclipseUiException("Cannot get stream from file node for Id "
+ fileId, re);
}
}
// Sanity checks
if (result == null)
- throw new ArgeoException("File node not found for ID" + fileId);
+ throw new EclipseUiException("File node not found for ID" + fileId);
// Ensure that the node have the correct type.
if (!result.isNodeType(NodeType.NT_FILE))
- throw new ArgeoException(
+ throw new EclipseUiException(
"Cannot open file children Node that are not of "
+ NodeType.NT_RESOURCE + " type.");
Node child = result.getNodes().nextNode();
if (child == null || !child.isNodeType(NodeType.NT_RESOURCE))
- throw new ArgeoException(
+ throw new EclipseUiException(
"ERROR: IN the current implemented model, "
+ NodeType.NT_FILE
+ " file node must have one and only one child of the nt:ressource, where actual data is stored");
return child;
} catch (RepositoryException re) {
- throw new ArgeoException("Erreur while getting file node of ID "
+ throw new EclipseUiException("Erreur while getting file node of ID "
+ fileId, re);
}
}
import javax.jcr.query.qom.Selector;
import javax.jcr.query.qom.StaticOperand;
-import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.EclipseUiUtils;
import org.argeo.eclipse.ui.jcr.JcrUiUtils;
import org.argeo.eclipse.ui.jcr.lists.JcrColumnDefinition;
}
return result;
} else
- throw new ArgeoException("Unvalid request: no selection column "
+ throw new EclipseUiException("Unvalid request: no selection column "
+ "has been created for the current table");
}
else
return null;
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get font for " + username, e);
+ throw new EclipseUiException("Cannot get font for " + username, e);
}
}
}
return userProfile.hasProperty(name) ? userProfile
.getProperty(name).getString() : "";
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get property " + name, e);
+ throw new EclipseUiException("Cannot get property " + name, e);
}
}
hasFilter ? filterTxt.getText() : null));
usersViewer.setInput(nodes.toArray());
} catch (RepositoryException e) {
- throw new ArgeoException("Unable to list users", e);
+ throw new EclipseUiException("Unable to list users", e);
}
}
import java.util.ArrayList;
import java.util.List;
-import org.argeo.ArgeoException;
import org.argeo.eclipse.ui.ColumnDefinition;
+import org.argeo.eclipse.ui.EclipseUiException;
import org.argeo.eclipse.ui.EclipseUiUtils;
import org.argeo.eclipse.ui.utils.ViewerUtils;
import org.eclipse.jface.layout.TableColumnLayout;
}
return result;
} else
- throw new ArgeoException("Unvalid request: no selection column "
+ throw new EclipseUiException("Unvalid request: no selection column "
+ "has been created for the current table");
}
// for (Role role : roles)
// users.add((User) role);
// } catch (InvalidSyntaxException e) {
- // throw new ArgeoException("Unable to get roles with filter: "
+ // throw new EclipseUiException("Unable to get roles with filter: "
// + filter, e);
// }
// return users;
-Import-Package:org.bouncycastle.*;resolution:=optional,\
-bitronix.tm.*;resolution:=optional,\
-org.apache.commons.codec,\
-org.apache.commons.codec.digest,\
-*
package org.argeo.osgi.useradmin;
import java.util.ArrayList;
+import java.util.Base64;
import java.util.List;
import java.util.SortedMap;
import javax.naming.directory.Attributes;
import javax.naming.ldap.LdapName;
-import junit.framework.TestCase;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.codec.digest.DigestUtils;
import org.argeo.util.naming.LdifParser;
+import junit.framework.TestCase;
+
public class LdifParserTest extends TestCase implements BasicTestConstants {
public void testBasicLdif() throws Exception {
LdifParser ldifParser = new LdifParser();
assertEquals("{SHA}ieSV55Qc+eQOaYDRSha/AjzNTJE=",
new String(rawPwEntry));
byte[] hashedPassword = DigestUtils.sha1("demo".getBytes());
- assertEquals("{SHA}" + Base64.encodeBase64String(hashedPassword),
+ assertEquals("{SHA}" + Base64.getEncoder().encodeToString(hashedPassword),
new String(rawPwEntry));
LdapName adminDn = new LdapName(ADMIN_GROUP_DN);
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
+import java.util.Base64;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import javax.transaction.TransactionManager;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.codec.digest.DigestUtils;
-import org.apache.commons.io.IOUtils;
import org.osgi.service.useradmin.Authorization;
import org.osgi.service.useradmin.Group;
import org.osgi.service.useradmin.Role;
assertEquals("root@localhost", rootUser.getProperties().get("mail"));
// credentials
- byte[] hashedPassword = ("{SHA}" + Base64.encodeBase64String(DigestUtils.sha1("demo".getBytes()))).getBytes();
+ byte[] hashedPassword = ("{SHA}" + Base64.getEncoder().encodeToString(DigestUtils.sha1("demo".getBytes())))
+ .getBytes();
assertTrue(rootUser.hasCredential(LdifName.userPassword.name(), hashedPassword));
assertTrue(demoUser.hasCredential(LdifName.userPassword.name(), hashedPassword));
ByteArrayOutputStream out = new ByteArrayOutputStream();
((LdifUserAdmin) userAdmin).save(out);
byte[] arr = out.toByteArray();
- IOUtils.closeQuietly(out);
+ out.close();
userAdmin.destroy();
// String written = new String(arr);
// System.out.print(written);
+++ /dev/null
-package org.argeo.osgi.transaction.simple;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.transaction.HeuristicMixedException;
-import javax.transaction.HeuristicRollbackException;
-import javax.transaction.RollbackException;
-import javax.transaction.Status;
-import javax.transaction.Synchronization;
-import javax.transaction.SystemException;
-import javax.transaction.Transaction;
-import javax.transaction.xa.XAException;
-import javax.transaction.xa.XAResource;
-import javax.transaction.xa.Xid;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-class SimpleTransaction implements Transaction, Status {
- private final static Log log = LogFactory.getLog(SimpleTransaction.class);
-
- private final Xid xid;
- private int status = Status.STATUS_ACTIVE;
- private final List<XAResource> xaResources = new ArrayList<XAResource>();
-
- private final SimpleTransactionManager transactionManager;
-
- public SimpleTransaction(SimpleTransactionManager transactionManager) {
- this.xid = new UuidXid();
- this.transactionManager = transactionManager;
- }
-
- @Override
- public synchronized void commit() throws RollbackException,
- HeuristicMixedException, HeuristicRollbackException,
- SecurityException, IllegalStateException, SystemException {
- status = STATUS_PREPARING;
- for (XAResource xaRes : xaResources) {
- if (status == STATUS_MARKED_ROLLBACK)
- break;
- try {
- xaRes.prepare(xid);
- } catch (XAException e) {
- status = STATUS_MARKED_ROLLBACK;
- log.error("Cannot prepare " + xaRes + " for " + xid, e);
- }
- }
- if (status == STATUS_MARKED_ROLLBACK) {
- rollback();
- throw new RollbackException();
- }
- status = STATUS_PREPARED;
-
- status = STATUS_COMMITTING;
- for (XAResource xaRes : xaResources) {
- if (status == STATUS_MARKED_ROLLBACK)
- break;
- try {
- xaRes.commit(xid, false);
- } catch (XAException e) {
- status = STATUS_MARKED_ROLLBACK;
- log.error("Cannot prepare " + xaRes + " for " + xid, e);
- }
- }
- if (status == STATUS_MARKED_ROLLBACK) {
- rollback();
- throw new RollbackException();
- }
-
- // complete
- status = STATUS_COMMITTED;
- if (log.isDebugEnabled())
- log.debug("COMMITTED " + xid);
- clearResources(XAResource.TMSUCCESS);
- transactionManager.unregister(xid);
- }
-
- @Override
- public synchronized void rollback() throws IllegalStateException,
- SystemException {
- status = STATUS_ROLLING_BACK;
- for (XAResource xaRes : xaResources) {
- try {
- xaRes.rollback(xid);
- } catch (XAException e) {
- log.error("Cannot rollback " + xaRes + " for " + xid, e);
- }
- }
-
- // complete
- status = STATUS_ROLLEDBACK;
- if (log.isDebugEnabled())
- log.debug("ROLLEDBACK " + xid);
- clearResources(XAResource.TMFAIL);
- transactionManager.unregister(xid);
- }
-
- @Override
- public synchronized boolean enlistResource(XAResource xaRes)
- throws RollbackException, IllegalStateException, SystemException {
- if (xaResources.add(xaRes)) {
- try {
- xaRes.start(getXid(), XAResource.TMNOFLAGS);
- return true;
- } catch (XAException e) {
- log.error("Cannot enlist " + xaRes, e);
- return false;
- }
- } else
- return false;
- }
-
- @Override
- public synchronized boolean delistResource(XAResource xaRes, int flag)
- throws IllegalStateException, SystemException {
- if (xaResources.remove(xaRes)) {
- try {
- xaRes.end(getXid(), flag);
- } catch (XAException e) {
- log.error("Cannot delist " + xaRes, e);
- return false;
- }
- return true;
- } else
- return false;
- }
-
- protected void clearResources(int flag) {
- for (XAResource xaRes : xaResources)
- try {
- xaRes.end(getXid(), flag);
- } catch (XAException e) {
- log.error("Cannot end " + xaRes, e);
- }
- xaResources.clear();
- }
-
- @Override
- public synchronized int getStatus() throws SystemException {
- return status;
- }
-
- @Override
- public void registerSynchronization(Synchronization sync)
- throws RollbackException, IllegalStateException, SystemException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void setRollbackOnly() throws IllegalStateException, SystemException {
- status = STATUS_MARKED_ROLLBACK;
- }
-
- @Override
- public int hashCode() {
- return xid.hashCode();
- }
-
- Xid getXid() {
- return xid;
- }
-
-}
+++ /dev/null
-package org.argeo.osgi.transaction.simple;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.transaction.HeuristicMixedException;
-import javax.transaction.HeuristicRollbackException;
-import javax.transaction.InvalidTransactionException;
-import javax.transaction.NotSupportedException;
-import javax.transaction.RollbackException;
-import javax.transaction.Status;
-import javax.transaction.Synchronization;
-import javax.transaction.SystemException;
-import javax.transaction.Transaction;
-import javax.transaction.TransactionManager;
-import javax.transaction.TransactionSynchronizationRegistry;
-import javax.transaction.UserTransaction;
-import javax.transaction.xa.Xid;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class SimpleTransactionManager implements TransactionManager, UserTransaction {
- private final static Log log = LogFactory.getLog(SimpleTransactionManager.class);
-
- private ThreadLocal<SimpleTransaction> current = new ThreadLocal<SimpleTransaction>();
-
- private Map<Xid, SimpleTransaction> knownTransactions = Collections
- .synchronizedMap(new HashMap<Xid, SimpleTransaction>());
- private SyncRegistry syncRegistry = new SyncRegistry();
-
- @Override
- public void begin() throws NotSupportedException, SystemException {
- if (getCurrent() != null)
- throw new NotSupportedException("Nested transactions are not supported");
- SimpleTransaction transaction = new SimpleTransaction(this);
- knownTransactions.put(transaction.getXid(), transaction);
- current.set(transaction);
- if (log.isDebugEnabled())
- log.debug("STARTED " + transaction.getXid());
- }
-
- @Override
- public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException,
- SecurityException, IllegalStateException, SystemException {
- if (getCurrent() == null)
- throw new IllegalStateException("No transaction registered with the current thread.");
- getCurrent().commit();
- }
-
- @Override
- public int getStatus() throws SystemException {
- if (getCurrent() == null)
- return Status.STATUS_NO_TRANSACTION;
- return getTransaction().getStatus();
- }
-
- @Override
- public Transaction getTransaction() throws SystemException {
- return getCurrent();
- }
-
- protected SimpleTransaction getCurrent() throws SystemException {
- SimpleTransaction transaction = current.get();
- if (transaction == null)
- return null;
- int status = transaction.getStatus();
- if (Status.STATUS_COMMITTED == status || Status.STATUS_ROLLEDBACK == status) {
- current.remove();
- return null;
- }
- return transaction;
- }
-
- void unregister(Xid xid) {
- knownTransactions.remove(xid);
- }
-
- @Override
- public void resume(Transaction tobj) throws InvalidTransactionException, IllegalStateException, SystemException {
- if (getCurrent() != null)
- throw new IllegalStateException("Transaction " + current.get() + " already registered");
- current.set((SimpleTransaction) tobj);
- }
-
- @Override
- public void rollback() throws IllegalStateException, SecurityException, SystemException {
- if (getCurrent() == null)
- throw new IllegalStateException("No transaction registered with the current thread.");
- getCurrent().rollback();
- }
-
- @Override
- public void setRollbackOnly() throws IllegalStateException, SystemException {
- if (getCurrent() == null)
- throw new IllegalStateException("No transaction registered with the current thread.");
- getCurrent().setRollbackOnly();
- }
-
- @Override
- public void setTransactionTimeout(int seconds) throws SystemException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Transaction suspend() throws SystemException {
- Transaction transaction = getCurrent();
- current.remove();
- return transaction;
- }
-
- public TransactionSynchronizationRegistry getTsr() {
- return syncRegistry;
- }
-
- private class SyncRegistry implements TransactionSynchronizationRegistry {
- @Override
- public Object getTransactionKey() {
- try {
- SimpleTransaction transaction = getCurrent();
- if (transaction == null)
- return null;
- return getCurrent().getXid();
- } catch (SystemException e) {
- throw new RuntimeException("Cannot get transaction key", e);
- }
- }
-
- @Override
- public void putResource(Object key, Object value) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Object getResource(Object key) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void registerInterposedSynchronization(Synchronization sync) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getTransactionStatus() {
- try {
- return getStatus();
- } catch (SystemException e) {
- throw new RuntimeException("Cannot get status", e);
- }
- }
-
- @Override
- public boolean getRollbackOnly() {
- try {
- return getStatus() == Status.STATUS_MARKED_ROLLBACK;
- } catch (SystemException e) {
- throw new RuntimeException("Cannot get status", e);
- }
- }
-
- @Override
- public void setRollbackOnly() {
- try {
- getCurrent().setRollbackOnly();
- } catch (Exception e) {
- throw new RuntimeException("Cannot set rollback only", e);
- }
- }
-
- }
-}
+++ /dev/null
-package org.argeo.osgi.transaction.simple;
-
-import java.io.Serializable;
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-import java.util.UUID;
-
-import javax.transaction.xa.Xid;
-
-/**
- * Implementation of {@link Xid} based on {@link UUID}, using max significant
- * bits as global transaction id, and least significant bits as branch
- * qualifier.
- */
-public class UuidXid implements Xid, Serializable {
- private static final long serialVersionUID = -5380531989917886819L;
- public final static int FORMAT = (int) serialVersionUID;
-
- private final static int BYTES_PER_LONG = Long.SIZE / Byte.SIZE;
-
- private final int format;
- private final byte[] globalTransactionId;
- private final byte[] branchQualifier;
- private final String uuid;
- private final int hashCode;
-
- public UuidXid() {
- this(UUID.randomUUID());
- }
-
- public UuidXid(UUID uuid) {
- this.format = FORMAT;
- this.globalTransactionId = uuidToBytes(uuid.getMostSignificantBits());
- this.branchQualifier = uuidToBytes(uuid.getLeastSignificantBits());
- this.uuid = uuid.toString();
- this.hashCode = uuid.hashCode();
- }
-
- public UuidXid(Xid xid) {
- this(xid.getFormatId(), xid.getGlobalTransactionId(), xid
- .getBranchQualifier());
- }
-
- private UuidXid(int format, byte[] globalTransactionId,
- byte[] branchQualifier) {
- this.format = format;
- this.globalTransactionId = globalTransactionId;
- this.branchQualifier = branchQualifier;
- this.uuid = bytesToUUID(globalTransactionId, branchQualifier)
- .toString();
- this.hashCode = uuid.hashCode();
- }
-
- @Override
- public int getFormatId() {
- return format;
- }
-
- @Override
- public byte[] getGlobalTransactionId() {
- return Arrays.copyOf(globalTransactionId, globalTransactionId.length);
- }
-
- @Override
- public byte[] getBranchQualifier() {
- return Arrays.copyOf(branchQualifier, branchQualifier.length);
- }
-
- @Override
- public int hashCode() {
- return hashCode;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj instanceof UuidXid) {
- UuidXid that = (UuidXid) obj;
- return Arrays.equals(globalTransactionId, that.globalTransactionId)
- && Arrays.equals(branchQualifier, that.branchQualifier);
- }
- if (obj instanceof Xid) {
- Xid that = (Xid) obj;
- return Arrays.equals(globalTransactionId,
- that.getGlobalTransactionId())
- && Arrays
- .equals(branchQualifier, that.getBranchQualifier());
- }
- return uuid.equals(obj.toString());
- }
-
- @Override
- protected Object clone() throws CloneNotSupportedException {
- return new UuidXid(format, globalTransactionId, branchQualifier);
- }
-
- @Override
- public String toString() {
- return uuid;
- }
-
- public UUID asUuid() {
- return bytesToUUID(globalTransactionId, branchQualifier);
- }
-
- public static byte[] uuidToBytes(long bits) {
- ByteBuffer buffer = ByteBuffer.allocate(BYTES_PER_LONG);
- buffer.putLong(0, bits);
- return buffer.array();
- }
-
- public static UUID bytesToUUID(byte[] most, byte[] least) {
- if (most.length < BYTES_PER_LONG)
- most = Arrays.copyOf(most, BYTES_PER_LONG);
- if (least.length < BYTES_PER_LONG)
- least = Arrays.copyOf(least, BYTES_PER_LONG);
- ByteBuffer buffer = ByteBuffer.allocate(2 * BYTES_PER_LONG);
- buffer.put(most, 0, BYTES_PER_LONG);
- buffer.put(least, 0, BYTES_PER_LONG);
- buffer.flip();
- return new UUID(buffer.getLong(), buffer.getLong());
- }
-
- // public static void main(String[] args) {
- // UUID uuid = UUID.randomUUID();
- // System.out.println(uuid);
- // uuid = bytesToUUID(uuidToBytes(uuid.getMostSignificantBits()),
- // uuidToBytes(uuid.getLeastSignificantBits()));
- // System.out.println(uuid);
- // }
-}
--- /dev/null
+package org.argeo.osgi.useradmin;
+
+import java.security.MessageDigest;
+
+class DigestUtils {
+ static byte[] sha1(byte[] bytes) {
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA1");
+ digest.update(bytes);
+ byte[] checksum = digest.digest();
+ return checksum;
+ } catch (Exception e) {
+ throw new UserDirectoryException("Cannot SHA1 digest", e);
+ }
+ }
+
+ private DigestUtils() {
+ }
+
+}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
import org.osgi.framework.Filter;
/**
}
return directGroups;
} catch (Exception e) {
- throw new ArgeoException("Cannot populate direct members of " + dn, e);
+ throw new UserDirectoryException("Cannot populate direct members of " + dn, e);
}
}
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Base64;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import javax.naming.directory.BasicAttribute;
import javax.naming.ldap.LdapName;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.codec.digest.DigestUtils;
-
/** Directory user implementation */
class LdifUser implements DirectoryUser {
private final AbstractUserDirectory userAdmin;
this(userAdmin, dn, attributes, false);
}
- private LdifUser(AbstractUserDirectory userAdmin, LdapName dn,
- Attributes attributes, boolean frozen) {
+ private LdifUser(AbstractUserDirectory userAdmin, LdapName dn, Attributes attributes, boolean frozen) {
this.userAdmin = userAdmin;
this.dn = dn;
this.publishedAttributes = attributes;
/** Hash and clear the password */
private byte[] hash(char[] password) {
- byte[] hashedPassword = ("{SHA}" + Base64
- .encodeBase64String(DigestUtils.sha1(toBytes(password))))
+ byte[] hashedPassword = ("{SHA}" + Base64.getEncoder().encodeToString(DigestUtils.sha1(toBytes(password))))
.getBytes();
Arrays.fill(password, '\u0000');
return hashedPassword;
private byte[] toBytes(char[] chars) {
CharBuffer charBuffer = CharBuffer.wrap(chars);
ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
- byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
- byteBuffer.position(), byteBuffer.limit());
+ byte[] bytes = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit());
Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data
Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
return bytes;
if (obj instanceof char[])
return (char[]) obj;
if (!(obj instanceof byte[]))
- throw new IllegalArgumentException(obj.getClass()
- + " is not a byte array");
+ throw new IllegalArgumentException(obj.getClass() + " is not a byte array");
ByteBuffer fromBuffer = ByteBuffer.wrap((byte[]) obj);
CharBuffer toBuffer = Charset.forName("UTF-8").decode(fromBuffer);
- char[] res = Arrays.copyOfRange(toBuffer.array(), toBuffer.position(),
- toBuffer.limit());
+ char[] res = Arrays.copyOfRange(toBuffer.array(), toBuffer.position(), toBuffer.limit());
Arrays.fill(fromBuffer.array(), (byte) 0); // clear sensitive data
Arrays.fill((byte[]) obj, (byte) 0); // clear sensitive data
Arrays.fill(toBuffer.array(), '\u0000'); // clear sensitive data
effectiveKeys.add(id);
}
} catch (NamingException e) {
- throw new UserDirectoryException(
- "Cannot initialise attribute dictionary", e);
+ throw new UserDirectoryException("Cannot initialise attribute dictionary", e);
}
}
if (objectClasses.contains(userAdmin.getUserObjectClass()))
return userAdmin.getUserObjectClass();
- else if (objectClasses
- .contains(userAdmin.getGroupObjectClass()))
+ else if (objectClasses.contains(userAdmin.getGroupObjectClass()))
return userAdmin.getGroupObjectClass();
else
return value;
} catch (NamingException e) {
- throw new UserDirectoryException(
- "Cannot get value for attribute " + key, e);
+ throw new UserDirectoryException("Cannot get value for attribute " + key, e);
}
}
startEditing();
if (!(value instanceof String || value instanceof byte[]))
- throw new IllegalArgumentException(
- "Value must be String or byte[]");
+ throw new IllegalArgumentException("Value must be String or byte[]");
if (includeFilter && !attrFilter.contains(key))
- throw new IllegalArgumentException("Key " + key
- + " not included");
+ throw new IllegalArgumentException("Key " + key + " not included");
else if (!includeFilter && attrFilter.contains(key))
throw new IllegalArgumentException("Key " + key + " excluded");
try {
- Attribute attribute = getModifiedAttributes().get(
- key.toString());
+ Attribute attribute = getModifiedAttributes().get(key.toString());
attribute = new BasicAttribute(key.toString());
- if (value instanceof String
- && !isAsciiPrintable(((String) value)))
+ if (value instanceof String && !isAsciiPrintable(((String) value)))
try {
attribute.add(((String) value).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
- throw new UserDirectoryException("Cannot encode "
- + value, e);
+ throw new UserDirectoryException("Cannot encode " + value, e);
}
else
attribute.add(value);
- Attribute previousAttribute = getModifiedAttributes().put(
- attribute);
+ Attribute previousAttribute = getModifiedAttributes().put(attribute);
if (previousAttribute != null)
return previousAttribute.get();
else
return null;
} catch (NamingException e) {
- throw new UserDirectoryException(
- "Cannot get value for attribute " + key, e);
+ throw new UserDirectoryException("Cannot get value for attribute " + key, e);
}
}
startEditing();
if (includeFilter && !attrFilter.contains(key))
- throw new IllegalArgumentException("Key " + key
- + " not included");
+ throw new IllegalArgumentException("Key " + key + " not included");
else if (!includeFilter && attrFilter.contains(key))
throw new IllegalArgumentException("Key " + key + " excluded");
else
return null;
} catch (NamingException e) {
- throw new UserDirectoryException("Cannot remove attribute "
- + key, e);
+ throw new UserDirectoryException("Cannot remove attribute " + key, e);
}
}
}
import javax.naming.ldap.LdapName;
import javax.transaction.TransactionManager;
-import org.apache.commons.io.IOUtils;
import org.argeo.util.naming.LdifParser;
import org.argeo.util.naming.LdifWriter;
import org.osgi.framework.Filter;
for (LdapName name : users.keySet())
ldifWriter.writeEntry(name, users.get(name).getAttributes());
} finally {
- IOUtils.closeQuietly(out);
+ out.close();
}
}
import static org.argeo.osgi.useradmin.LdifName.dn;
+import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Base64;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.argeo.osgi.useradmin.UserDirectoryException;
public SortedMap<LdapName, Attributes> read(InputStream in) throws IOException {
SortedMap<LdapName, Attributes> res = new TreeMap<LdapName, Attributes>();
try {
- List<String> lines = IOUtils.readLines(in);
+ List<String> lines = new ArrayList<>();
+ try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
+ String line;
+ while ((line = br.readLine()) != null) {
+ lines.add(line);
+ }
+ }
if (lines.size() == 0)
return res;
// add an empty new line since the last line is not checked
String attributeId = attrId.toString();
String cleanValueStr = currentEntry.toString().trim();
- Object attributeValue = isBase64 ? Base64.decodeBase64(cleanValueStr) : cleanValueStr;
+ Object attributeValue = isBase64 ? Base64.getDecoder().decode(cleanValueStr) : cleanValueStr;
// manage DN attributes
if (attributeId.equals(dn.name()) || isLastLine) {
currentEntry.append(line);
}
} finally {
- IOUtils.closeQuietly(in);
+ in.close();
}
return res;
}
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
+import java.util.Base64;
import java.util.Map;
import javax.naming.NamingEnumeration;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
-import org.apache.commons.codec.binary.Base64;
import org.argeo.osgi.useradmin.UserDirectoryException;
/** Basic LDIF writer */
for (NamingEnumeration<?> attrValues = attribute.getAll(); attrValues.hasMore();) {
Object value = attrValues.next();
if (value instanceof byte[]) {
- String encoded = Base64.encodeBase64String((byte[]) value);
+ String encoded = Base64.getEncoder().encodeToString((byte[]) value);
writer.append(attribute.getID()).append("::").append(encoded).append('\n');
} else {
writer.append(attribute.getID()).append(':').append(value.toString()).append('\n');
package org.argeo.security.ui.admin.internal;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IStartup;
if (iwp != null)
iwp.addPartListener(new PartStateChanged());
} catch (Exception e) {
- throw new ArgeoException(
+ throw new CmsException(
"Error while registering the PartStateChangedListener",
e);
}
import javax.transaction.UserTransaction;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.security.ui.admin.internal.providers.UserTransactionProvider;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
.getSourceProvider(UserTransactionProvider.TRANSACTION_STATE);
esp.fireTransactionStateChange();
} catch (Exception e) {
- throw new ArgeoException("Unable to begin transaction", e);
+ throw new CmsException("Unable to begin transaction", e);
}
}
}
\ No newline at end of file
import javax.transaction.Status;
import javax.transaction.UserTransaction;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.osgi.service.useradmin.UserAdminEvent;
import org.osgi.service.useradmin.UserAdminListener;
}
return userTransaction;
} catch (Exception e) {
- throw new ArgeoException("Unable to begin transaction", e);
+ throw new CmsException("Unable to begin transaction", e);
}
}
import java.util.Dictionary;
import java.util.Map;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.eclipse.ui.EclipseUiUtils;
import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
import org.argeo.jcr.ArgeoNames;
private void initialiseDnCmb(Combo combo) {
Map<String, String> dns = userAdminWrapper.getKnownBaseDns(true);
if (dns.isEmpty())
- throw new ArgeoException(
+ throw new CmsException(
"No writable base dn found. Cannot create group");
combo.setItems(dns.keySet().toArray(new String[0]));
if (dns.size() == 1)
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.util.useradmin.UserAdminUtils;
import org.argeo.eclipse.ui.EclipseUiUtils;
import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
private void initialiseDnCmb(Combo combo) {
Map<String, String> dns = userAdminWrapper.getKnownBaseDns(true);
if (dns.isEmpty())
- throw new ArgeoException(
+ throw new CmsException(
"No writable base dn found. Cannot create user");
combo.setItems(dns.keySet().toArray(new String[0]));
if (dns.size() == 1)
return username + "@" + (String) rdns.get(1).getValue() + '.'
+ (String) rdns.get(0).getValue();
} catch (InvalidNameException e) {
- throw new ArgeoException("Unable to generate mail for "
+ throw new CmsException("Unable to generate mail for "
+ username + " with base dn " + baseDn, e);
}
}
import javax.transaction.Status;
import javax.transaction.UserTransaction;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.security.ui.admin.SecurityAdminPlugin;
import org.argeo.security.ui.admin.internal.UiAdminUtils;
import org.argeo.security.ui.admin.internal.UserAdminWrapper;
try {
if (TRANSACTION_BEGIN.equals(commandId)) {
if (userTransaction.getStatus() != Status.STATUS_NO_TRANSACTION)
- throw new ArgeoException("A transaction already exists");
+ throw new CmsException("A transaction already exists");
else
userTransaction.begin();
} else if (TRANSACTION_COMMIT.equals(commandId)) {
if (userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION)
- throw new ArgeoException("No transaction.");
+ throw new CmsException("No transaction.");
else
userTransaction.commit();
} else if (TRANSACTION_ROLLBACK.equals(commandId)) {
if (userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION)
- throw new ArgeoException("No transaction to rollback.");
+ throw new CmsException("No transaction to rollback.");
else {
userTransaction.rollback();
userAdminWrapper.notifyListeners(new UserAdminEvent(null,
}
});
- } catch (ArgeoException e) {
+ } catch (CmsException e) {
throw e;
} catch (Exception e) {
- throw new ArgeoException("Unable to call " + commandId + " on "
+ throw new CmsException("Unable to call " + commandId + " on "
+ userTransaction, e);
}
return null;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.jcr.ArgeoNames;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
createGeneralPart(form.getBody());
createPassworPart(form.getBody());
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot create form content", e);
+ throw new CmsException("Cannot create form content", e);
}
}
if (log.isTraceEnabled())
log.trace("General part committed");
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot commit", e);
+ throw new CmsException("Cannot commit", e);
}
}
};
} else {
password1.setText("");
password2.setText("");
- throw new ArgeoException("Passwords are not equals");
+ throw new CmsException("Passwords are not equals");
}
}
}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.auth.AuthConstants;
import org.argeo.cms.util.useradmin.UserAdminUtils;
import org.argeo.eclipse.ui.ColumnDefinition;
roles = userAdminWrapper.getUserAdmin().getRoles(
builder.toString());
} catch (InvalidSyntaxException e) {
- throw new ArgeoException("Unable to get roles with filter: "
+ throw new CmsException("Unable to get roles with filter: "
+ filter, e);
}
List<User> users = new ArrayList<User>();
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.auth.AuthConstants;
import org.argeo.cms.util.useradmin.UserAdminUtils;
import org.argeo.eclipse.ui.ColumnDefinition;
+ "are you sure you want to proceed ?"))
return false;
} catch (SystemException e) {
- throw new ArgeoException("Cannot get user transaction state "
+ throw new CmsException("Cannot get user transaction state "
+ "before user batch update", e);
}
if (CMD_UPDATE_PASSWORD.equals(chooseCommandPage.getCommand())) {
char[] newValue = chooseCommandPage.getPwdValue();
if (newValue == null)
- throw new ArgeoException(
+ throw new CmsException(
"Password cannot be null or an empty string");
ResetPassword job = new ResetPassword(userAdminWrapper,
userListPage.getSelectedUsers(), newValue);
userTransaction.commit();
UiAdminUtils.notifyTransactionStateChange(userTransaction);
} catch (Exception e) {
- throw new ArgeoException(
+ throw new CmsException(
"Cannot perform batch update on users", e);
} finally {
UserTransaction ut = userAdminWrapper.getUserTransaction();
// log.info("Add/Remove to group actions are not yet implemented");
// // TODO implement this
// // try {
- // // throw new ArgeoException("Not yet implemented");
+ // // throw new CmsException("Not yet implemented");
// // } catch (RepositoryException re) {
- // // throw new ArgeoException(
+ // // throw new CmsException(
// // "Unable to update boolean value for node " + node, re);
// // }
// }
// }
// userAdminWrapper.getUserTransaction().commit();
// } catch (Exception e) {
- // throw new ArgeoException(
+ // throw new CmsException(
// "Cannot perform batch update on users", e);
// } finally {
// UserTransaction ut = userAdminWrapper.getUserTransaction();
roles = userAdminWrapper.getUserAdmin().getRoles(
builder.toString());
} catch (InvalidSyntaxException e) {
- throw new ArgeoException(
+ throw new CmsException(
"Unable to get roles with filter: " + filter, e);
}
List<User> users = new ArrayList<User>();
import java.util.ArrayList;
import java.util.List;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.util.useradmin.UserAdminUtils;
import org.argeo.osgi.useradmin.LdifName;
import org.argeo.security.ui.admin.SecurityAdminPlugin;
else
addPage(new UserMainPage(this, userAdminWrapper));
} catch (Exception e) {
- throw new ArgeoException("Cannot add pages", e);
+ throw new CmsException("Cannot add pages", e);
}
}
import java.util.Iterator;
import java.util.List;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.auth.AuthConstants;
import org.argeo.cms.util.useradmin.UserAdminUtils;
import org.argeo.eclipse.ui.ColumnDefinition;
} else {
password1.setText("");
password2.setText("");
- throw new ArgeoException("Passwords are not equals");
+ throw new CmsException("Passwords are not equals");
}
}
}
import java.util.ArrayList;
import java.util.List;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.auth.AuthConstants;
import org.argeo.cms.util.useradmin.UserAdminUtils;
import org.argeo.eclipse.ui.ColumnDefinition;
roles = userAdminWrapper.getUserAdmin().getRoles(
builder.toString());
} catch (InvalidSyntaxException e) {
- throw new ArgeoException("Unable to get roles with filter: "
+ throw new CmsException("Unable to get roles with filter: "
+ filter, e);
}
List<User> users = new ArrayList<User>();
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.util.useradmin.UserAdminUtils;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ColumnLabelProvider;
return bold;
}
} catch (InvalidNameException e) {
- throw new ArgeoException("cannot parse dn for " + element, e);
+ throw new CmsException("cannot parse dn for " + element, e);
}
// Disabled as Italic
package org.argeo.security.ui.admin.internal.providers;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.eclipse.ui.workbench.WorkbenchUiPlugin;
import org.argeo.security.ui.admin.internal.parts.UserEditor;
import org.argeo.security.ui.admin.internal.parts.UserEditorInput;
else
iwp.openEditor(uei, UserEditor.USER_EDITOR_ID);
} catch (PartInitException pie) {
- throw new ArgeoException("Unable to open UserEditor for " + user,
+ throw new CmsException("Unable to open UserEditor for " + user,
pie);
}
}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.security.ui.admin.SecurityAdminPlugin;
import org.eclipse.swt.SWTException;
import org.eclipse.ui.AbstractSourceProvider;
transactionState = STATUS_ACTIVE;
return transactionState;
} catch (Exception e) {
- throw new ArgeoException("Unable to begin transaction", e);
+ throw new CmsException("Unable to begin transaction", e);
}
}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.auth.AuthConstants;
import org.eclipse.rap.rwt.RWT;
import org.eclipse.rap.rwt.application.EntryPoint;
subject);
loginContext.login();
} catch (LoginException e1) {
- throw new ArgeoException("Cannot initialize login context", e1);
+ throw new CmsException("Cannot initialize login context", e1);
}
// identify after successful login
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.auth.AuthConstants;
import org.argeo.cms.auth.ThreadDeathLoginException;
import org.argeo.cms.widgets.auth.DefaultLoginDialog;
AuthConstants.LOGIN_CONTEXT_USER, subject,
callbackHandler);
} catch (LoginException e1) {
- throw new ArgeoException("Cannot initialize login context", e1);
+ throw new CmsException("Cannot initialize login context", e1);
}
tryLogin: while (subject.getPrincipals(X500Principal.class).size() == 0) {
try {
loginContext.login();
if (subject.getPrincipals(X500Principal.class).size() == 0)
- throw new ArgeoException("Login succeeded but no auth");// fatal
+ throw new CmsException("Login succeeded but no auth");// fatal
// add thread locale to RWT session
// if (log.isTraceEnabled())
display.dispose();
return -1;
} else {
- throw new ArgeoException(
+ throw new CmsException(
"Unexpected exception during authentication", e);
}
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.cms.widgets.auth.DefaultLoginDialog;
import org.eclipse.swt.widgets.Display;
import org.osgi.framework.BundleActivator;
private ServiceRegistration<CallbackHandler> defaultCallbackHandlerReg;
public void start(BundleContext context) throws Exception {
- if (bundleContext != null)
- if (!bundleContext.equals(bundleContext))
- throw new ArgeoException(
- "Bundle context already set with a different value");
- else
- return;
-
bundleContext = context;
defaultCallbackHandler = new DefaultCallbackHandler();
try {
dialog.handle(callbacks);
} catch (IOException e) {
- throw new ArgeoException("Cannot open dialog", e);
+ throw new CmsException("Cannot open dialog", e);
}
}
});
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.cms.CmsException;
import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
try {
dn = new LdapName(name);
} catch (InvalidNameException e) {
- throw new ArgeoException("Invalid user dn " + name, e);
+ throw new CmsException("Invalid user dn " + name, e);
}
User user = (User) userAdmin.getRole(dn.toString());
if (!user.hasCredential(null, oldPassword))
- throw new ArgeoException("Invalid password");
+ throw new CmsException("Invalid password");
if (newPassword.equals(""))
- throw new ArgeoException("New password empty");
+ throw new CmsException("New password empty");
try {
userTransaction.begin();
user.getCredentials().put(null, newPassword);
if (e instanceof RuntimeException)
throw (RuntimeException) e;
else
- throw new ArgeoException("Cannot change password", e);
+ throw new CmsException("Cannot change password", e);
}
}
protected void okPressed() {
try {
if (!newPassword1.getText().equals(newPassword2.getText()))
- throw new ArgeoException("New passwords are different");
+ throw new CmsException("New passwords are different");
changePassword(oldPassword.getTextChars(),
newPassword1.getTextChars());
close();
import org.apache.jackrabbit.core.RepositoryImpl;
import org.apache.jackrabbit.core.config.RepositoryConfig;
import org.apache.jackrabbit.core.config.RepositoryConfigurationParser;
-import org.argeo.ArgeoException;
+import org.argeo.jcr.ArgeoJcrException;
import org.argeo.jcr.ArgeoNames;
import org.argeo.jcr.JcrUtils;
import org.springframework.core.io.Resource;
// long begin = System.currentTimeMillis();
if (getRepository() != null)
- throw new ArgeoException("Cannot be used to wrap another repository");
+ throw new ArgeoJcrException("Cannot be used to wrap another repository");
Repository repository = createJackrabbitRepository();
super.setRepository(repository);
return repository;
} catch (Exception e) {
- throw new ArgeoException("Cannot create Jackrabbit repository " + getHomeDirectory(), e);
+ throw new ArgeoJcrException("Cannot create Jackrabbit repository " + getHomeDirectory(), e);
} finally {
IOUtils.closeQuietly(configurationIn);
}
return homeDirectory.getCanonicalFile();
} catch (IOException e) {
- throw new ArgeoException("Cannot get canonical file for " + homeDirectory, e);
+ throw new ArgeoJcrException("Cannot get canonical file for " + homeDirectory, e);
}
}
restartAndClearCaches = true;
}
}
- } catch (ArgeoException e) {
+ } catch (ArgeoJcrException e) {
throw e;
} catch (Exception e) {
- throw new ArgeoException("Cannot migrate", e);
+ throw new ArgeoJcrException("Cannot migrate", e);
} finally {
JcrUtils.logoutQuietly(session);
}
try {
session = login();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot login to migrated repository", e);
+ throw new ArgeoJcrException("Cannot login to migrated repository", e);
}
for (JackrabbitDataModelMigration dataModelMigration : new TreeSet<JackrabbitDataModelMigration>(
try {
return configuration != null ? configuration.getInputStream() : null;
} catch (IOException e) {
- throw new ArgeoException("Cannot read Jackrabbit configuration " + configuration, e);
+ throw new ArgeoJcrException("Cannot read Jackrabbit configuration " + configuration, e);
}
}
try {
return variables != null ? variables.getInputStream() : null;
} catch (IOException e) {
- throw new ArgeoException("Cannot read Jackrabbit variables " + variables, e);
+ throw new ArgeoJcrException("Cannot read Jackrabbit variables " + variables, e);
}
}
}
} catch (IOException e) {
- throw new ArgeoException("Cannot read configuration properties", e);
+ throw new ArgeoJcrException("Cannot read configuration properties", e);
} finally {
IOUtils.closeQuietly(propsIn);
}
}
public void setRepository(Repository repository) {
- throw new ArgeoException("Cannot be used to wrap another repository");
+ throw new ArgeoJcrException("Cannot be used to wrap another repository");
}
public void setDataModelMigrations(Set<JackrabbitDataModelMigration> dataModelMigrations) {
import org.apache.commons.logging.LogFactory;
import org.apache.jackrabbit.commons.cnd.CndImporter;
import org.apache.jackrabbit.core.config.RepositoryConfig;
-import org.argeo.ArgeoException;
+import org.argeo.jcr.ArgeoJcrException;
import org.argeo.jcr.ArgeoNames;
import org.argeo.jcr.JcrCallback;
import org.argeo.jcr.JcrUtils;
return true;
} catch (Exception e) {
JcrUtils.discardQuietly(session);
- throw new ArgeoException("Migration of data model "
+ throw new ArgeoJcrException("Migration of data model "
+ dataModelNodePath + " to " + targetVersion + " failed.",
e);
} finally {
if (log.isDebugEnabled())
log.debug("Cleared " + customeNodeTypesPath);
} catch (Exception e) {
- throw new ArgeoException("Cannot clear caches", e);
+ throw new ArgeoJcrException("Cannot clear caches", e);
}
// File customNodeTypes = new File(home.getPath()
import org.apache.jackrabbit.core.config.RepositoryConfig;
import org.apache.jackrabbit.core.config.RepositoryConfigurationParser;
import org.apache.jackrabbit.jcr2dav.Jcr2davRepositoryFactory;
-import org.argeo.ArgeoException;
import org.argeo.jcr.ArgeoJcrConstants;
import org.argeo.jcr.ArgeoJcrException;
import org.springframework.core.io.ClassPathResource;
params.put(JcrUtils.REPOSITORY_URI, uri);
Repository repository = new Jcr2davRepositoryFactory().getRepository(params);
if (repository == null)
- throw new ArgeoException("Remote Davex repository " + uri + " not found");
+ throw new ArgeoJcrException("Remote Davex repository " + uri + " not found");
log.info("Initialized remote Jackrabbit repository from uri " + uri);
return repository;
}
String dirPath = uri.substring("file:".length());
File homeDir = new File(dirPath);
if (homeDir.exists() && !homeDir.isDirectory())
- throw new ArgeoException("Repository home " + dirPath + " is not a directory");
+ throw new ArgeoJcrException("Repository home " + dirPath + " is not a directory");
if (!homeDir.exists())
homeDir.mkdirs();
configurationIn = fileRepositoryConfiguration.getInputStream();
log.info("Initialized file Jackrabbit repository from uri " + uri);
return repository;
} catch (Exception e) {
- throw new ArgeoException("Cannot create repository " + uri, e);
+ throw new ArgeoJcrException("Cannot create repository " + uri, e);
} finally {
IOUtils.closeQuietly(configurationIn);
}
alias = alias.substring(0, alias.length() - 1);
return alias;
} catch (URISyntaxException e) {
- throw new ArgeoException("Cannot interpret URI " + uri, e);
+ throw new ArgeoJcrException("Cannot interpret URI " + uri, e);
}
}
import javax.jcr.NoSuchWorkspaceException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
+import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.nodetype.NodeType;
import org.apache.jackrabbit.api.JackrabbitRepository;
import org.apache.jackrabbit.commons.NamespaceHelper;
import org.apache.jackrabbit.commons.cnd.CndImporter;
-import org.argeo.ArgeoException;
import org.argeo.jcr.ArgeoJcrConstants;
+import org.argeo.jcr.ArgeoJcrException;
import org.argeo.jcr.ArgeoNames;
import org.argeo.jcr.ArgeoTypes;
import org.argeo.jcr.JcrRepositoryWrapper;
}
} catch (Exception e) {
JcrUtils.discardQuietly(session);
- throw new ArgeoException("Cannot import node type definitions "
+ throw new ArgeoJcrException("Cannot import node type definitions "
+ cndFiles, e);
} finally {
JcrUtils.logoutQuietly(session);
+ (bundle != null ? ", version " + bundle.getVersion()
+ ", bundle " + bundle.getSymbolicName() : ""));
} catch (Exception e) {
- throw new ArgeoException("Cannot process data model " + resUrl, e);
+ throw new ArgeoJcrException("Cannot process data model " + resUrl, e);
} finally {
IOUtils.closeQuietly(reader);
}
in = res.getInputStream();
url = res.getURL();
} else {
- throw new ArgeoException("No " + resUrl + " in the classpath,"
+ throw new ArgeoJcrException("No " + resUrl + " in the classpath,"
+ " make sure the containing" + " package is visible.");
}
return IOUtils.toByteArray(in);
} catch (Exception e) {
- throw new ArgeoException("Cannot read CND from " + resUrl, e);
+ throw new ArgeoJcrException("Cannot read CND from " + resUrl, e);
} finally {
IOUtils.closeQuietly(in);
}
ExportedPackage[] exportedPackages = packageAdmin
.getExportedPackages(pkg);
if (exportedPackages == null)
- throw new ArgeoException("No exported package found for " + pkg);
+ throw new ArgeoJcrException("No exported package found for " + pkg);
for (ExportedPackage ep : exportedPackages) {
for (Bundle b : ep.getImportingBundles()) {
if (b.getBundleId() == bundleContext.getBundle().getBundleId()) {
} else {
// assume this is in the same bundle
exportingBundle = bundleContext.getBundle();
- // throw new ArgeoException("No OSGi exporting package found for "
+ // throw new ArgeoJcrException("No OSGi exporting package found for "
// + resUrl);
}
return exportingBundle;
import javax.jcr.RepositoryException;
import javax.jcr.RepositoryFactory;
-import org.argeo.ArgeoException;
-
/** Utilities related to Argeo model in JCR */
public class ArgeoJcrUtils implements ArgeoJcrConstants {
/**
parameters.put(JCR_REPOSITORY_ALIAS, alias);
return repositoryFactory.getRepository(parameters);
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new ArgeoJcrException(
"Unexpected exception when trying to retrieve repository with alias "
+ alias, e);
}
parameters.put(JCR_REPOSITORY_ALIAS, alias);
return repositoryFactory.getRepository(parameters);
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new ArgeoJcrException(
"Unexpected exception when trying to retrieve repository with uri "
+ uri, e);
}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
/** To be overridden */
public class DefaultJcrListener implements EventListener {
if (log.isDebugEnabled())
log.debug("Registered JCR event listener on " + path);
} catch (Exception e) {
- throw new ArgeoException("Cannot register event listener", e);
+ throw new ArgeoJcrException("Cannot register event listener", e);
}
}
if (log.isDebugEnabled())
log.debug("Unregistered JCR event listener on " + path);
} catch (Exception e) {
- throw new ArgeoException("Cannot unregister event listener", e);
+ throw new ArgeoJcrException("Cannot unregister event listener", e);
}
}
import javax.jcr.RepositoryException;
import javax.jcr.RepositoryFactory;
-import org.argeo.ArgeoException;
-
/**
* Simple implementation of {@link RepositoryFactory}, supporting OSGi aliases.
*/
alias = alias.substring(0, alias.length() - 1);
return alias;
} catch (URISyntaxException e) {
- throw new ArgeoException("Cannot interpret URI " + uri, e);
+ throw new ArgeoJcrException("Cannot interpret URI " + uri, e);
}
}
--- /dev/null
+package org.argeo.jcr;
+
+import org.argeo.ArgeoMonitor;
+
+/**
+ * Simple monitor abstraction. Inspired by Eclipse IProgressMOnitor, but without
+ * dependency to it.
+ */
+@SuppressWarnings("deprecation")
+public interface JcrMonitor extends ArgeoMonitor {
+ /**
+ * Constant indicating an unknown amount of work.
+ */
+ public final static int UNKNOWN = -1;
+
+ /**
+ * Notifies that the main task is beginning. This must only be called once
+ * on a given progress monitor instance.
+ *
+ * @param name
+ * the name (or description) of the main task
+ * @param totalWork
+ * the total number of work units into which the main task is
+ * been subdivided. If the value is <code>UNKNOWN</code> the
+ * implementation is free to indicate progress in a way which
+ * doesn't require the total number of work units in advance.
+ */
+ public void beginTask(String name, int totalWork);
+
+ /**
+ * Notifies that the work is done; that is, either the main task is
+ * completed or the user canceled it. This method may be called more than
+ * once (implementations should be prepared to handle this case).
+ */
+ public void done();
+
+ /**
+ * Returns whether cancelation of current operation has been requested.
+ * Long-running operations should poll to see if cancelation has been
+ * requested.
+ *
+ * @return <code>true</code> if cancellation has been requested, and
+ * <code>false</code> otherwise
+ * @see #setCanceled(boolean)
+ */
+ public boolean isCanceled();
+
+ /**
+ * Sets the cancel state to the given value.
+ *
+ * @param value
+ * <code>true</code> indicates that cancelation has been
+ * requested (but not necessarily acknowledged);
+ * <code>false</code> clears this flag
+ * @see #isCanceled()
+ */
+ public void setCanceled(boolean value);
+
+ /**
+ * Sets the task name to the given value. This method is used to restore the
+ * task label after a nested operation was executed. Normally there is no
+ * need for clients to call this method.
+ *
+ * @param name
+ * the name (or description) of the main task
+ * @see #beginTask(java.lang.String, int)
+ */
+ public void setTaskName(String name);
+
+ /**
+ * Notifies that a subtask of the main task is beginning. Subtasks are
+ * optional; the main task might not have subtasks.
+ *
+ * @param name
+ * the name (or description) of the subtask
+ */
+ public void subTask(String name);
+
+ /**
+ * Notifies that a given number of work unit of the main task has been
+ * completed. Note that this amount represents an installment, as opposed to
+ * a cumulative amount of work done to date.
+ *
+ * @param work
+ * a non-negative number of work units just completed
+ */
+ public void worked(int work);
+
+}
import javax.jcr.Session;
import javax.jcr.Value;
-import org.argeo.ArgeoException;
-
/**
* Wrapper around a JCR repository which allows to simplify configuration and
* intercept some actions. It exposes itself as a {@link Repository}.
/** Wraps access to the repository, making sure it is available. */
protected synchronized Repository getRepository() {
// if (repository == null) {
-// throw new ArgeoException("No repository initialized."
+// throw new ArgeoJcrException("No repository initialized."
// + " Was the init() method called?"
// + " The destroy() method should also"
// + " be called on shutdown.");
protected Session createWorkspaceAndLogsIn(Credentials credentials,
String workspaceName) throws RepositoryException {
if (workspaceName == null)
- throw new ArgeoException("No workspace specified.");
+ throw new ArgeoJcrException("No workspace specified.");
Session session = getRepository().login(credentials);
session.getWorkspace().createWorkspace(workspaceName);
session.logout();
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
/**
* Bridge Spring resources and JCR folder / files semantics (nt:folder /
public void create(String path, InputStream in, String mimeType) {
try {
if (session().itemExists(path)) {
- throw new ArgeoException("Node " + path + " already exists.");
+ throw new ArgeoJcrException("Node " + path + " already exists.");
}
int index = path.lastIndexOf('/');
parentPath = "/";
String fileName = path.substring(index + 1);
if (!session().itemExists(parentPath))
- throw new ArgeoException("Parent folder of node " + path
+ throw new ArgeoJcrException("Parent folder of node " + path
+ " does not exist: " + parentPath);
Node folderNode = (Node) session().getItem(parentPath);
if (log.isDebugEnabled())
log.debug("Created " + path);
} catch (Exception e) {
- throw new ArgeoException("Cannot create node for " + path, e);
+ throw new ArgeoJcrException("Cannot create node for " + path, e);
}
}
if (log.isDebugEnabled())
log.debug("Updated " + path);
} catch (Exception e) {
- throw new ArgeoException("Cannot update node " + path, e);
+ throw new ArgeoJcrException("Cannot update node " + path, e);
}
}
public List<Calendar> listVersions(String path) {
if (!versioning)
- throw new ArgeoException("Versioning is not activated");
+ throw new ArgeoJcrException("Versioning is not activated");
try {
List<Calendar> versions = new ArrayList<Calendar>();
}
return versions;
} catch (Exception e) {
- throw new ArgeoException("Cannot list version of node " + path, e);
+ throw new ArgeoJcrException("Cannot list version of node " + path, e);
}
}
Property property = node.getProperty(Property.JCR_DATA);
return property.getBinary().getStream();
} catch (Exception e) {
- throw new ArgeoException("Cannot retrieve " + path, e);
+ throw new ArgeoJcrException("Cannot retrieve " + path, e);
}
}
public synchronized InputStream retrieve(String path, Integer revision) {
if (!versioning)
- throw new ArgeoException("Versioning is not activated");
+ throw new ArgeoJcrException("Versioning is not activated");
try {
Node fileNode = (Node) session().getItem(path);
count++;
}
} catch (Exception e) {
- throw new ArgeoException("Cannot retrieve version " + revision
+ throw new ArgeoJcrException("Cannot retrieve version " + revision
+ " of " + path, e);
}
- throw new ArgeoException("Version " + revision
+ throw new ArgeoJcrException("Version " + revision
+ " does not exist for node " + path);
}
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
import org.argeo.ArgeoMonitor;
import org.argeo.util.security.DigestUtils;
import org.argeo.util.security.SimplePrincipal;
* Queries one single node.
*
* @return one single node or null if none was found
- * @throws ArgeoException
+ * @throws ArgeoJcrException
* if more than one node was found
*/
public static Node querySingleNode(Query query) {
QueryResult queryResult = query.execute();
nodeIterator = queryResult.getNodes();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot execute query " + query, e);
+ throw new ArgeoJcrException("Cannot execute query " + query, e);
}
Node node;
if (nodeIterator.hasNext())
return null;
if (nodeIterator.hasNext())
- throw new ArgeoException("Query returned more than one node.");
+ throw new ArgeoJcrException("Query returned more than one node.");
return node;
}
if (path.equals("/"))
return "";
if (path.charAt(0) != '/')
- throw new ArgeoException("Path " + path + " must start with a '/'");
+ throw new ArgeoJcrException("Path " + path + " must start with a '/'");
String pathT = path;
if (pathT.charAt(pathT.length() - 1) == '/')
pathT = pathT.substring(0, pathT.length() - 2);
/** Retrieves the parent path of the provided path */
public static String parentPath(String path) {
if (path.equals("/"))
- throw new ArgeoException("Root path '/' has no parent path");
+ throw new ArgeoJcrException("Root path '/' has no parent path");
if (path.charAt(0) != '/')
- throw new ArgeoException("Path " + path + " must start with a '/'");
+ throw new ArgeoJcrException("Path " + path + " must start with a '/'");
String pathT = path;
if (pathT.charAt(pathT.length() - 1) == '/')
pathT = pathT.substring(0, pathT.length() - 2);
path.append(u.getPath());
return path.toString();
} catch (MalformedURLException e) {
- throw new ArgeoException("Cannot generate URL path for " + url, e);
+ throw new ArgeoJcrException("Cannot generate URL path for " + url, e);
}
}
node.setProperty(Property.JCR_PORT, Integer.toString(u.getPort()));
node.setProperty(Property.JCR_PATH, normalizePath(u.getPath()));
} catch (Exception e) {
- throw new ArgeoException("Cannot set URL " + url
+ throw new ArgeoJcrException("Cannot set URL " + url
+ " as nt:address properties", e);
}
}
.getProperty(Property.JCR_PATH).getString());
return u.toString();
} catch (Exception e) {
- throw new ArgeoException(
+ throw new ArgeoJcrException(
"Cannot get URL from nt:address properties of " + node, e);
}
}
calendar.setTime(date);
return calendar;
} catch (ParseException e) {
- throw new ArgeoException("Cannot parse " + value
+ throw new ArgeoJcrException("Cannot parse " + value
+ " with date format " + dateFormat, e);
}
/** The last element of a path. */
public static String lastPathElement(String path) {
if (path.charAt(path.length() - 1) == '/')
- throw new ArgeoException("Path " + path + " cannot end with '/'");
+ throw new ArgeoJcrException("Path " + path + " cannot end with '/'");
int index = path.lastIndexOf('/');
if (index < 0)
return path;
try {
return node.getName();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get name from " + node, e);
+ throw new ArgeoJcrException("Cannot get name from " + node, e);
}
}
try {
return node.getProperty(propertyName).getString();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get name from " + node, e);
+ throw new ArgeoJcrException("Cannot get name from " + node, e);
}
}
return null;
return node.getProperty(propertyName).getString();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get property " + propertyName
+ throw new ArgeoJcrException("Cannot get property " + propertyName
+ " of " + node, e);
}
}
try {
return node.getProperty(propertyName).getBoolean();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get property " + propertyName
+ throw new ArgeoJcrException("Cannot get property " + propertyName
+ " of " + node, e);
}
}
try {
return getBinaryAsBytes(node.getProperty(propertyName));
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot get property " + propertyName
+ throw new ArgeoJcrException("Cannot get property " + propertyName
+ " of " + node, e);
}
}
}
return currParent;
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot mkdirs relative path "
+ throw new ArgeoJcrException("Cannot mkdirs relative path "
+ relativePath + " from " + parentNode, e);
}
}
String type) {
try {
if (session.hasPendingChanges())
- throw new ArgeoException(
+ throw new ArgeoJcrException(
"Session has pending changes, save them first.");
Node node = mkdirs(session, path, type);
session.save();
return node;
} catch (RepositoryException e) {
discardQuietly(session);
- throw new ArgeoException("Cannot safely make directories", e);
+ throw new ArgeoJcrException("Cannot safely make directories", e);
}
}
// check type
if (type != null && !node.isNodeType(type)
&& !node.getPath().equals("/"))
- throw new ArgeoException("Node " + node
+ throw new ArgeoJcrException("Node " + node
+ " exists but is of type "
+ node.getPrimaryNodeType().getName()
+ " not of type " + type);
return currentNode;
} catch (RepositoryException e) {
discardQuietly(session);
- throw new ArgeoException("Cannot mkdirs " + path, e);
+ throw new ArgeoJcrException("Cannot mkdirs " + path, e);
} finally {
}
}
registerNamespaceSafely(session.getWorkspace()
.getNamespaceRegistry(), prefix, uri);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot find namespace registry", e);
+ throw new ArgeoJcrException("Cannot find namespace registry", e);
}
}
if (pref.equals(prefix)) {
String registeredUri = nr.getURI(pref);
if (!registeredUri.equals(uri))
- throw new ArgeoException("Prefix " + pref
+ throw new ArgeoJcrException("Prefix " + pref
+ " already registered for URI "
+ registeredUri
+ " which is different from provided URI "
}
nr.registerNamespace(prefix, uri);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot register namespace " + uri
+ throw new ArgeoJcrException("Cannot register namespace " + uri
+ " under prefix " + prefix, e);
}
}
}
return buf.toString();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot write summary of " + acl, e);
+ throw new ArgeoJcrException("Cannot write summary of " + acl, e);
}
}
copy(fromChild, toChild);
}
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot copy " + fromNode + " to "
+ throw new ArgeoJcrException("Cannot copy " + fromNode + " to "
+ toNode, e);
}
}
}
return true;
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot check all properties equals of "
+ throw new ArgeoJcrException("Cannot check all properties equals of "
+ reference + " and " + observed, e);
}
}
}
}
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot diff " + reference + " and "
+ throw new ArgeoJcrException("Cannot diff " + reference + " and "
+ observed, e);
}
}
}
}
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot diff " + reference + " and "
+ throw new ArgeoJcrException("Cannot diff " + reference + " and "
+ observed, e);
}
return diffs;
IOUtils.copy(in, out);
return out.toByteArray();
} catch (Exception e) {
- throw new ArgeoException("Cannot read binary " + property
+ throw new ArgeoJcrException("Cannot read binary " + property
+ " as bytes", e);
} finally {
IOUtils.closeQuietly(out);
binary = node.getSession().getValueFactory().createBinary(in);
node.setProperty(property, binary);
} catch (Exception e) {
- throw new ArgeoException("Cannot read binary " + property
+ throw new ArgeoJcrException("Cannot read binary " + property
+ " as bytes", e);
} finally {
IOUtils.closeQuietly(in);
*/
public static String firstCharsToPath(String str, Integer nbrOfChars) {
if (str.length() < nbrOfChars)
- throw new ArgeoException("String " + str
+ throw new ArgeoJcrException("String " + str
+ " length must be greater or equal than " + nbrOfChars);
StringBuffer path = new StringBuffer("");
StringBuffer curr = new StringBuffer("");
nodeType == null ? null : new String[] { nodeType },
true);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot add JCR listener " + listener
+ throw new ArgeoJcrException("Cannot add JCR listener " + listener
+ " to session " + session, e);
}
}
node.setProperty(Property.JCR_LAST_MODIFIED_BY, node.getSession()
.getUserID());
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot update last modified on " + node,
+ throw new ArgeoJcrException("Cannot update last modified on " + node,
e);
}
}
public static void updateLastModifiedAndParents(Node node, String untilPath) {
try {
if (untilPath != null && !node.getPath().startsWith(untilPath))
- throw new ArgeoException(node + " is not under " + untilPath);
+ throw new ArgeoJcrException(node + " is not under " + untilPath);
updateLastModified(node);
if (untilPath == null) {
if (!node.getPath().equals("/"))
updateLastModifiedAndParents(node.getParent(), untilPath);
}
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot update lastModified from " + node
+ throw new ArgeoJcrException("Cannot update lastModified from " + node
+ " until " + untilPath, e);
}
}
if (prop.getDefinition().isMultiple())
sbuf.append("*");
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new ArgeoJcrException(
"unexpected error while getting property definition as String",
re);
}
curNodeSize += getNodeApproxSize(ni.nextNode());
return curNodeSize;
} catch (RepositoryException re) {
- throw new ArgeoException(
+ throw new ArgeoJcrException(
"Unexpected error while recursively determining node size.",
re);
}
if (acl != null)
return acl;
else
- throw new ArgeoException("ACL not found at " + path);
+ throw new ArgeoJcrException("ACL not found at " + path);
}
/** Clear authorizations for a user at this path */
* files
* @return how many files were copied
*/
+ @SuppressWarnings("deprecation")
public static Long copyFiles(Node fromNode, Node toNode, Boolean recursive,
ArgeoMonitor monitor) {
long count = 0l;
NodeIterator fromChildren = fromNode.getNodes();
while (fromChildren.hasNext()) {
if (monitor != null && monitor.isCanceled())
- throw new ArgeoException(
+ throw new ArgeoJcrException(
"Copy cancelled before it was completed");
Node fromChild = fromChildren.nextNode();
if (toNode.hasNode(fileName)) {
toChildFolder = toNode.getNode(fileName);
if (!toChildFolder.isNodeType(NodeType.NT_FOLDER))
- throw new ArgeoException(toChildFolder
+ throw new ArgeoJcrException(toChildFolder
+ " is not of type nt:folder");
} else {
toChildFolder = toNode.addNode(fileName,
}
return count;
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot copy files between " + fromNode
+ throw new ArgeoJcrException("Cannot copy files between " + fromNode
+ " and " + toNode);
} finally {
// in case there was an exception
localCount = localCount + 1;
}
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot count all children of " + node);
+ throw new ArgeoJcrException("Cannot count all children of " + node);
}
return localCount;
}
in = new FileInputStream(file);
return copyStreamAsFile(folderNode, file.getName(), in);
} catch (IOException e) {
- throw new ArgeoException("Cannot copy file " + file + " under "
+ throw new ArgeoJcrException("Cannot copy file " + file + " under "
+ folderNode, e);
} finally {
IOUtils.closeQuietly(in);
in = new ByteArrayInputStream(bytes);
return copyStreamAsFile(folderNode, fileName, in);
} catch (Exception e) {
- throw new ArgeoException("Cannot copy file " + fileName + " under "
+ throw new ArgeoJcrException("Cannot copy file " + fileName + " under "
+ folderNode, e);
} finally {
IOUtils.closeQuietly(in);
if (folderNode.hasNode(fileName)) {
fileNode = folderNode.getNode(fileName);
if (!fileNode.isNodeType(NodeType.NT_FILE))
- throw new ArgeoException(fileNode
+ throw new ArgeoJcrException(fileNode
+ " is not of type nt:file");
// we assume that the content node is already there
contentNode = fileNode.getNode(Node.JCR_CONTENT);
contentNode.setProperty(Property.JCR_DATA, binary);
return fileNode;
} catch (Exception e) {
- throw new ArgeoException("Cannot create file node " + fileName
+ throw new ArgeoJcrException("Cannot create file node " + fileName
+ " under " + folderNode, e);
} finally {
closeQuietly(binary);
in = data.getStream();
return DigestUtils.digest(algorithm, in);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot checksum file " + fileNode, e);
+ throw new ArgeoJcrException("Cannot checksum file " + fileNode, e);
} finally {
IOUtils.closeQuietly(in);
closeQuietly(data);
import javax.jcr.Value;
-import org.argeo.ArgeoException;
-
/** The result of the comparison of two JCR properties. */
public class PropertyDiff {
public final static Integer MODIFIED = 0;
if (type == MODIFIED) {
if (referenceValue == null || newValue == null)
- throw new ArgeoException(
+ throw new ArgeoJcrException(
"Reference and new values must be specified.");
} else if (type == ADDED) {
if (referenceValue != null || newValue == null)
- throw new ArgeoException(
+ throw new ArgeoJcrException(
"New value and only it must be specified.");
} else if (type == REMOVED) {
if (referenceValue == null || newValue != null)
- throw new ArgeoException(
+ throw new ArgeoJcrException(
"Reference value and only it must be specified.");
} else {
- throw new ArgeoException("Unkown diff type " + type);
+ throw new ArgeoJcrException("Unkown diff type " + type);
}
if (relPath == null)
- throw new ArgeoException("Relative path must be specified");
+ throw new ArgeoJcrException("Relative path must be specified");
this.type = type;
this.relPath = relPath;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
/** Proxy JCR sessions and attach them to calling threads. */
@Deprecated
/** Logs in to the repository using various strategies. */
protected synchronized Session login() {
if (!isActive())
- throw new ArgeoException("Thread bound session factory inactive");
+ throw new ArgeoJcrException("Thread bound session factory inactive");
// discard session previously attached to this thread
Thread thread = Thread.currentThread();
// invalid credentials, go to the next step
} catch (RepositoryException e1) {
// other kind of exception, fail
- throw new ArgeoException("Cannot log in to repository", e1);
+ throw new ArgeoJcrException("Cannot log in to repository", e1);
}
// log using default username / password (useful for testing purposes)
defaultPassword.toCharArray());
newSession = repository().login(sc, workspace);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot log in to repository", e);
+ throw new ArgeoJcrException("Cannot log in to repository", e);
}
session.set(newSession);
if (it.hasNext())
return it.next();
}
- throw new ArgeoException("No repository injected");
+ throw new ArgeoJcrException("No repository injected");
}
// /** Useful for declarative registration of OSGi services (blueprint) */
import javax.jcr.query.qom.Selector;
import javax.jcr.query.qom.StaticOperand;
-import org.argeo.ArgeoException;
-
/**
* Utilities related to the user home and properties based on Argeo JCR model.
* Do not use anymore. Does not fit with current security model
Query query = qomf.createQuery(userHomeSel, constraint, null, null);
return JcrUtils.querySingleNode(query);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot find home for user " + username, e);
+ throw new ArgeoJcrException("Cannot find home for user " + username, e);
}
}
Query query = qomf.createQuery(userHomeSel, constraint, null, null);
return JcrUtils.querySingleNode(query);
} catch (RepositoryException e) {
- throw new ArgeoException(
+ throw new ArgeoJcrException(
"Cannot find profile for user " + username, e);
}
}
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.jcr.ArgeoJcrException;
import org.argeo.jcr.JcrUtils;
/** Base class for URL based proxys. */
jcrAdminSession.save();
} catch (Exception e) {
JcrUtils.discardQuietly(jcrAdminSession);
- throw new ArgeoException("Cannot initialize Maven proxy", e);
+ throw new ArgeoJcrException("Cannot initialize Maven proxy", e);
}
}
nodeClient = clientSession.getNode(path);
return nodeClient;
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot proxy " + path, e);
+ throw new ArgeoJcrException("Cannot proxy " + path, e);
} finally {
if (nodeClient == null)
JcrUtils.logoutQuietly(clientSession);
return node;
} catch (RepositoryException e) {
JcrUtils.discardQuietly(jcrAdminSession);
- throw new ArgeoException("Cannot retrieve and save " + path, e);
+ throw new ArgeoJcrException("Cannot retrieve and save " + path, e);
} finally {
notifyAll();
}
String path) throws RepositoryException {
Node node = null;
if (session.itemExists(path)) {
- // throw new ArgeoException("Node " + path + " already exists");
+ // throw new ArgeoJcrException("Node " + path + " already exists");
}
InputStream in = null;
try {
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.jcr.ArgeoJcrException;
import org.argeo.jcr.JcrUtils;
/** Wraps a proxy via HTTP */
in = binary.getStream();
IOUtils.copy(in, response.getOutputStream());
} catch (Exception e) {
- throw new ArgeoException("Cannot download " + node, e);
+ throw new ArgeoJcrException("Cannot download " + node, e);
} finally {
IOUtils.closeQuietly(in);
JcrUtils.closeQuietly(binary);
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.Privilege;
-import org.argeo.ArgeoException;
+import org.argeo.jcr.ArgeoJcrException;
import org.argeo.jcr.JcrUtils;
import org.argeo.util.security.SimplePrincipal;
}
} catch (Exception e) {
JcrUtils.discardQuietly(session);
- throw new ArgeoException(
+ throw new ArgeoJcrException(
"Cannot set authorizations " + principalPrivileges
+ " on workspace " + currentWorkspace, e);
} finally {
initAuthorizations(session);
} catch (Exception e) {
JcrUtils.discardQuietly(session);
- throw new ArgeoException("Cannot set authorizations "
+ throw new ArgeoJcrException("Cannot set authorizations "
+ principalPrivileges + " on repository " + repository, e);
} finally {
JcrUtils.logoutQuietly(session);
String path = null;
int slashIndex = privileges.indexOf('/');
if (slashIndex == 0) {
- throw new ArgeoException("Privilege " + privileges
+ throw new ArgeoJcrException("Privilege " + privileges
+ " badly formatted it starts with /");
} else if (slashIndex > 0) {
path = privileges.substring(slashIndex);
// + session.getWorkspace().getName() + "'");
// }
// } else {
- // throw new ArgeoException("Don't know how to apply privileges "
+ // throw new ArgeoJcrException("Don't know how to apply privileges "
// + privs + " to " + principal + " on " + path
// + " from workspace '" + session.getWorkspace().getName()
// + "'");
import javax.jcr.Session;
import org.apache.commons.io.IOUtils;
-import org.argeo.ArgeoException;
+import org.argeo.jcr.ArgeoJcrException;
import org.argeo.jcr.ArgeoNames;
import org.argeo.jcr.ArgeoTypes;
import org.argeo.jcr.JcrUtils;
Node userHome = UserJcrUtils.getUserHome(session);
return userHome.hasNode(ARGEO_KEYRING);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot check whether keyring is setup", e);
+ throw new ArgeoJcrException("Cannot check whether keyring is setup", e);
}
}
try {
Node userHome = UserJcrUtils.getUserHome(session);
if (userHome.hasNode(ARGEO_KEYRING))
- throw new ArgeoException("Keyring already setup");
+ throw new ArgeoJcrException("Keyring already setup");
Node keyring = userHome.addNode(ARGEO_KEYRING);
keyring.addMixin(ArgeoTypes.ARGEO_PBE_SPEC);
secreteKeyEncryption);
keyring.setProperty(ARGEO_CIPHER, cipherName);
+ //keyring.getSession().save();
+
// encrypted password hash
// IOUtils.closeQuietly(in);
// JcrUtils.closeQuietly(binary);
notYetSavedKeyring.set(keyring);
} catch (Exception e) {
- throw new ArgeoException("Cannot setup keyring", e);
+ throw new ArgeoJcrException("Cannot setup keyring", e);
} finally {
JcrUtils.closeQuietly(binary);
IOUtils.closeQuietly(in);
else if (notYetSavedKeyring.get() != null)
keyring = notYetSavedKeyring.get();
else
- throw new ArgeoException("Keyring not setup");
+ throw new ArgeoJcrException("Keyring not setup");
pbeCallback.set(keyring.getProperty(ARGEO_SECRET_KEY_FACTORY)
.getString(), JcrUtils.getBinaryAsBytes(keyring
if (notYetSavedKeyring.get() != null)
notYetSavedKeyring.remove();
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot handle key spec callback", e);
+ throw new ArgeoJcrException("Cannot handle key spec callback", e);
}
}
if (!session.nodeExists(path)) {
String parentPath = JcrUtils.parentPath(path);
if (!session.nodeExists(parentPath))
- throw new ArgeoException("No parent node of " + path);
+ throw new ArgeoJcrException("No parent node of " + path);
Node parentNode = session.getNode(parentPath);
node = parentNode.addNode(JcrUtils.nodeNameFromPath(path));
} else {
node.setProperty(Property.JCR_DATA, binary);
session.save();
} catch (Exception e) {
- throw new ArgeoException("Cannot encrypt", e);
+ throw new ArgeoJcrException("Cannot encrypt", e);
} finally {
IOUtils.closeQuietly(unencrypted);
IOUtils.closeQuietly(in);
return new CipherInputStream(encrypted, cipher);
}
} catch (Exception e) {
- throw new ArgeoException("Cannot decrypt", e);
+ throw new ArgeoJcrException("Cannot decrypt", e);
} finally {
IOUtils.closeQuietly(encrypted);
IOUtils.closeQuietly(reader);
try {
Node userHome = UserJcrUtils.getUserHome(session);
if (!userHome.hasNode(ARGEO_KEYRING))
- throw new ArgeoException("Keyring not setup");
+ throw new ArgeoJcrException("Keyring not setup");
Node keyring = userHome.getNode(ARGEO_KEYRING);
Cipher cipher = Cipher.getInstance(keyring
.getProperty(ARGEO_CIPHER).getString(),
getSecurityProvider());
return cipher;
} catch (Exception e) {
- throw new ArgeoException("Cannot get cipher", e);
+ throw new ArgeoJcrException("Cannot get cipher", e);
}
}
import javax.jcr.RepositoryException;
import org.apache.commons.io.IOUtils;
-import org.argeo.ArgeoException;
+import org.argeo.jcr.ArgeoJcrException;
import org.argeo.jcr.ArgeoTypes;
import org.argeo.util.CsvParser;
import org.argeo.util.tabular.ArrayTabularRow;
thread.start();
}
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot read table " + tableNode, e);
+ throw new ArgeoJcrException("Cannot read table " + tableNode, e);
}
}
import javax.jcr.RepositoryException;
import org.apache.commons.io.IOUtils;
-import org.argeo.ArgeoException;
+import org.argeo.jcr.ArgeoJcrException;
import org.argeo.jcr.ArgeoTypes;
import org.argeo.jcr.JcrUtils;
import org.argeo.util.CsvWriter;
csvWriter = new CsvWriter(out);
}
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot create table node " + tableNode, e);
+ throw new ArgeoJcrException("Cannot create table node " + tableNode, e);
}
}
.createBinary(in);
contentNode.setProperty(Property.JCR_DATA, binary);
} catch (RepositoryException e) {
- throw new ArgeoException("Cannot store data in " + contentNode, e);
+ throw new ArgeoJcrException("Cannot store data in " + contentNode, e);
} finally {
IOUtils.closeQuietly(in);
JcrUtils.closeQuietly(binary);
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
-import junit.framework.TestCase;
-
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
+import org.argeo.jcr.ArgeoJcrException;
+
+import junit.framework.TestCase;
public abstract class AbstractJcrTestCase extends TestCase {
private final static Log log = LogFactory.getLog(AbstractJcrTestCase.class);
lc = new LoginContext(getLoginContext());
lc.login();
} catch (LoginException e) {
- throw new ArgeoException("JAAS login failed", e);
+ throw new ArgeoJcrException("JAAS login failed", e);
}
session = Subject.doAs(lc.getSubject(),
new PrivilegedAction<Session>() {
return getRepository().login(
new SimpleCredentials("demo", "demo".toCharArray()));
} catch (Exception e) {
- throw new ArgeoException("Cannot login to repository", e);
+ throw new ArgeoJcrException("Cannot login to repository", e);
}
}
this.repository = repository;
}
- // public void logout() {
- // if (session != null && session.isLive())
- // JcrUtils.logoutQuietly(session);
- // }
- //
- // protected static TestSuite defaultTestSuite(Class<? extends TestCase>
- // clss) {
- // String testSuiteClassName =
- // "org.argeo.jackrabbit.unit.JackrabbitTestSuite";
- // try {
- // Class<?> testSuiteClass = AbstractJcrTestCase.class
- // .getClassLoader().loadClass(testSuiteClassName);
- // if (clss == null) {
- // return (TestSuite) testSuiteClass.newInstance();
- // } else {
- // return (TestSuite) testSuiteClass.getConstructor(Class.class)
- // .newInstance(clss);
- // }
- // } catch (Exception e) {
- // throw new ArgeoException("Cannot find default test suite "
- // + testSuiteClassName, e);
- // }
- // }
-
protected File getHomeDir() {
File homeDir = new File(System.getProperty("java.io.tmpdir"),
AbstractJcrTestCase.class.getSimpleName() + "-"
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.StreamUtils;
+import org.argeo.util.internal.StreamUtils;
import org.argeo.util.security.PasswordBasedEncryption;
public class PasswordBasedEncryptionTest extends TestCase {
*/
package org.argeo;
-/** Argeo Commons specific exception. */
+import javax.naming.OperationNotSupportedException;
+
+/**
+ * Argeo Commons specific exception.
+ *
+ * @deprecated Use project specific exceptions or standard ones like
+ * {@link OperationNotSupportedException},
+ * {@link IllegalArgumentException}, etc.
+ */
+@Deprecated
public class ArgeoException extends RuntimeException {
private static final long serialVersionUID = 1L;
super(message, e);
}
- /**
- * Chain the messages of all causes (one per line, <b>starts with a line
- * return</b>) without all the stack
- */
- public static String chainCausesMessages(Throwable t) {
- StringBuffer buf = new StringBuffer();
- chainCauseMessage(buf, t);
- return buf.toString();
- }
-
- /** Recursive chaining of messages */
- private static void chainCauseMessage(StringBuffer buf, Throwable t) {
- buf.append('\n').append(' ').append(t.getClass().getCanonicalName())
- .append(": ").append(t.getMessage());
- if (t.getCause() != null)
- chainCauseMessage(buf, t.getCause());
- }
}
/**
* Simple monitor abstraction. Inspired by Eclipse IProgressMOnitor, but without
* dependency to it.
+ *
+ * @deprecated use org.argeo.jcr.JcrMonitor instead
*/
+@Deprecated
public interface ArgeoMonitor {
/**
* Constant indicating an unknown amount of work.
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.io.Writer;
-
-/** Utilities to be used when APache COmmons IO is not available. */
-public class StreamUtils {
- private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
-
- /*
- * APACHE COMMONS IO (inspired)
- */
-
- /** @return the number of bytes */
- public static Long copy(InputStream in, OutputStream out)
- throws IOException {
- Long count = 0l;
- byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
- while (true) {
- int length = in.read(buf);
- if (length < 0)
- break;
- out.write(buf, 0, length);
- count = count + length;
- }
- return count;
- }
-
- /** @return the number of chars */
- public static Long copy(Reader in, Writer out) throws IOException {
- Long count = 0l;
- char[] buf = new char[DEFAULT_BUFFER_SIZE];
- while (true) {
- int length = in.read(buf);
- if (length < 0)
- break;
- out.write(buf, 0, length);
- count = count + length;
- }
- return count;
- }
-
- public static void closeQuietly(InputStream in) {
- if (in != null)
- try {
- in.close();
- } catch (Exception e) {
- //
- }
- }
-
- public static void closeQuietly(OutputStream out) {
- if (out != null)
- try {
- out.close();
- } catch (Exception e) {
- //
- }
- }
-
- public static void closeQuietly(Reader in) {
- if (in != null)
- try {
- in.close();
- } catch (Exception e) {
- //
- }
- }
-
- public static void closeQuietly(Writer out) {
- if (out != null)
- try {
- out.close();
- } catch (Exception e) {
- //
- }
- }
-
- /*
- * APACHE COMMONS CODEC (forked)
- */
- /**
- * Used to build output as Hex
- */
- private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5',
- '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
-
- /**
- * Used to build output as Hex
- */
- private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5',
- '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
-
- /**
- * Converts an array of bytes into a String representing the hexadecimal
- * values of each byte in order. The returned String will be double the
- * length of the passed array, as it takes two characters to represent any
- * given byte.
- *
- * @param data
- * a byte[] to convert to Hex characters
- * @return A String containing hexadecimal characters
- * @since 1.4
- */
- public static String encodeHexString(byte[] data) {
- return new String(encodeHex(data));
- }
-
- /**
- * Converts an array of bytes into an array of characters representing the
- * hexadecimal values of each byte in order. The returned array will be
- * double the length of the passed array, as it takes two characters to
- * represent any given byte.
- *
- * @param data
- * a byte[] to convert to Hex characters
- * @return A char[] containing hexadecimal characters
- */
- public static char[] encodeHex(byte[] data) {
- return encodeHex(data, true);
- }
-
- /**
- * Converts an array of bytes into an array of characters representing the
- * hexadecimal values of each byte in order. The returned array will be
- * double the length of the passed array, as it takes two characters to
- * represent any given byte.
- *
- * @param data
- * a byte[] to convert to Hex characters
- * @param toLowerCase
- * <code>true</code> converts to lowercase, <code>false</code> to
- * uppercase
- * @return A char[] containing hexadecimal characters
- * @since 1.4
- */
- public static char[] encodeHex(byte[] data, boolean toLowerCase) {
- return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
- }
-
- /**
- * Converts an array of bytes into an array of characters representing the
- * hexadecimal values of each byte in order. The returned array will be
- * double the length of the passed array, as it takes two characters to
- * represent any given byte.
- *
- * @param data
- * a byte[] to convert to Hex characters
- * @param toDigits
- * the output alphabet
- * @return A char[] containing hexadecimal characters
- * @since 1.4
- */
- protected static char[] encodeHex(byte[] data, char[] toDigits) {
- int l = data.length;
- char[] out = new char[l << 1];
- // two characters form the hex value.
- for (int i = 0, j = 0; i < l; i++) {
- out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
- out[j++] = toDigits[0x0F & data[i]];
- }
- return out;
- }
-
-}
import java.util.Collections;
import java.util.List;
-import org.argeo.ArgeoException;
-import org.argeo.StreamUtils;
+import org.argeo.util.internal.StreamUtils;
+import org.argeo.util.internal.UtilsException;
/**
* Parses a CSV file interpreting the first line as a header. The
if (tokenSize == 1 && line.trim().equals(""))
continue lines;// empty line
if (headerSize != tokenSize) {
- throw new ArgeoException("Token size " + tokenSize
+ throw new UtilsException("Token size " + tokenSize
+ " is different from header size "
+ headerSize + " at line " + lineCount
+ ", line: " + line + ", header: " + header
}
processLine(lineCount, header, tokens);
}
- } catch (ArgeoException e) {
+ } catch (UtilsException e) {
throw e;
} catch (IOException e) {
- throw new ArgeoException("Cannot parse CSV file (line: "
+ throw new UtilsException("Cannot parse CSV file (line: "
+ lineCount + ")", e);
} finally {
StreamUtils.closeQuietly(reader);
import java.util.List;
import java.util.Map;
-import org.argeo.ArgeoException;
+import org.argeo.util.internal.UtilsException;
/**
* CSV parser allowing to process lines as maps whose keys are the header
protected final void processLine(Integer lineNumber, List<String> header,
List<String> tokens) {
if (header == null)
- throw new ArgeoException("Only CSV with header is supported");
+ throw new UtilsException("Only CSV with header is supported");
Map<String, String> line = new HashMap<String, String>();
for (int i = 0; i < header.size(); i++) {
String key = header.get(i);
import java.util.Iterator;
import java.util.List;
-import org.argeo.ArgeoException;
+import org.argeo.util.internal.UtilsException;
/** Write in CSV format. */
public class CsvWriter {
try {
this.out = new OutputStreamWriter(out, encoding);
} catch (UnsupportedEncodingException e) {
- throw new ArgeoException("Cannot initialize CSV writer", e);
+ throw new UtilsException("Cannot initialize CSV writer", e);
}
}
out.write('\n');
out.flush();
} catch (IOException e) {
- throw new ArgeoException("Could not write " + tokens, e);
+ throw new UtilsException("Could not write " + tokens, e);
}
}
out.write('\n');
out.flush();
} catch (IOException e) {
- throw new ArgeoException("Could not write " + tokens, e);
+ throw new UtilsException("Could not write " + tokens, e);
}
}
res.put(key.toString(), toLoad.get(key));
return res;
}
+
+ /*
+ * EXCEPTIONS
+ */
+ /**
+ * Chain the messages of all causes (one per line, <b>starts with a line
+ * return</b>) without all the stack
+ */
+ public static String chainCausesMessages(Throwable t) {
+ StringBuffer buf = new StringBuffer();
+ chainCauseMessage(buf, t);
+ return buf.toString();
+ }
+
+ /** Recursive chaining of messages */
+ private static void chainCauseMessage(StringBuffer buf, Throwable t) {
+ buf.append('\n').append(' ').append(t.getClass().getCanonicalName())
+ .append(": ").append(t.getMessage());
+ if (t.getCause() != null)
+ chainCauseMessage(buf, t.getCause());
+ }
/** Singleton constructor. */
private LangUtils() {
import java.text.ParseException;
import java.util.Locale;
-import org.argeo.ArgeoException;
+import org.argeo.util.internal.UtilsException;
public class Throughput {
private final static NumberFormat usNumberFormat = NumberFormat
else if (unit.equals(Unit.d))
value = ((double) count * 24d * 60d * 60d * 1000d) / periodMs;
else
- throw new ArgeoException("Unsupported unit " + unit);
+ throw new UtilsException("Unsupported unit " + unit);
this.unit = unit;
}
public Throughput(String def) {
int index = def.indexOf('/');
if (def.length() < 3 || index <= 0 || index != def.length() - 2)
- throw new ArgeoException(def + " no a proper throughput definition"
+ throw new UtilsException(def + " no a proper throughput definition"
+ " (should be <value>/<unit>, e.g. 3.54/s or 1500/h");
String valueStr = def.substring(0, index);
String unitStr = def.substring(index + 1);
try {
this.value = usNumberFormat.parse(valueStr).doubleValue();
} catch (ParseException e) {
- throw new ArgeoException("Cannot parse " + valueStr
+ throw new UtilsException("Cannot parse " + valueStr
+ " as a number.", e);
}
this.unit = Unit.valueOf(unitStr);
else if (unit.equals(Unit.d))
return Math.round((24d * 60d * 60d * 1000d) / value);
else
- throw new ArgeoException("Unsupported unit " + unit);
+ throw new UtilsException("Unsupported unit " + unit);
}
@Override
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.util.internal;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.io.Writer;
+
+/** Utilities to be used when APache COmmons IO is not available. */
+public class StreamUtils {
+ private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
+
+ /*
+ * APACHE COMMONS IO (inspired)
+ */
+
+ /** @return the number of bytes */
+ public static Long copy(InputStream in, OutputStream out)
+ throws IOException {
+ Long count = 0l;
+ byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
+ while (true) {
+ int length = in.read(buf);
+ if (length < 0)
+ break;
+ out.write(buf, 0, length);
+ count = count + length;
+ }
+ return count;
+ }
+
+ /** @return the number of chars */
+ public static Long copy(Reader in, Writer out) throws IOException {
+ Long count = 0l;
+ char[] buf = new char[DEFAULT_BUFFER_SIZE];
+ while (true) {
+ int length = in.read(buf);
+ if (length < 0)
+ break;
+ out.write(buf, 0, length);
+ count = count + length;
+ }
+ return count;
+ }
+
+ public static void closeQuietly(InputStream in) {
+ if (in != null)
+ try {
+ in.close();
+ } catch (Exception e) {
+ //
+ }
+ }
+
+ public static void closeQuietly(OutputStream out) {
+ if (out != null)
+ try {
+ out.close();
+ } catch (Exception e) {
+ //
+ }
+ }
+
+ public static void closeQuietly(Reader in) {
+ if (in != null)
+ try {
+ in.close();
+ } catch (Exception e) {
+ //
+ }
+ }
+
+ public static void closeQuietly(Writer out) {
+ if (out != null)
+ try {
+ out.close();
+ } catch (Exception e) {
+ //
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.util.internal;
+
+/** Utils specific exception. */
+public class UtilsException extends RuntimeException {
+ private static final long serialVersionUID = 1L;
+
+ /** Creates an exception with a message. */
+ public UtilsException(String message) {
+ super(message);
+ }
+
+ /** Creates an exception with a message and a root cause. */
+ public UtilsException(String message, Throwable e) {
+ super(message, e);
+ }
+
+}
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
-import org.argeo.ArgeoException;
-import org.argeo.StreamUtils;
+import org.argeo.util.internal.UtilsException;
+import org.argeo.util.internal.StreamUtils;
/** username / password based keyring. TODO internationalize */
public abstract class AbstractKeyring implements Keyring, CryptoKeyring {
.iterator();
return iterator.next();
} catch (LoginException e) {
- throw new ArgeoException("Keyring login failed", e);
+ throw new UtilsException("Keyring login failed", e);
}
} else {
SecretKey secretKey = iterator.next();
if (iterator.hasNext())
- throw new ArgeoException(
+ throw new UtilsException(
"More than one secret key in private credentials");
return secretKey;
}
StreamUtils.copy(reader, writer);
return writer.toCharArray();
} catch (IOException e) {
- throw new ArgeoException("Cannot decrypt to char array", e);
+ throw new UtilsException("Cannot decrypt to char array", e);
} finally {
StreamUtils.closeQuietly(reader);
StreamUtils.closeQuietly(in);
in = new ByteArrayInputStream(out.toByteArray());
set(path, in);
} catch (IOException e) {
- throw new ArgeoException("Cannot encrypt to char array", e);
+ throw new UtilsException("Cannot encrypt to char array", e);
} finally {
StreamUtils.closeQuietly(writer);
StreamUtils.closeQuietly(out);
}
return btPass;
} catch (Exception e) {
- throw new ArgeoException("Cannot hash", e);
+ throw new UtilsException("Cannot hash", e);
} finally {
StreamUtils.closeQuietly(out);
StreamUtils.closeQuietly(writer);
char[] password = passwordCb.getPassword();
return password;
} catch (Exception e) {
- throw new ArgeoException("Cannot ask for a password", e);
+ throw new UtilsException("Cannot ask for a password", e);
}
}
import java.security.MessageDigest;
import java.util.zip.Checksum;
-import org.argeo.ArgeoException;
+import org.argeo.util.internal.UtilsException;
/** Allows to fine tune how files are read. */
public class ChecksumFactory {
}
}
} catch (Exception e) {
- throw new ArgeoException("Cannot digest " + path, e);
+ throw new UtilsException("Cannot digest " + path, e);
}
}
}
return crc.getValue();
} catch (Exception e) {
- throw new ArgeoException("Cannot checksum " + path, e);
+ throw new UtilsException("Cannot checksum " + path, e);
} finally {
long duration = System.currentTimeMillis() - begin;
System.out.println(duration / 1000 + "s");
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
-import org.argeo.ArgeoException;
-import org.argeo.StreamUtils;
+import org.argeo.util.internal.UtilsException;
+import org.argeo.util.internal.StreamUtils;
/** Utilities around cryptographic digests */
public class DigestUtils {
MessageDigest digest = MessageDigest.getInstance(algorithm);
digest.update(bytes);
byte[] checksum = digest.digest();
- String res = StreamUtils.encodeHexString(checksum);
+ String res = encodeHexString(checksum);
return res;
} catch (Exception e) {
- throw new ArgeoException("Cannot digest with algorithm "
- + algorithm, e);
+ throw new UtilsException("Cannot digest with algorithm " + algorithm, e);
}
}
}
byte[] checksum = digest.digest();
- String res = StreamUtils.encodeHexString(checksum);
+ String res = encodeHexString(checksum);
return res;
} catch (Exception e) {
- throw new ArgeoException("Cannot digest with algorithm "
- + algorithm, e);
+ throw new UtilsException("Cannot digest with algorithm " + algorithm, e);
} finally {
StreamUtils.closeQuietly(in);
}
ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
return digest(algorithm, bb);
} catch (IOException e) {
- throw new ArgeoException("Cannot digest " + file
- + " with algorithm " + algorithm, e);
+ throw new UtilsException("Cannot digest " + file + " with algorithm " + algorithm, e);
} finally {
StreamUtils.closeQuietly(fis);
if (fc.isOpen())
MessageDigest digest = MessageDigest.getInstance(algorithm);
digest.update(bb);
byte[] checksum = digest.digest();
- String res = StreamUtils.encodeHexString(checksum);
+ String res = encodeHexString(checksum);
long end = System.currentTimeMillis();
if (debug)
- System.out.println((end - begin) + " ms / "
- + ((end - begin) / 1000) + " s");
+ System.out.println((end - begin) + " ms / " + ((end - begin) / 1000) + " s");
return res;
} catch (NoSuchAlgorithmException e) {
- throw new ArgeoException("Cannot digest with algorithm "
- + algorithm, e);
+ throw new UtilsException("Cannot digest with algorithm " + algorithm, e);
}
}
if (args.length > 0)
file = new File(args[0]);
else {
- System.err.println("Usage: <file> [<algorithm>]"
- + " (see http://java.sun.com/j2se/1.5.0/"
+ System.err.println("Usage: <file> [<algorithm>]" + " (see http://java.sun.com/j2se/1.5.0/"
+ "docs/guide/security/CryptoSpec.html#AppA)");
return;
}
}
}
+ final private static char[] hexArray = "0123456789ABCDEF".toCharArray();
+
+ /**
+ * From
+ * http://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to
+ * -a-hex-string-in-java
+ */
+ private static String encodeHexString(byte[] bytes) {
+ char[] hexChars = new char[bytes.length * 2];
+ for (int j = 0; j < bytes.length; j++) {
+ int v = bytes[j] & 0xFF;
+ hexChars[j * 2] = hexArray[v >>> 4];
+ hexChars[j * 2 + 1] = hexArray[v & 0x0F];
+ }
+ return new String(hexChars);
+ }
+
}
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
-import org.argeo.ArgeoException;
-import org.argeo.StreamUtils;
+import org.argeo.util.internal.UtilsException;
+import org.argeo.util.internal.StreamUtils;
/** Simple password based encryption / decryption */
public class PasswordBasedEncryption {
try {
initKeyAndCiphers(password, passwordSalt, initializationVector);
} catch (Exception e1) {
- throw new ArgeoException(
+ throw new UtilsException(
"Cannot get secret key (with restricted length)", e1);
}
} catch (Exception e) {
- throw new ArgeoException("Cannot get secret key", e);
+ throw new UtilsException("Cannot get secret key", e);
}
}
} catch (IOException e) {
throw e;
} catch (Exception e) {
- throw new ArgeoException("Cannot encrypt", e);
+ throw new UtilsException("Cannot encrypt", e);
} finally {
StreamUtils.closeQuietly(decryptedIn);
}
} catch (IOException e) {
throw e;
} catch (Exception e) {
- throw new ArgeoException("Cannot decrypt", e);
+ throw new UtilsException("Cannot decrypt", e);
} finally {
StreamUtils.closeQuietly(encryptedIn);
}
encrypt(in, out);
return out.toByteArray();
} catch (Exception e) {
- throw new ArgeoException("Cannot encrypt", e);
+ throw new UtilsException("Cannot encrypt", e);
} finally {
StreamUtils.closeQuietly(out);
}
decrypt(in, out);
return new String(out.toByteArray(), DEFAULT_CHARSET);
} catch (Exception e) {
- throw new ArgeoException("Cannot decrypt", e);
+ throw new UtilsException("Cannot decrypt", e);
} finally {
StreamUtils.closeQuietly(out);
}
import java.security.Principal;
-import org.argeo.ArgeoException;
+import org.argeo.util.internal.UtilsException;
/** Canonical implementation of a {@link Principal} */
public class SimplePrincipal implements Principal {
public SimplePrincipal(String name) {
if (name == null)
- throw new ArgeoException("Principal name cannot be null");
+ throw new UtilsException("Principal name cannot be null");
this.name = name;
}