From: Mathieu Baudier Date: Sat, 31 Oct 2020 06:22:06 +0000 (+0100) Subject: Refactor JCR exceptions. X-Git-Tag: argeo-commons-2.1.89~47 X-Git-Url: https://git.argeo.org/?p=lgpl%2Fargeo-commons.git;a=commitdiff_plain;h=215480a865603e0090c43114541441ac1586b379 Refactor JCR exceptions. --- diff --git a/org.argeo.cms.ui/src/org/argeo/cms/ui/util/CmsStyle.java b/org.argeo.cms.ui/src/org/argeo/cms/ui/util/CmsStyle.java index daf78d477..aeff40451 100644 --- a/org.argeo.cms.ui/src/org/argeo/cms/ui/util/CmsStyle.java +++ b/org.argeo.cms.ui/src/org/argeo/cms/ui/util/CmsStyle.java @@ -1,6 +1,6 @@ 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(); diff --git a/org.argeo.cms/src/org/argeo/cms/internal/jcr/RepositoryBuilder.java b/org.argeo.cms/src/org/argeo/cms/internal/jcr/RepositoryBuilder.java index bc6a82626..d4a42fdcc 100644 --- a/org.argeo.cms/src/org/argeo/cms/internal/jcr/RepositoryBuilder.java +++ b/org.argeo.cms/src/org/argeo/cms/internal/jcr/RepositoryBuilder.java @@ -22,9 +22,7 @@ import org.apache.jackrabbit.core.cache.CacheManager; 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. */ @@ -55,7 +53,7 @@ public class RepositoryBuilder { 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, @@ -91,7 +89,7 @@ public class RepositoryBuilder { 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; @@ -119,7 +117,7 @@ public class RepositoryBuilder { 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 (?) @@ -132,7 +130,7 @@ public class RepositoryBuilder { // 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()); @@ -171,7 +169,7 @@ public class RepositoryBuilder { case localfs: break; default: - throw new ArgeoJcrException("Unsupported node type " + type); + throw new IllegalArgumentException("Unsupported node type " + type); } return props; } diff --git a/org.argeo.cms/src/org/argeo/cms/internal/kernel/NodeRepositoryFactory.java b/org.argeo.cms/src/org/argeo/cms/internal/kernel/NodeRepositoryFactory.java index a0dd38e3e..a6c722015 100644 --- a/org.argeo.cms/src/org/argeo/cms/internal/kernel/NodeRepositoryFactory.java +++ b/org.argeo.cms/src/org/argeo/cms/internal/kernel/NodeRepositoryFactory.java @@ -15,7 +15,6 @@ import org.apache.commons.logging.LogFactory; 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; @@ -37,13 +36,13 @@ class NodeRepositoryFactory implements RepositoryFactory { Collection> 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); } } @@ -85,7 +84,7 @@ class NodeRepositoryFactory implements RepositoryFactory { // JCR repository factory"); repository = getRepositoryByAlias(getAliasFromURI(uri)); } else - throw new ArgeoJcrException("Unrecognized URI format " + uri); + throw new IllegalArgumentException("Unrecognized URI format " + uri); } @@ -98,10 +97,10 @@ class NodeRepositoryFactory implements RepositoryFactory { // 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; } @@ -113,7 +112,7 @@ class NodeRepositoryFactory implements RepositoryFactory { 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; } @@ -173,7 +172,7 @@ class NodeRepositoryFactory implements RepositoryFactory { 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); } } diff --git a/org.argeo.cms/src/org/argeo/cms/security/JcrKeyring.java b/org.argeo.cms/src/org/argeo/cms/security/JcrKeyring.java index 2e9295b72..c23db194d 100644 --- a/org.argeo.cms/src/org/argeo/cms/security/JcrKeyring.java +++ b/org.argeo.cms/src/org/argeo/cms/security/JcrKeyring.java @@ -7,11 +7,13 @@ import java.io.InputStream; 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; @@ -31,8 +33,7 @@ import org.argeo.api.NodeUtils; 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 */ @@ -96,7 +97,7 @@ public class JcrKeyring extends AbstractKeyring implements ArgeoNames { 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); } } @@ -111,7 +112,7 @@ public class JcrKeyring extends AbstractKeyring implements ArgeoNames { 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); } @@ -126,7 +127,7 @@ public class JcrKeyring extends AbstractKeyring implements ArgeoNames { 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); } @@ -144,8 +145,10 @@ public class JcrKeyring extends AbstractKeyring implements ArgeoNames { } 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); @@ -168,8 +171,8 @@ public class JcrKeyring extends AbstractKeyring implements ArgeoNames { // 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); @@ -190,7 +193,7 @@ public class JcrKeyring extends AbstractKeyring implements ArgeoNames { // 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)), @@ -201,7 +204,7 @@ public class JcrKeyring extends AbstractKeyring implements ArgeoNames { // 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); } @@ -222,7 +225,7 @@ public class JcrKeyring extends AbstractKeyring implements ArgeoNames { 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 { @@ -242,7 +245,7 @@ public class JcrKeyring extends AbstractKeyring implements ArgeoNames { // session().save(); // } } catch (RepositoryException e) { - throw new ArgeoJcrException("Cannot encrypt", e); + throw new JcrException("Cannot encrypt", e); } finally { try { unencrypted.close(); @@ -273,25 +276,16 @@ public class JcrKeyring extends AbstractKeyring implements ArgeoNames { } 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)) { @@ -305,11 +299,11 @@ public class JcrKeyring extends AbstractKeyring implements ArgeoNames { 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()); } @@ -333,7 +327,7 @@ public class JcrKeyring extends AbstractKeyring implements ArgeoNames { 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(); @@ -343,8 +337,12 @@ public class JcrKeyring extends AbstractKeyring implements ArgeoNames { 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 { + } } @@ -363,8 +361,10 @@ public class JcrKeyring extends AbstractKeyring implements ArgeoNames { 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); } diff --git a/org.argeo.cms/src/org/argeo/cms/tabular/JcrTabularRowIterator.java b/org.argeo.cms/src/org/argeo/cms/tabular/JcrTabularRowIterator.java index e749765cb..23bc8e83d 100644 --- a/org.argeo.cms/src/org/argeo/cms/tabular/JcrTabularRowIterator.java +++ b/org.argeo.cms/src/org/argeo/cms/tabular/JcrTabularRowIterator.java @@ -18,7 +18,7 @@ import org.argeo.api.tabular.TabularColumn; 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. */ @@ -86,7 +86,7 @@ public class JcrTabularRowIterator implements TabularRowIterator { thread.start(); } } catch (RepositoryException e) { - throw new ArgeoJcrException("Cannot read table " + tableNode, e); + throw new JcrException("Cannot read table " + tableNode, e); } } diff --git a/org.argeo.cms/src/org/argeo/cms/tabular/JcrTabularWriter.java b/org.argeo.cms/src/org/argeo/cms/tabular/JcrTabularWriter.java index e2565bf46..29933cd75 100644 --- a/org.argeo.cms/src/org/argeo/cms/tabular/JcrTabularWriter.java +++ b/org.argeo.cms/src/org/argeo/cms/tabular/JcrTabularWriter.java @@ -15,7 +15,7 @@ import org.apache.commons.io.IOUtils; 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; @@ -55,7 +55,7 @@ public class JcrTabularWriter implements TabularWriter { 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); } } @@ -73,7 +73,7 @@ public class JcrTabularWriter implements TabularWriter { .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); diff --git a/org.argeo.enterprise/src/org/argeo/naming/SpecifiedName.java b/org.argeo.enterprise/src/org/argeo/naming/SpecifiedName.java index c59ea2c8a..28cc2f9da 100644 --- a/org.argeo.enterprise/src/org/argeo/naming/SpecifiedName.java +++ b/org.argeo.enterprise/src/org/argeo/naming/SpecifiedName.java @@ -13,7 +13,7 @@ public interface SpecifiedName { return null; } - /** Typicall an OID */ + /** Typically an OID */ default String getID() { return getClass().getName() + "." + name(); } diff --git a/org.argeo.jcr/src/org/argeo/jackrabbit/JackrabbitDataModelMigration.java b/org.argeo.jcr/src/org/argeo/jackrabbit/JackrabbitDataModelMigration.java index 2e87b347d..838446d5c 100644 --- a/org.argeo.jcr/src/org/argeo/jackrabbit/JackrabbitDataModelMigration.java +++ b/org.argeo.jcr/src/org/argeo/jackrabbit/JackrabbitDataModelMigration.java @@ -1,26 +1,25 @@ 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 { - private final static Log log = LogFactory - .getLog(JackrabbitDataModelMigration.class); +public class JackrabbitDataModelMigration implements Comparable { +// private final static Log log = LogFactory.getLog(JackrabbitDataModelMigration.class); private String dataModelNodePath; private String targetVersion; @@ -40,8 +39,7 @@ public class JackrabbitDataModelMigration implements 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); @@ -60,7 +58,7 @@ public class JackrabbitDataModelMigration implements 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 @@ -70,14 +68,17 @@ public class JackrabbitDataModelMigration implements 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); @@ -94,11 +95,11 @@ public class JackrabbitDataModelMigration implements 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() @@ -119,11 +120,9 @@ public class JackrabbitDataModelMigration implements 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 diff --git a/org.argeo.jcr/src/org/argeo/jackrabbit/fs/DavexFsProvider.java b/org.argeo.jcr/src/org/argeo/jackrabbit/fs/DavexFsProvider.java index bfd36b048..57d348be4 100644 --- a/org.argeo.jcr/src/org/argeo/jackrabbit/fs/DavexFsProvider.java +++ b/org.argeo.jcr/src/org/argeo/jackrabbit/fs/DavexFsProvider.java @@ -16,7 +16,6 @@ import javax.jcr.RepositoryFactory; 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; @@ -38,7 +37,7 @@ public class DavexFsProvider extends AbstractJackrabbitFsProvider { @Override public FileSystem newFileSystem(URI uri, Map 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(); @@ -46,8 +45,8 @@ public class DavexFsProvider extends AbstractJackrabbitFsProvider { 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); } } @@ -79,7 +78,7 @@ public class DavexFsProvider extends AbstractJackrabbitFsProvider { 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 { diff --git a/org.argeo.jcr/src/org/argeo/jcr/ArgeoJcrException.java b/org.argeo.jcr/src/org/argeo/jcr/ArgeoJcrException.java deleted file mode 100644 index 40f57ab65..000000000 --- a/org.argeo.jcr/src/org/argeo/jcr/ArgeoJcrException.java +++ /dev/null @@ -1,15 +0,0 @@ -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); - } - -} diff --git a/org.argeo.jcr/src/org/argeo/jcr/DefaultJcrListener.java b/org.argeo.jcr/src/org/argeo/jcr/DefaultJcrListener.java index 610b44562..fc6888851 100644 --- a/org.argeo.jcr/src/org/argeo/jcr/DefaultJcrListener.java +++ b/org.argeo.jcr/src/org/argeo/jcr/DefaultJcrListener.java @@ -22,8 +22,8 @@ public class DefaultJcrListener implements EventListener { 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); } } @@ -33,8 +33,8 @@ public class DefaultJcrListener implements EventListener { .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); } } diff --git a/org.argeo.jcr/src/org/argeo/jcr/Jcr.java b/org.argeo.jcr/src/org/argeo/jcr/Jcr.java index 3ee235f62..fb6f61013 100644 --- a/org.argeo.jcr/src/org/argeo/jcr/Jcr.java +++ b/org.argeo.jcr/src/org/argeo/jcr/Jcr.java @@ -36,7 +36,6 @@ import javax.jcr.version.VersionManager; * exceptions. Loosely inspired by Java's Files singleton. */ public class Jcr { - /** * @see Node#isNodeType(String) * @throws IllegalStateException caused by {@link RepositoryException} diff --git a/org.argeo.jcr/src/org/argeo/jcr/JcrAuthorizations.java b/org.argeo.jcr/src/org/argeo/jcr/JcrAuthorizations.java index 381a051fb..351929f8d 100644 --- a/org.argeo.jcr/src/org/argeo/jcr/JcrAuthorizations.java +++ b/org.argeo.jcr/src/org/argeo/jcr/JcrAuthorizations.java @@ -50,9 +50,9 @@ public class JcrAuthorizations implements Runnable { 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); @@ -64,9 +64,9 @@ public class JcrAuthorizations implements Runnable { 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); @@ -86,7 +86,7 @@ public class JcrAuthorizations implements Runnable { 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); diff --git a/org.argeo.jcr/src/org/argeo/jcr/JcrException.java b/org.argeo.jcr/src/org/argeo/jcr/JcrException.java new file mode 100644 index 000000000..c77874376 --- /dev/null +++ b/org.argeo.jcr/src/org/argeo/jcr/JcrException.java @@ -0,0 +1,22 @@ +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(); + } +} diff --git a/org.argeo.jcr/src/org/argeo/jcr/JcrRepositoryWrapper.java b/org.argeo.jcr/src/org/argeo/jcr/JcrRepositoryWrapper.java index 8798c42ac..3228eee74 100644 --- a/org.argeo.jcr/src/org/argeo/jcr/JcrRepositoryWrapper.java +++ b/org.argeo.jcr/src/org/argeo/jcr/JcrRepositoryWrapper.java @@ -136,7 +136,7 @@ public abstract class JcrRepositoryWrapper implements Repository { 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(); diff --git a/org.argeo.jcr/src/org/argeo/jcr/JcrUtils.java b/org.argeo.jcr/src/org/argeo/jcr/JcrUtils.java index eb6be528b..857bd60b0 100644 --- a/org.argeo.jcr/src/org/argeo/jcr/JcrUtils.java +++ b/org.argeo.jcr/src/org/argeo/jcr/JcrUtils.java @@ -9,6 +9,7 @@ import java.io.InputStream; 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; @@ -72,7 +73,7 @@ public class JcrUtils { * 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; @@ -80,7 +81,7 @@ public class JcrUtils { 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()) @@ -89,7 +90,7 @@ public class JcrUtils { 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; } @@ -98,7 +99,7 @@ public class JcrUtils { 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); @@ -110,9 +111,9 @@ public class JcrUtils { /** 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); @@ -141,7 +142,7 @@ public class JcrUtils { 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); } } @@ -153,8 +154,10 @@ public class JcrUtils { 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); } } @@ -166,8 +169,10 @@ public class JcrUtils { (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); } } @@ -264,7 +269,7 @@ public class JcrUtils { 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); } } @@ -272,7 +277,7 @@ public class JcrUtils { /** 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; @@ -287,7 +292,7 @@ public class JcrUtils { 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); } } @@ -299,7 +304,7 @@ public class JcrUtils { 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); } } @@ -342,7 +347,7 @@ public class JcrUtils { 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); } } @@ -351,7 +356,7 @@ public class JcrUtils { 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); } } @@ -360,7 +365,7 @@ public class JcrUtils { 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); } } @@ -369,7 +374,7 @@ public class JcrUtils { 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); } } @@ -416,7 +421,7 @@ public class JcrUtils { } 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); } } @@ -427,13 +432,13 @@ public class JcrUtils { 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); } } @@ -468,7 +473,7 @@ public class JcrUtils { 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; @@ -504,7 +509,7 @@ public class JcrUtils { return currentNode; } catch (RepositoryException e) { discardQuietly(session); - throw new ArgeoJcrException("Cannot mkdirs " + path, e); + throw new JcrException("Cannot mkdirs " + path, e); } finally { } } @@ -571,7 +576,7 @@ public class JcrUtils { 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); } } @@ -585,14 +590,14 @@ public class JcrUtils { 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); } } @@ -685,7 +690,7 @@ public class JcrUtils { } return buf.toString(); } catch (RepositoryException e) { - throw new ArgeoJcrException("Cannot write summary of " + acl, e); + throw new JcrException("Cannot write summary of " + acl, e); } } @@ -747,7 +752,7 @@ public class JcrUtils { copy(fromChild, toChild); } } catch (RepositoryException e) { - throw new ArgeoJcrException("Cannot copy " + fromNode + " to " + toNode, e); + throw new JcrException("Cannot copy " + fromNode + " to " + toNode, e); } } @@ -775,7 +780,7 @@ public class JcrUtils { } 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); } } @@ -837,7 +842,7 @@ public class JcrUtils { } } } catch (RepositoryException e) { - throw new ArgeoJcrException("Cannot diff " + reference + " and " + observed, e); + throw new JcrException("Cannot diff " + reference + " and " + observed, e); } } @@ -879,7 +884,7 @@ public class JcrUtils { } } } catch (RepositoryException e) { - throw new ArgeoJcrException("Cannot diff " + reference + " and " + observed, e); + throw new JcrException("Cannot diff " + reference + " and " + observed, e); } return diffs; } @@ -956,22 +961,15 @@ public class JcrUtils { /** 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); } } @@ -981,8 +979,10 @@ public class JcrUtils { 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); } @@ -994,8 +994,10 @@ public class JcrUtils { 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); } @@ -1007,7 +1009,7 @@ public class JcrUtils { */ 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++) { @@ -1104,7 +1106,7 @@ public class JcrUtils { 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); } } @@ -1162,7 +1164,7 @@ public class JcrUtils { 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); } } @@ -1175,7 +1177,7 @@ public class JcrUtils { 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("/")) @@ -1185,7 +1187,7 @@ public class JcrUtils { 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); } } @@ -1209,7 +1211,7 @@ public class JcrUtils { 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(); } @@ -1240,7 +1242,7 @@ public class JcrUtils { 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); } } @@ -1332,7 +1334,7 @@ public class JcrUtils { 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 */ @@ -1377,7 +1379,7 @@ public class JcrUtils { 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(); @@ -1392,9 +1394,9 @@ public class JcrUtils { 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(); @@ -1409,7 +1411,7 @@ public class JcrUtils { 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); @@ -1420,8 +1422,8 @@ public class JcrUtils { } } 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); @@ -1444,7 +1446,7 @@ public class JcrUtils { 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; } @@ -1456,14 +1458,10 @@ public class JcrUtils { * @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); } } @@ -1473,8 +1471,8 @@ public class JcrUtils { 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); } @@ -1494,7 +1492,7 @@ public class JcrUtils { 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 { @@ -1504,8 +1502,8 @@ public class JcrUtils { 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); } @@ -1526,8 +1524,10 @@ public class JcrUtils { 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); } } @@ -1545,8 +1545,10 @@ public class JcrUtils { 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); } } diff --git a/org.argeo.jcr/src/org/argeo/jcr/PropertyDiff.java b/org.argeo.jcr/src/org/argeo/jcr/PropertyDiff.java index 3c43e52b3..71e76fe9b 100644 --- a/org.argeo.jcr/src/org/argeo/jcr/PropertyDiff.java +++ b/org.argeo.jcr/src/org/argeo/jcr/PropertyDiff.java @@ -13,28 +13,24 @@ public class PropertyDiff { 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; diff --git a/org.argeo.jcr/src/org/argeo/jcr/ThreadBoundJcrSessionFactory.java b/org.argeo.jcr/src/org/argeo/jcr/ThreadBoundJcrSessionFactory.java index cc6ef26f6..1e23338b5 100644 --- a/org.argeo.jcr/src/org/argeo/jcr/ThreadBoundJcrSessionFactory.java +++ b/org.argeo.jcr/src/org/argeo/jcr/ThreadBoundJcrSessionFactory.java @@ -54,7 +54,7 @@ public abstract class ThreadBoundJcrSessionFactory { /** 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(); @@ -76,7 +76,7 @@ public abstract class ThreadBoundJcrSessionFactory { // 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) @@ -85,7 +85,7 @@ public abstract class ThreadBoundJcrSessionFactory { 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); @@ -173,9 +173,9 @@ public abstract class ThreadBoundJcrSessionFactory { } /** - * 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; @@ -190,7 +190,7 @@ public abstract class ThreadBoundJcrSessionFactory { 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) */ diff --git a/org.argeo.jcr/src/org/argeo/jcr/proxy/AbstractUrlProxy.java b/org.argeo.jcr/src/org/argeo/jcr/proxy/AbstractUrlProxy.java index f1d028569..f0e8605c4 100644 --- a/org.argeo.jcr/src/org/argeo/jcr/proxy/AbstractUrlProxy.java +++ b/org.argeo.jcr/src/org/argeo/jcr/proxy/AbstractUrlProxy.java @@ -14,7 +14,7 @@ import javax.jcr.nodetype.NodeType; 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. */ @@ -33,9 +33,9 @@ public abstract class AbstractUrlProxy implements ResourceProxy { 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); } } @@ -73,7 +73,7 @@ public abstract class AbstractUrlProxy implements ResourceProxy { 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); @@ -89,7 +89,7 @@ public abstract class AbstractUrlProxy implements ResourceProxy { 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(); } diff --git a/org.argeo.jcr/src/org/argeo/jcr/proxy/ResourceProxyServlet.java b/org.argeo.jcr/src/org/argeo/jcr/proxy/ResourceProxyServlet.java index c399578b7..d77bd49dc 100644 --- a/org.argeo.jcr/src/org/argeo/jcr/proxy/ResourceProxyServlet.java +++ b/org.argeo.jcr/src/org/argeo/jcr/proxy/ResourceProxyServlet.java @@ -15,7 +15,7 @@ import org.apache.commons.io.FilenameUtils; 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; @@ -101,20 +101,11 @@ public class ResourceProxyServlet extends HttpServlet { 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); } } diff --git a/org.argeo.jcr/src/org/argeo/jcr/unit/AbstractJcrTestCase.java b/org.argeo.jcr/src/org/argeo/jcr/unit/AbstractJcrTestCase.java index 319ba75d6..dc2963a51 100644 --- a/org.argeo.jcr/src/org/argeo/jcr/unit/AbstractJcrTestCase.java +++ b/org.argeo.jcr/src/org/argeo/jcr/unit/AbstractJcrTestCase.java @@ -5,6 +5,7 @@ import java.security.AccessController; 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; @@ -14,10 +15,11 @@ import javax.security.auth.login.LoginException; 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); @@ -30,8 +32,7 @@ public abstract class AbstractJcrTestCase extends TestCase { 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 { @@ -60,17 +61,16 @@ public abstract class AbstractJcrTestCase extends TestCase { 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 = Subject.doAs(lc.getSubject(), new PrivilegedAction() { - @Override - public Session run() { - return login(); - } + @Override + public Session run() { + return login(); + } - }); + }); } else session = login(); this.session = session; @@ -89,10 +89,9 @@ public abstract class AbstractJcrTestCase extends TestCase { 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); } } @@ -110,8 +109,7 @@ public abstract class AbstractJcrTestCase extends TestCase { 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; }