package org.argeo.cms.ui.util;
-/** Can be applied to {@link Enum}s in order to generated (CSS) class names. */
+/** Can be applied to {@link Enum}s in order to generate (CSS) class names. */
public interface CmsStyle {
String name();
import org.apache.jackrabbit.core.config.RepositoryConfig;
import org.apache.jackrabbit.core.config.RepositoryConfigurationParser;
import org.argeo.api.NodeConstants;
-import org.argeo.cms.CmsException;
import org.argeo.cms.internal.kernel.CmsPaths;
-import org.argeo.jcr.ArgeoJcrException;
import org.xml.sax.InputSource;
/** Can interpret properties in order to create an actual JCR repository. */
final String base = "/org/argeo/cms/internal/jcr";
try (InputStream in = cl.getResourceAsStream(base + "/repository-" + type.name() + ".xml")) {
if (in == null)
- throw new ArgeoJcrException("Repository configuration not found");
+ throw new IllegalArgumentException("Repository configuration not found");
InputSource config = new InputSource(in);
Properties jackrabbitVars = getConfigurationProperties(type, properties);
// RepositoryConfig repositoryConfig = RepositoryConfig.create(config,
String clusterIdProp = props.getProperty(RepoConf.clusterId.name());
if (clusterId != null) {
if (clusterIdProp != null)
- throw new CmsException("Cluster id defined as System properties and in deploy config");
+ throw new IllegalArgumentException("Cluster id defined as System properties and in deploy config");
props.put(RepoConf.clusterId.name(), clusterId);
} else {
clusterId = clusterIdProp;
throw new IllegalArgumentException("Cannot manage repository path for host " + host);
}
} catch (URISyntaxException e) {
- throw new CmsException("Invalid repository home URI", e);
+ throw new IllegalArgumentException("Invalid repository home URI", e);
}
}
// TODO use Jackrabbit API (?)
// File homeDir = homePath.toFile();
// homeDir.mkdirs();
} catch (IOException e) {
- throw new CmsException("Cannot set up repository home " + homePath, e);
+ throw new RuntimeException("Cannot set up repository home " + homePath, e);
}
// home cannot be overridden
props.put(RepositoryConfigurationParser.REPOSITORY_HOME_VARIABLE, homePath.toString());
case localfs:
break;
default:
- throw new ArgeoJcrException("Unsupported node type " + type);
+ throw new IllegalArgumentException("Unsupported node type " + type);
}
return props;
}
import org.apache.jackrabbit.jcr2dav.Jcr2davRepositoryFactory;
import org.argeo.api.NodeConstants;
import org.argeo.cms.internal.jcr.RepoConf;
-import org.argeo.jcr.ArgeoJcrException;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
Collection<ServiceReference<Repository>> srs = bundleContext.getServiceReferences(Repository.class,
"(" + NodeConstants.CN + "=" + alias + ")");
if (srs.size() == 0)
- throw new ArgeoJcrException("No repository with alias " + alias + " found in OSGi registry");
+ throw new IllegalArgumentException("No repository with alias " + alias + " found in OSGi registry");
else if (srs.size() > 1)
- throw new ArgeoJcrException(
+ throw new IllegalArgumentException(
srs.size() + " repositories with alias " + alias + " found in OSGi registry");
return bundleContext.getService(srs.iterator().next());
} catch (InvalidSyntaxException e) {
- throw new ArgeoJcrException("Cannot find repository with alias " + alias, e);
+ throw new IllegalArgumentException("Cannot find repository with alias " + alias, e);
}
}
// JCR repository factory");
repository = getRepositoryByAlias(getAliasFromURI(uri));
} else
- throw new ArgeoJcrException("Unrecognized URI format " + uri);
+ throw new IllegalArgumentException("Unrecognized URI format " + uri);
}
// with properties " + properties);
repository = getRepositoryByAlias(alias);
} else
- throw new ArgeoJcrException("Not enough information in " + parameters);
+ throw new IllegalArgumentException("Not enough information in " + parameters);
if (repository == null)
- throw new ArgeoJcrException("Repository not found " + parameters);
+ throw new IllegalArgumentException("Repository not found " + parameters);
return repository;
}
params.put(KernelConstants.JACKRABBIT_REMOTE_DEFAULT_WORKSPACE, defaultWorkspace);
Repository repository = new Jcr2davRepositoryFactory().getRepository(params);
if (repository == null)
- throw new ArgeoJcrException("Remote Davex repository " + uri + " not found");
+ throw new IllegalArgumentException("Remote Davex repository " + uri + " not found");
log.info("Initialized remote Jackrabbit repository from uri " + uri);
return repository;
}
alias = alias.substring(0, alias.length() - 1);
return alias;
} catch (URISyntaxException e) {
- throw new ArgeoJcrException("Cannot interpret URI " + uri, e);
+ throw new IllegalArgumentException("Cannot interpret URI " + uri, e);
}
}
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
+import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
+import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.jcr.Binary;
import org.argeo.api.security.PBEKeySpecCallback;
import org.argeo.cms.ArgeoNames;
import org.argeo.cms.ArgeoTypes;
-import org.argeo.cms.CmsException;
-import org.argeo.jcr.ArgeoJcrException;
+import org.argeo.jcr.JcrException;
import org.argeo.jcr.JcrUtils;
/** JCR based implementation of a keyring */
try {
return repository.login(NodeConstants.HOME_WORKSPACE);
} catch (RepositoryException e) {
- throw new CmsException("Cannot login key ring session", e);
+ throw new JcrException("Cannot login key ring session", e);
}
}
Node userHome = NodeUtils.getUserHome(session);
return userHome.hasNode(ARGEO_KEYRING);
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot check whether keyring is setup", e);
+ throw new JcrException("Cannot check whether keyring is setup", e);
} finally {
JcrUtils.logoutQuietly(session);
}
Node userHome = NodeUtils.getUserHome(session());
Node keyring;
if (userHome.hasNode(ARGEO_KEYRING)) {
- throw new CmsException("Keyring already set up");
+ throw new IllegalArgumentException("Keyring already set up");
} else {
keyring = userHome.addNode(ARGEO_KEYRING);
}
}
try (InputStream in = new ByteArrayInputStream(salt);) {
binary = session().getValueFactory().createBinary(in);
+ keyring.setProperty(ARGEO_SALT, binary);
+ } catch (IOException e) {
+ throw new RuntimeException("Cannot set keyring salt", e);
}
- keyring.setProperty(ARGEO_SALT, binary);
Integer iterationCount = username.length() * iterationCountFactor;
keyring.setProperty(ARGEO_ITERATION_COUNT, iterationCount);
// keyring.setProperty(ARGEO_PASSWORD, binary);
// notYetSavedKeyring.set(keyring);
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot setup keyring", e);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot setup keyring", e);
} finally {
JcrUtils.closeQuietly(binary);
// IOUtils.closeQuietly(in);
// else if (notYetSavedKeyring.get() != null)
// keyring = notYetSavedKeyring.get();
else
- throw new ArgeoJcrException("Keyring not setup");
+ throw new IllegalStateException("Keyring not setup");
pbeCallback.set(keyring.getProperty(ARGEO_SECRET_KEY_FACTORY).getString(),
JcrUtils.getBinaryAsBytes(keyring.getProperty(ARGEO_SALT)),
// if (notYetSavedKeyring.get() != null)
// notYetSavedKeyring.remove();
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot handle key spec callback", e);
+ throw new JcrException("Cannot handle key spec callback", e);
} finally {
JcrUtils.logoutQuietly(session);
}
if (!session().nodeExists(path)) {
String parentPath = JcrUtils.parentPath(path);
if (!session().nodeExists(parentPath))
- throw new ArgeoJcrException("No parent node of " + path);
+ throw new IllegalStateException("No parent node of " + path);
Node parentNode = session().getNode(parentPath);
node = parentNode.addNode(JcrUtils.nodeNameFromPath(path));
} else {
// session().save();
// }
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot encrypt", e);
+ throw new JcrException("Cannot encrypt", e);
} finally {
try {
unencrypted.close();
} finally {
JcrUtils.closeQuietly(binary);
}
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot encrypt", e);
- } finally {
- try {
- unencrypted.close();
- } catch (IOException e) {
- // silent
- }
- // IOUtils.closeQuietly(unencrypted);
- // IOUtils.closeQuietly(in);
- // JcrUtils.closeQuietly(binary);
- // JcrUtils.logoutQuietly(session());
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot encrypt", e);
+ } catch (GeneralSecurityException | IOException e) {
+ throw new RuntimeException("Cannot encrypt", e);
}
}
@Override
protected synchronized InputStream decrypt(String path) {
Binary binary = null;
- // InputStream encrypted = null;
try {
session().refresh(true);
if (!session().nodeExists(path)) {
Node node = session().getNode(path);
return decrypt(secretKey, cipher, node);
}
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot decrypt", e);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot decrypt", e);
+ } catch (GeneralSecurityException | IOException e) {
+ throw new RuntimeException("Cannot decrypt", e);
} finally {
- // IOUtils.closeQuietly(encrypted);
- // IOUtils.closeQuietly(reader);
JcrUtils.closeQuietly(binary);
JcrUtils.logoutQuietly(session());
}
try {
Node userHome = NodeUtils.getUserHome(session());
if (!userHome.hasNode(ARGEO_KEYRING))
- throw new ArgeoJcrException("Keyring not setup");
+ throw new IllegalArgumentException("Keyring not setup");
Node keyring = userHome.getNode(ARGEO_KEYRING);
String cipherName = keyring.getProperty(ARGEO_CIPHER).getString();
Provider securityProvider = getSecurityProvider();
else
cipher = Cipher.getInstance(cipherName, securityProvider);
return cipher;
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot get cipher", e);
+ } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
+ throw new IllegalArgumentException("Cannot get cipher", e);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot get cipher", e);
+ } finally {
+
}
}
if (log.isDebugEnabled())
log.debug("Converted keyring encrypted value of " + node.getPath());
}
- } catch (RepositoryException | GeneralSecurityException e) {
- throw new CmsException("Cannot change JCR keyring password", e);
+ } catch (GeneralSecurityException e) {
+ throw new RuntimeException("Cannot change JCR keyring password", e);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot change JCR keyring password", e);
} finally {
JcrUtils.logoutQuietly(session);
}
import org.argeo.api.tabular.TabularRow;
import org.argeo.api.tabular.TabularRowIterator;
import org.argeo.cms.ArgeoTypes;
-import org.argeo.jcr.ArgeoJcrException;
+import org.argeo.jcr.JcrException;
import org.argeo.util.CsvParser;
/** Iterates over the rows of a {@link ArgeoTypes#ARGEO_TABLE} node. */
thread.start();
}
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot read table " + tableNode, e);
+ throw new JcrException("Cannot read table " + tableNode, e);
}
}
import org.argeo.api.tabular.TabularColumn;
import org.argeo.api.tabular.TabularWriter;
import org.argeo.cms.ArgeoTypes;
-import org.argeo.jcr.ArgeoJcrException;
+import org.argeo.jcr.JcrException;
import org.argeo.jcr.JcrUtils;
import org.argeo.util.CsvWriter;
csvWriter = new CsvWriter(out);
}
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot create table node " + tableNode, e);
+ throw new JcrException("Cannot create table node " + tableNode, e);
}
}
.createBinary(in);
contentNode.setProperty(Property.JCR_DATA, binary);
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot store data in " + contentNode, e);
+ throw new JcrException("Cannot store data in " + contentNode, e);
} finally {
IOUtils.closeQuietly(in);
JcrUtils.closeQuietly(binary);
return null;
}
- /** Typicall an OID */
+ /** Typically an OID */
default String getID() {
return getClass().getName() + "." + name();
}
package org.argeo.jackrabbit;
+import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
+import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
import org.apache.jackrabbit.commons.cnd.CndImporter;
+import org.apache.jackrabbit.commons.cnd.ParseException;
import org.apache.jackrabbit.core.config.RepositoryConfig;
-import org.argeo.jcr.ArgeoJcrException;
+import org.argeo.jcr.JcrException;
import org.argeo.jcr.JcrCallback;
import org.argeo.jcr.JcrUtils;
/** Migrate the data in a Jackrabbit repository. */
@Deprecated
-public class JackrabbitDataModelMigration implements
- Comparable<JackrabbitDataModelMigration> {
- private final static Log log = LogFactory
- .getLog(JackrabbitDataModelMigration.class);
+public class JackrabbitDataModelMigration implements Comparable<JackrabbitDataModelMigration> {
+// private final static Log log = LogFactory.getLog(JackrabbitDataModelMigration.class);
private String dataModelNodePath;
private String targetVersion;
try {
// check if already migrated
if (!session.itemExists(dataModelNodePath)) {
- log.warn("Node " + dataModelNodePath
- + " does not exist: nothing to migrate.");
+// log.warn("Node " + dataModelNodePath + " does not exist: nothing to migrate.");
return false;
}
// Node dataModelNode = session.getNode(dataModelNodePath);
reader = new InputStreamReader(migrationCnd.openStream());
CndImporter.registerNodeTypes(reader, session, true);
session.save();
- log.info("Registered migration node types from " + migrationCnd);
+// log.info("Registered migration node types from " + migrationCnd);
}
// modify data
session.save();
long duration = System.currentTimeMillis() - begin;
- log.info("Migration of data model " + dataModelNodePath + " to "
- + targetVersion + " performed in " + duration + "ms");
+// log.info("Migration of data model " + dataModelNodePath + " to " + targetVersion + " performed in "
+// + duration + "ms");
return true;
- } catch (Exception e) {
+ } catch (RepositoryException e) {
JcrUtils.discardQuietly(session);
- throw new ArgeoJcrException("Migration of data model "
- + dataModelNodePath + " to " + targetVersion + " failed.",
- e);
+ throw new JcrException(
+ "Migration of data model " + dataModelNodePath + " to " + targetVersion + " failed.", e);
+ } catch (ParseException | IOException e) {
+ JcrUtils.discardQuietly(session);
+ throw new RuntimeException(
+ "Migration of data model " + dataModelNodePath + " to " + targetVersion + " failed.", e);
} finally {
JcrUtils.logoutQuietly(session);
IOUtils.closeQuietly(reader);
try {
String customeNodeTypesPath = "/nodetypes/custom_nodetypes.xml";
// FIXME causes weird error in Eclipse
- //repositoryConfig.getFileSystem().deleteFile(customeNodeTypesPath);
- if (log.isDebugEnabled())
- log.debug("Cleared " + customeNodeTypesPath);
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot clear caches", e);
+// repositoryConfig.getFileSystem().deleteFile(customeNodeTypesPath);
+// if (log.isDebugEnabled())
+// log.debug("Cleared " + customeNodeTypesPath);
+ } catch (RuntimeException e) {
+ throw e;
}
// File customNodeTypes = new File(home.getPath()
public int compareTo(JackrabbitDataModelMigration dataModelMigration) {
// TODO make ordering smarter
if (dataModelNodePath.equals(dataModelMigration.dataModelNodePath))
- return compareVersions(targetVersion,
- dataModelMigration.targetVersion);
+ return compareVersions(targetVersion, dataModelMigration.targetVersion);
else
- return dataModelNodePath
- .compareTo(dataModelMigration.dataModelNodePath);
+ return dataModelNodePath.compareTo(dataModelMigration.dataModelNodePath);
}
@Override
import javax.jcr.Session;
import org.argeo.jackrabbit.client.ClientDavexRepositoryFactory;
-import org.argeo.jcr.ArgeoJcrException;
import org.argeo.jcr.fs.JcrFileSystem;
import org.argeo.jcr.fs.JcrFsException;
@Override
public FileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException {
if (uri.getHost() == null)
- throw new ArgeoJcrException("An host should be provided");
+ throw new IllegalArgumentException("An host should be provided");
try {
URI repoUri = new URI("http", uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null, null);
String repoKey = repoUri.toString();
throw new FileSystemAlreadyExistsException("CMS file system already exists for " + repoKey);
RepositoryFactory repositoryFactory = new ClientDavexRepositoryFactory();
return tryGetRepo(repositoryFactory, repoUri, "home");
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot open file system " + uri, e);
+ } catch (URISyntaxException e) {
+ throw new IllegalArgumentException("Cannot open file system " + uri, e);
}
}
try {
nextUri = new URI(nextRepoUriStr);
} catch (URISyntaxException e) {
- throw new ArgeoJcrException("Badly formatted URI", e);
+ throw new IllegalArgumentException("Badly formatted URI", e);
}
return tryGetRepo(repositoryFactory, nextUri, nextWorkspace);
} else {
+++ /dev/null
-package org.argeo.jcr;
-
-/** Argeo JCR specific exceptions. */
-public class ArgeoJcrException extends IllegalStateException {
- private static final long serialVersionUID = -1941940005390084331L;
-
- public ArgeoJcrException(String message, Throwable e) {
- super(message, e);
- }
-
- public ArgeoJcrException(String message) {
- super(message);
- }
-
-}
addEventListener(session().getWorkspace().getObservationManager());
if (log.isDebugEnabled())
log.debug("Registered JCR event listener on " + path);
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot register event listener", e);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot register event listener", e);
}
}
.removeEventListener(this);
if (log.isDebugEnabled())
log.debug("Unregistered JCR event listener on " + path);
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot unregister event listener", e);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot unregister event listener", e);
}
}
* exceptions. Loosely inspired by Java's <code>Files</code> singleton.
*/
public class Jcr {
-
/**
* @see Node#isNodeType(String)
* @throws IllegalStateException caused by {@link RepositoryException}
session = repository.login(workspace);
initAuthorizations(session);
}
- } catch (Exception e) {
+ } catch (RepositoryException e) {
JcrUtils.discardQuietly(session);
- throw new ArgeoJcrException(
+ throw new JcrException(
"Cannot set authorizations " + principalPrivileges + " on workspace " + currentWorkspace, e);
} finally {
JcrUtils.logoutQuietly(session);
try {
session = repository.login(workspace);
initAuthorizations(session);
- } catch (Exception e) {
+ } catch (RepositoryException e) {
JcrUtils.discardQuietly(session);
- throw new ArgeoJcrException(
+ throw new JcrException(
"Cannot set authorizations " + principalPrivileges + " on repository " + repository, e);
} finally {
JcrUtils.logoutQuietly(session);
String path = null;
int slashIndex = privileges.indexOf('/');
if (slashIndex == 0) {
- throw new ArgeoJcrException("Privilege " + privileges + " badly formatted it starts with /");
+ throw new IllegalArgumentException("Privilege " + privileges + " badly formatted it starts with /");
} else if (slashIndex > 0) {
path = privileges.substring(slashIndex);
privileges = privileges.substring(0, slashIndex);
--- /dev/null
+package org.argeo.jcr;
+
+import javax.jcr.RepositoryException;
+
+/**
+ * Wraps a {@link RepositoryException} in a {@link RuntimeException}.
+ */
+public class JcrException extends IllegalStateException {
+ private static final long serialVersionUID = -4530350094877964989L;
+
+ public JcrException(String message, RepositoryException e) {
+ super(message, e);
+ }
+
+ public JcrException(RepositoryException e) {
+ super(e);
+ }
+
+ public RepositoryException getRepositoryCause() {
+ return (RepositoryException) getCause();
+ }
+}
protected Session createWorkspaceAndLogsIn(Credentials credentials, String workspaceName)
throws RepositoryException {
if (workspaceName == null)
- throw new ArgeoJcrException("No workspace specified.");
+ throw new IllegalArgumentException("No workspace specified.");
Session session = getRepository(workspaceName).login(credentials);
session.getWorkspace().createWorkspace(workspaceName);
session.logout();
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.text.DateFormat;
import java.text.ParseException;
* Queries one single node.
*
* @return one single node or null if none was found
- * @throws ArgeoJcrException if more than one node was found
+ * @throws JcrException if more than one node was found
*/
public static Node querySingleNode(Query query) {
NodeIterator nodeIterator;
QueryResult queryResult = query.execute();
nodeIterator = queryResult.getNodes();
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot execute query " + query, e);
+ throw new JcrException("Cannot execute query " + query, e);
}
Node node;
if (nodeIterator.hasNext())
return null;
if (nodeIterator.hasNext())
- throw new ArgeoJcrException("Query returned more than one node.");
+ throw new IllegalArgumentException("Query returned more than one node.");
return node;
}
if (path.equals("/"))
return "";
if (path.charAt(0) != '/')
- throw new ArgeoJcrException("Path " + path + " must start with a '/'");
+ throw new IllegalArgumentException("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 ArgeoJcrException("Root path '/' has no parent path");
+ throw new IllegalArgumentException("Root path '/' has no parent path");
if (path.charAt(0) != '/')
- throw new ArgeoJcrException("Path " + path + " must start with a '/'");
+ throw new IllegalArgumentException("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 ArgeoJcrException("Cannot generate URL path for " + url, e);
+ throw new IllegalArgumentException("Cannot generate URL path for " + url, e);
}
}
node.setProperty(Property.JCR_HOST, u.getHost());
node.setProperty(Property.JCR_PORT, Integer.toString(u.getPort()));
node.setProperty(Property.JCR_PATH, normalizePath(u.getPath()));
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot set URL " + url + " as nt:address properties", e);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot set URL " + url + " as nt:address properties", e);
+ } catch (MalformedURLException e) {
+ throw new IllegalArgumentException("Cannot set URL " + url + " as nt:address properties", e);
}
}
(int) node.getProperty(Property.JCR_PORT).getLong(),
node.getProperty(Property.JCR_PATH).getString());
return u.toString();
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot get URL from nt:address properties of " + node, e);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot get URL from nt:address properties of " + node, e);
+ } catch (MalformedURLException e) {
+ throw new IllegalArgumentException("Cannot get URL from nt:address properties of " + node, e);
}
}
calendar.setTime(date);
return calendar;
} catch (ParseException e) {
- throw new ArgeoJcrException("Cannot parse " + value + " with date format " + dateFormat, e);
+ throw new IllegalArgumentException("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 ArgeoJcrException("Path " + path + " cannot end with '/'");
+ throw new IllegalArgumentException("Path " + path + " cannot end with '/'");
int index = path.lastIndexOf('/');
if (index < 0)
return path;
try {
return node.getName();
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot get name from " + node, e);
+ throw new JcrException("Cannot get name from " + node, e);
}
}
try {
return node.getProperty(propertyName).getString();
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot get name from " + node, e);
+ throw new JcrException("Cannot get name from " + node, e);
}
}
return null;
return node.getProperty(propertyName).getString();
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot get property " + propertyName + " of " + node, e);
+ throw new JcrException("Cannot get property " + propertyName + " of " + node, e);
}
}
try {
return node.getPath();
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot get path of " + node, e);
+ throw new JcrException("Cannot get path of " + node, e);
}
}
try {
return node.getProperty(propertyName).getBoolean();
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot get property " + propertyName + " of " + node, e);
+ throw new JcrException("Cannot get property " + propertyName + " of " + node, e);
}
}
try {
return getBinaryAsBytes(node.getProperty(propertyName));
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot get property " + propertyName + " of " + node, e);
+ throw new JcrException("Cannot get property " + propertyName + " of " + node, e);
}
}
}
return currParent;
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot mkdirs relative path " + relativePath + " from " + parentNode, e);
+ throw new JcrException("Cannot mkdirs relative path " + relativePath + " from " + parentNode, e);
}
}
public synchronized static Node mkdirsSafe(Session session, String path, String type) {
try {
if (session.hasPendingChanges())
- throw new ArgeoJcrException("Session has pending changes, save them first.");
+ throw new IllegalStateException("Session has pending changes, save them first.");
Node node = mkdirs(session, path, type);
session.save();
return node;
} catch (RepositoryException e) {
discardQuietly(session);
- throw new ArgeoJcrException("Cannot safely make directories", e);
+ throw new JcrException("Cannot safely make directories", e);
}
}
Node node = session.getNode(path);
// check type
if (type != null && !node.isNodeType(type) && !node.getPath().equals("/"))
- throw new ArgeoJcrException("Node " + node + " exists but is of type "
+ throw new IllegalArgumentException("Node " + node + " exists but is of type "
+ node.getPrimaryNodeType().getName() + " not of type " + type);
// TODO: check versioning
return node;
return currentNode;
} catch (RepositoryException e) {
discardQuietly(session);
- throw new ArgeoJcrException("Cannot mkdirs " + path, e);
+ throw new JcrException("Cannot mkdirs " + path, e);
} finally {
}
}
try {
registerNamespaceSafely(session.getWorkspace().getNamespaceRegistry(), prefix, uri);
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot find namespace registry", e);
+ throw new JcrException("Cannot find namespace registry", e);
}
}
if (pref.equals(prefix)) {
String registeredUri = nr.getURI(pref);
if (!registeredUri.equals(uri))
- throw new ArgeoJcrException("Prefix " + pref + " already registered for URI " + registeredUri
- + " which is different from provided URI " + uri);
+ throw new IllegalArgumentException("Prefix " + pref + " already registered for URI "
+ + registeredUri + " which is different from provided URI " + uri);
else
return;// skip
}
nr.registerNamespace(prefix, uri);
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot register namespace " + uri + " under prefix " + prefix, e);
+ throw new JcrException("Cannot register namespace " + uri + " under prefix " + prefix, e);
}
}
}
return buf.toString();
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot write summary of " + acl, e);
+ throw new JcrException("Cannot write summary of " + acl, e);
}
}
copy(fromChild, toChild);
}
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot copy " + fromNode + " to " + toNode, e);
+ throw new JcrException("Cannot copy " + fromNode + " to " + toNode, e);
}
}
}
return true;
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot check all properties equals of " + reference + " and " + observed, e);
+ throw new JcrException("Cannot check all properties equals of " + reference + " and " + observed, e);
}
}
}
}
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot diff " + reference + " and " + observed, e);
+ throw new JcrException("Cannot diff " + reference + " and " + observed, e);
}
}
}
}
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot diff " + reference + " and " + observed, e);
+ throw new JcrException("Cannot diff " + reference + " and " + observed, e);
}
return diffs;
}
/** Retrieve a {@link Binary} as a byte array */
public static byte[] getBinaryAsBytes(Property property) {
- // ByteArrayOutputStream out = new ByteArrayOutputStream();
- // InputStream in = null;
- // Binary binary = null;
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
Bin binary = new Bin(property);
InputStream in = binary.getStream()) {
- // binary = property.getBinary();
- // in = binary.getStream();
IOUtils.copy(in, out);
return out.toByteArray();
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot read binary " + property + " as bytes", e);
- } finally {
- // IOUtils.closeQuietly(out);
- // IOUtils.closeQuietly(in);
- // closeQuietly(binary);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot read binary " + property + " as bytes", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Cannot read binary " + property + " as bytes", e);
}
}
try (InputStream in = new ByteArrayInputStream(bytes)) {
binary = node.getSession().getValueFactory().createBinary(in);
node.setProperty(property, binary);
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot set binary " + property + " as bytes", e);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot set binary " + property + " as bytes", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Cannot set binary " + property + " as bytes", e);
} finally {
closeQuietly(binary);
}
try (InputStream in = new ByteArrayInputStream(bytes)) {
binary = prop.getSession().getValueFactory().createBinary(in);
prop.setValue(binary);
- } catch (RepositoryException | IOException e) {
- throw new ArgeoJcrException("Cannot set binary " + prop + " as bytes", e);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot set binary " + prop + " as bytes", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Cannot set binary " + prop + " as bytes", e);
} finally {
closeQuietly(binary);
}
*/
public static String firstCharsToPath(String str, Integer nbrOfChars) {
if (str.length() < nbrOfChars)
- throw new ArgeoJcrException("String " + str + " length must be greater or equal than " + nbrOfChars);
+ throw new IllegalArgumentException("String " + str + " length must be greater or equal than " + nbrOfChars);
StringBuffer path = new StringBuffer("");
StringBuffer curr = new StringBuffer("");
for (int i = 0; i < nbrOfChars; i++) {
session.getWorkspace().getObservationManager().addEventListener(listener, eventTypes, basePath, true, null,
nodeType == null ? null : new String[] { nodeType }, true);
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot add JCR listener " + listener + " to session " + session, e);
+ throw new JcrException("Cannot add JCR listener " + listener + " to session " + session, e);
}
}
node.setProperty(Property.JCR_LAST_MODIFIED, new GregorianCalendar());
node.setProperty(Property.JCR_LAST_MODIFIED_BY, node.getSession().getUserID());
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot update last modified on " + node, e);
+ throw new JcrException("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 ArgeoJcrException(node + " is not under " + untilPath);
+ throw new IllegalArgumentException(node + " is not under " + untilPath);
updateLastModified(node);
if (untilPath == null) {
if (!node.getPath().equals("/"))
updateLastModifiedAndParents(node.getParent(), untilPath);
}
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot update lastModified from " + node + " until " + untilPath, e);
+ throw new JcrException("Cannot update lastModified from " + node + " until " + untilPath, e);
}
}
if (prop.getDefinition().isMultiple())
sbuf.append("*");
} catch (RepositoryException re) {
- throw new ArgeoJcrException("unexpected error while getting property definition as String", re);
+ throw new JcrException("unexpected error while getting property definition as String", re);
}
return sbuf.toString();
}
curNodeSize += getNodeApproxSize(ni.nextNode());
return curNodeSize;
} catch (RepositoryException re) {
- throw new ArgeoJcrException("Unexpected error while recursively determining node size.", re);
+ throw new JcrException("Unexpected error while recursively determining node size.", re);
}
}
if (acl != null)
return acl;
else
- throw new ArgeoJcrException("ACL not found at " + path);
+ throw new IllegalArgumentException("ACL not found at " + path);
}
/** Clear authorizations for a user at this path */
NodeIterator fromChildren = fromNode.getNodes();
children: while (fromChildren.hasNext()) {
if (monitor != null && monitor.isCanceled())
- throw new ArgeoJcrException("Copy cancelled before it was completed");
+ throw new IllegalStateException("Copy cancelled before it was completed");
Node fromChild = fromChildren.nextNode();
String fileName = fromChild.getName();
try (Bin binary = new Bin(fromChild.getNode(Node.JCR_CONTENT).getProperty(Property.JCR_DATA));
InputStream in = binary.getStream();) {
copyStreamAsFile(toNode, fileName, in);
+ } catch (IOException e) {
+ throw new RuntimeException("Cannot copy " + fileName + " to " + toNode, e);
}
- // IOUtils.closeQuietly(in);
- // closeQuietly(binary);
// save session
toNode.getSession().save();
if (toNode.hasNode(fileName)) {
toChildFolder = toNode.getNode(fileName);
if (!toChildFolder.isNodeType(NodeType.NT_FOLDER))
- throw new ArgeoJcrException(toChildFolder + " is not of type nt:folder");
+ throw new IllegalArgumentException(toChildFolder + " is not of type nt:folder");
} else {
toChildFolder = toNode.addNode(fileName, NodeType.NT_FOLDER);
}
}
return count;
- } catch (RepositoryException | IOException e) {
- throw new ArgeoJcrException("Cannot copy files between " + fromNode + " and " + toNode);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot copy files between " + fromNode + " and " + toNode, e);
} finally {
// in case there was an exception
// IOUtils.closeQuietly(in);
localCount = localCount + 1;
}
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot count all children of " + node);
+ throw new JcrException("Cannot count all children of " + node, e);
}
return localCount;
}
* @return the created file node
*/
public static Node copyFile(Node folderNode, File file) {
- // InputStream in = null;
try (InputStream in = new FileInputStream(file)) {
- // in = new FileInputStream(file);
return copyStreamAsFile(folderNode, file.getName(), in);
} catch (IOException e) {
- throw new ArgeoJcrException("Cannot copy file " + file + " under " + folderNode, e);
- // } finally {
- // IOUtils.closeQuietly(in);
+ throw new RuntimeException("Cannot copy file " + file + " under " + folderNode, e);
}
}
try (InputStream in = new ByteArrayInputStream(bytes)) {
// in = new ByteArrayInputStream(bytes);
return copyStreamAsFile(folderNode, fileName, in);
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot copy file " + fileName + " under " + folderNode, e);
+ } catch (IOException e) {
+ throw new RuntimeException("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 ArgeoJcrException(fileNode + " is not of type nt:file");
+ throw new IllegalArgumentException(fileNode + " is not of type nt:file");
// we assume that the content node is already there
contentNode = fileNode.getNode(Node.JCR_CONTENT);
} else {
binary = contentNode.getSession().getValueFactory().createBinary(in);
contentNode.setProperty(Property.JCR_DATA, binary);
return fileNode;
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot create file node " + fileName + " under " + folderNode, e);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot create file node " + fileName + " under " + folderNode, e);
} finally {
closeQuietly(binary);
}
try (InputStream in = fileNode.getNode(Node.JCR_CONTENT).getProperty(Property.JCR_DATA).getBinary()
.getStream()) {
return digest(algorithm, in);
- } catch (RepositoryException | IOException e) {
- throw new ArgeoJcrException("Cannot checksum file " + fileNode, e);
+ } catch (IOException e) {
+ throw new RuntimeException("Cannot checksum file " + fileNode + " with algorithm " + algorithm, e);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot checksum file " + fileNode + " with algorithm " + algorithm, e);
}
}
byte[] checksum = digest.digest();
String res = encodeHexString(checksum);
return res;
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot digest with algorithm " + algorithm, e);
+ } catch (IOException e) {
+ throw new RuntimeException("Cannot digest with algorithm " + algorithm, e);
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalArgumentException("Cannot digest with algorithm " + algorithm, e);
}
}
private final Value referenceValue;
private final Value newValue;
- public PropertyDiff(Integer type, String relPath, Value referenceValue,
- Value newValue) {
+ public PropertyDiff(Integer type, String relPath, Value referenceValue, Value newValue) {
super();
if (type == MODIFIED) {
if (referenceValue == null || newValue == null)
- throw new ArgeoJcrException(
- "Reference and new values must be specified.");
+ throw new IllegalArgumentException("Reference and new values must be specified.");
} else if (type == ADDED) {
if (referenceValue != null || newValue == null)
- throw new ArgeoJcrException(
- "New value and only it must be specified.");
+ throw new IllegalArgumentException("New value and only it must be specified.");
} else if (type == REMOVED) {
if (referenceValue == null || newValue != null)
- throw new ArgeoJcrException(
- "Reference value and only it must be specified.");
+ throw new IllegalArgumentException("Reference value and only it must be specified.");
} else {
- throw new ArgeoJcrException("Unkown diff type " + type);
+ throw new IllegalArgumentException("Unkown diff type " + type);
}
if (relPath == null)
- throw new ArgeoJcrException("Relative path must be specified");
+ throw new IllegalArgumentException("Relative path must be specified");
this.type = type;
this.relPath = relPath;
/** Logs in to the repository using various strategies. */
protected synchronized Session login() {
if (!isActive())
- throw new ArgeoJcrException("Thread bound session factory inactive");
+ throw new IllegalStateException("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 ArgeoJcrException("Cannot log in to repository", e1);
+ throw new JcrException("Cannot log in to repository", e1);
}
// log using default username / password (useful for testing purposes)
SimpleCredentials sc = new SimpleCredentials(defaultUsername, defaultPassword.toCharArray());
newSession = repository().login(sc, workspace);
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot log in to repository", e);
+ throw new JcrException("Cannot log in to repository", e);
}
session.set(newSession);
}
/**
- * Called before a method is actually called, allowing to check the session
- * or re-login it (e.g. if authentication has changed). The default
- * implementation returns the session.
+ * Called before a method is actually called, allowing to check the session or
+ * re-login it (e.g. if authentication has changed). The default implementation
+ * returns the session.
*/
protected Session preCall(Session session) {
return session;
if (it.hasNext())
return it.next();
}
- throw new ArgeoJcrException("No repository injected");
+ throw new IllegalStateException("No repository injected");
}
// /** Useful for declarative registration of OSGi services (blueprint) */
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.ArgeoJcrException;
+import org.argeo.jcr.JcrException;
import org.argeo.jcr.JcrUtils;
/** Base class for URL based proxys. */
beforeInitSessionSave(jcrAdminSession);
if (jcrAdminSession.hasPendingChanges())
jcrAdminSession.save();
- } catch (Exception e) {
+ } catch (RepositoryException e) {
JcrUtils.discardQuietly(jcrAdminSession);
- throw new ArgeoJcrException("Cannot initialize Maven proxy", e);
+ throw new JcrException("Cannot initialize URL proxy", e);
}
}
nodeClient = clientSession.getNode(path);
return nodeClient;
} catch (RepositoryException e) {
- throw new ArgeoJcrException("Cannot proxy " + path, e);
+ throw new JcrException("Cannot proxy " + path, e);
} finally {
if (nodeClient == null)
JcrUtils.logoutQuietly(clientSession);
return node;
} catch (RepositoryException e) {
JcrUtils.discardQuietly(jcrAdminSession);
- throw new ArgeoJcrException("Cannot retrieve and save " + path, e);
+ throw new JcrException("Cannot retrieve and save " + path, e);
} finally {
notifyAll();
}
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.ArgeoJcrException;
+import org.argeo.jcr.JcrException;
import org.argeo.jcr.Bin;
import org.argeo.jcr.JcrUtils;
response.setContentType(contentType);
-// try {
-// binary = node.getNode(Property.JCR_CONTENT)
-// .getProperty(Property.JCR_DATA).getBinary();
-// } catch (PathNotFoundException e) {
-// log.error("Node " + node + " as no data under content");
-// throw e;
-// }
-// in = binary.getStream();
IOUtils.copy(in, response.getOutputStream());
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot download " + node, e);
-// } finally {
-// IOUtils.closeQuietly(in);
-// JcrUtils.closeQuietly(binary);
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot download " + node, e);
+ } catch (IOException e) {
+ throw new RuntimeException("Cannot download " + node, e);
}
}
import java.security.PrivilegedAction;
import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.security.auth.Subject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.ArgeoJcrException;
+import org.argeo.jcr.JcrException;
import junit.framework.TestCase;
+/** Base for unit tests with a JCR repository. */
public abstract class AbstractJcrTestCase extends TestCase {
private final static Log log = LogFactory.getLog(AbstractJcrTestCase.class);
protected abstract Repository createRepository() throws Exception;
- protected abstract void clearRepository(Repository repository)
- throws Exception;
+ protected abstract void clearRepository(Repository repository) throws Exception;
@Override
protected void setUp() throws Exception {
lc = new LoginContext(getLoginContext());
lc.login();
} catch (LoginException e) {
- throw new ArgeoJcrException("JAAS login failed", e);
+ throw new IllegalStateException("JAAS login failed", e);
}
- session = Subject.doAs(lc.getSubject(),
- new PrivilegedAction<Session>() {
+ session = Subject.doAs(lc.getSubject(), new PrivilegedAction<Session>() {
- @Override
- public Session run() {
- return login();
- }
+ @Override
+ public Session run() {
+ return login();
+ }
- });
+ });
} else
session = login();
this.session = session;
if (subject != null)
return getRepository().login();
else
- return getRepository().login(
- new SimpleCredentials("demo", "demo".toCharArray()));
- } catch (Exception e) {
- throw new ArgeoJcrException("Cannot login to repository", e);
+ return getRepository().login(new SimpleCredentials("demo", "demo".toCharArray()));
+ } catch (RepositoryException e) {
+ throw new JcrException("Cannot login to repository", e);
}
}
protected File getHomeDir() {
File homeDir = new File(System.getProperty("java.io.tmpdir"),
- AbstractJcrTestCase.class.getSimpleName() + "-"
- + System.getProperty("user.name"));
+ AbstractJcrTestCase.class.getSimpleName() + "-" + System.getProperty("user.name"));
return homeDir;
}