From jackrabbit-commits-return-1283-apmail-incubator-jackrabbit-commits-archive=www.apache.org@incubator.apache.org Thu Aug 11 18:06:36 2005 Return-Path: Delivered-To: apmail-incubator-jackrabbit-commits-archive@www.apache.org Received: (qmail 87317 invoked from network); 11 Aug 2005 18:06:35 -0000 Received: from hermes.apache.org (HELO mail.apache.org) (209.237.227.199) by minotaur.apache.org with SMTP; 11 Aug 2005 18:06:35 -0000 Received: (qmail 87565 invoked by uid 500); 11 Aug 2005 18:06:34 -0000 Mailing-List: contact jackrabbit-commits-help@incubator.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: jackrabbit-dev@incubator.apache.org Delivered-To: mailing list jackrabbit-commits@incubator.apache.org Received: (qmail 87324 invoked by uid 500); 11 Aug 2005 18:06:32 -0000 Delivered-To: apmail-incubator-jackrabbit-cvs@incubator.apache.org Received: (qmail 87321 invoked by uid 99); 11 Aug 2005 18:06:32 -0000 X-ASF-Spam-Status: No, hits=-9.8 required=10.0 tests=ALL_TRUSTED,NO_REAL_NAME X-Spam-Check-By: apache.org Received: from [209.237.227.194] (HELO minotaur.apache.org) (209.237.227.194) by apache.org (qpsmtpd/0.29) with SMTP; Thu, 11 Aug 2005 11:06:25 -0700 Received: (qmail 87207 invoked by uid 65534); 11 Aug 2005 18:06:25 -0000 Message-ID: <20050811180625.87205.qmail@minotaur.apache.org> Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: svn commit: r231495 [3/7] - in /incubator/jackrabbit/trunk/contrib/jcr-commands: ./ applications/test/ applications/test/fs/ applications/test/fs/dummy folder/ benchmarking/ src/java/ src/java/org/apache/jackrabbit/chain/ src/java/org/apache/jackrabbit... Date: Thu, 11 Aug 2005 18:06:07 -0000 To: jackrabbit-cvs@incubator.apache.org From: edgarpoce@apache.org X-Mailer: svnmailer-1.0.3 X-Virus-Checked: Checked by ClamAV on apache.org X-Spam-Rating: minotaur.apache.org 1.6.2 0/1000/N Modified: incubator/jackrabbit/trunk/contrib/jcr-commands/project.properties URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/project.properties?rev=231495&r1=231494&r2=231495&view=diff ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/project.properties (original) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/project.properties Thu Aug 11 11:04:29 2005 @@ -99,3 +99,8 @@ # Site Deploy (into ../jackrabbit-site for checkout on incubator.apache.org) ###################################################################### maven.site.deploy.method=fs + +###################################################################### +# Javaapp plugin +###################################################################### +maven.javaapp.mainclass=org.apache.jackrabbit.chain.cli.JcrClient \ No newline at end of file Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/MANIFEST URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/MANIFEST?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/MANIFEST (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/MANIFEST Thu Aug 11 11:04:29 2005 @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 +Main-Class: org.apache.jackrabbit.chain.cli.JcrClient Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/log4j.properties URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/log4j.properties?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/log4j.properties (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/log4j.properties Thu Aug 11 11:04:29 2005 @@ -0,0 +1,21 @@ +# Set root logger level to DEBUG and its only appender to A1. +log4j.rootLogger=ERROR, stdout +#log4j.rootLogger=DEBUG, stdout, file +#log4j.rootLogger=ERROR, stdout, file + +log4j.logger.org.apache.jackrabbit.chain=ERROR + +# 'stdout' is set to be a ConsoleAppender. +log4j.appender.stdout=org.apache.log4j.ConsoleAppender + +# 'stdout' uses PatternLayout +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{dd.MM.yyyy HH:mm:ss} *%-5p* [%t] %c{1}: %m (%F, line %L)\n + +# 'file' is set to be a FileAppender. +# log4j.appender.file=org.apache.log4j.FileAppender +# log4j.appender.file.File=jcr.log + +# 'file' uses PatternLayout. +# log4j.appender.file.layout=org.apache.log4j.PatternLayout +# log4j.appender.file.layout.ConversionPattern=%d{dd.MM.yyyy HH:mm:ss} *%-5p* [%t] %c{1}: %m (%F, line %L)\n Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/log4j.properties ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/CtxHelper.java URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/CtxHelper.java?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/CtxHelper.java (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/CtxHelper.java Thu Aug 11 11:04:29 2005 @@ -0,0 +1,450 @@ +/* + * Copyright 2004-2005 The Apache Software Foundation or its licensors, + * as applicable. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.chain; + +import java.io.PrintWriter; +import java.util.Iterator; + +import javax.jcr.Item; +import javax.jcr.Node; +import javax.jcr.NodeIterator; +import javax.jcr.PathNotFoundException; +import javax.jcr.PropertyIterator; +import javax.jcr.Repository; +import javax.jcr.RepositoryException; +import javax.jcr.Session; + +import org.apache.commons.chain.Context; +import org.apache.commons.collections.IteratorUtils; + +/** + * Helper class for getting and setting context attributes. + */ +public class CtxHelper +{ + /** Current node key */ + private static String CURRENT_NODE_KEY = "jcr.current"; + + /** repository key */ + private static String REPOSITORY_KEY = "jcr.repository"; + + /** session key */ + private static String SESSION_KEY = "jcr.session"; + + /** session key */ + private static String OUTPUT_KEY = "jcr.output"; + + /** + * Sets the current output + * + * @param ctx + * @param output + */ + public static void setOutput(Context ctx, PrintWriter out) + { + if (out == null) + { + ctx.remove(OUTPUT_KEY); + } else + { + ctx.put(OUTPUT_KEY, out); + } + } + + /** + * Sets the current working Node + * + * @param ctx + * @param node + * @throws JcrCommandException + */ + public static void setCurrentNode(Context ctx, Node node) + throws JcrCommandException + { + if (node == null) + { + ctx.remove(CURRENT_NODE_KEY); + } else + { + ctx.put(CURRENT_NODE_KEY, node); + } + } + + /** + * Sets the current working Repository + * + * @param ctx + * @param repository + */ + public static void setRepository(Context ctx, Repository repository) + { + if (repository == null) + { + ctx.remove(REPOSITORY_KEY); + } else + { + ctx.put(REPOSITORY_KEY, repository); + } + + } + + /** + * Sets the current working Session + * + * @param ctx + * @param session + */ + public static void setSession(Context ctx, Session session) + { + if (session == null) + { + ctx.remove(SESSION_KEY); + } else + { + ctx.put(SESSION_KEY, session); + } + } + + /** + * Gets the current working Node + * + * @param ctx + * @return + */ + public static PrintWriter getOutput(Context ctx) + { + PrintWriter out = (PrintWriter) ctx.get(OUTPUT_KEY); + if (out == null) + { + out = new PrintWriter(System.out, true); + } + return out; + } + + /** + * Gets the current working Node + * + * @param ctx + * @return + * @throws JcrCommandException + */ + public static Node getCurrentNode(Context ctx) throws JcrCommandException + { + Node n = (Node) ctx.get(CURRENT_NODE_KEY); + if (n == null) + { + throw new JcrCommandException("no.current.node"); + } + return n; + } + + /** + * Gets the current working Repository + * + * @param ctx + * @return + * @throws JcrCommandException + */ + public static Repository getRepository(Context ctx) + throws JcrCommandException + { + return (Repository) ctx.get(REPOSITORY_KEY); + } + + /** + * Gets the current working Session + * + * @param ctx + * @return + * @throws JcrCommandException + */ + public static Session getSession(Context ctx) throws JcrCommandException + { + return (Session) ctx.get(SESSION_KEY); + } + + /** + * Gets node at the given path + * + * @param ctx + * @param path + * @return + * @throws JcrCommandException + * @throws PathNotFoundException + * @throws RepositoryException + */ + public static Node getNode(Context ctx, String path) + throws JcrCommandException, PathNotFoundException, + RepositoryException + { + Node current = (Node) ctx.get(CURRENT_NODE_KEY); + Node node = null; + if (path.equals("/")) + { + node = current.getSession().getRootNode(); + } else if (path.startsWith("/")) + { + node = current.getSession().getRootNode() + .getNode(path.substring(1)); + } else + { + node = current.getNode(path); + } + + return node; + } + + /** + * Gets the Item at the given path + * + * @param ctx + * @param path + * @return + * @throws JcrCommandException + * @throws PathNotFoundException + * @throws RepositoryException + */ + public static Item getItem(Context ctx, String path) + throws JcrCommandException, PathNotFoundException, + RepositoryException + { + Node current = (Node) ctx.get(CURRENT_NODE_KEY); + Item i = null; + if (path.equals("/")) + { + i = current.getSession().getRootNode(); + } else if (path.startsWith("/")) + { + i = current.getSession().getItem(path); + } else + { + String newPath = current.getPath(); + if (!newPath.endsWith("/")) + { + newPath += "/"; + } + newPath += path; + i = current.getSession().getItem(newPath); + } + + return i; + } + + /** + * Returns true if the node exists at the given path + * + * @param ctx + * @param path + * @return + * @throws JcrCommandException + * @throws RepositoryException + */ + public static boolean hasNode(Context ctx, String path) + throws JcrCommandException, RepositoryException + { + if (path.equals("/")) + { + return true; + } else if (path.startsWith("/")) + { + return getSession(ctx).getRootNode().hasNode(path.substring(1)); + } else + { + Node current = (Node) ctx.get(CURRENT_NODE_KEY); + return current.hasNode(path); + } + } + + /** + * Get the nodes under the current working node for the given pattern + * + * @param ctx + * @return + * @throws JcrCommandException + * @throws RepositoryException + */ + public static NodeIterator getNodes(Context ctx, String pattern) + throws JcrCommandException, RepositoryException + { + Node n = CtxHelper.getCurrentNode(ctx); + if (pattern != null) + { + return n.getNodes(pattern); + } else + { + return n.getNodes(); + } + } + + /** + * Get the properties under the current working node for the given pattern + * + * @param ctx + * @return + * @throws JcrCommandException + * @throws RepositoryException + */ + public static PropertyIterator getProperties(Context ctx, String pattern) + throws JcrCommandException, RepositoryException + { + Node n = CtxHelper.getCurrentNode(ctx); + if (pattern != null) + { + return n.getProperties(pattern); + } else + { + return n.getProperties(); + } + } + + /** + * Get the items under the current working node for the given pattern + * + * @param ctx + * @return + * @throws JcrCommandException + * @throws RepositoryException + */ + public static Iterator getItems(Context ctx, String pattern) + throws JcrCommandException, RepositoryException + { + return IteratorUtils.chainedIterator(getNodes(ctx, pattern), + getProperties(ctx, pattern)); + } + + /** + * @param literal + * @param key + * @param ctx + * @return the literal value if it's not null. Otherwise it returns the + * context attribute under the given key. + */ + public static String getAttr(String literal, String key, Context ctx) + { + if (literal != null) + { + return literal; + } + + if (key == null) + { + return null; + } + + return (String) ctx.get(key); + } + + /** + * + * @param literal + * @param key + * @param defa + * @param ctx + * @return the literal value if it's not null. Otherwise it returns the + * context attribute under the given key. + */ + public static boolean getBooleanAttr( + String literal, + String key, + boolean defa, + Context ctx) + { + String retu = getAttr(literal, key, ctx); + if (retu == null) + { + return defa; + } else + { + return Boolean.valueOf(retu).booleanValue(); + } + } + + /** + * + * @param key + * @param defa + * @param ctx + * @return the literal value if it's not null. Otherwise it returns the + * context attribute under the given key. If both are null it + * returns the given default value. + */ + public static boolean getBooleanAttr(String key, boolean defa, Context ctx) + { + String retu = getAttr(null, key, ctx); + if (retu == null) + { + return defa; + } else + { + return Boolean.valueOf(retu).booleanValue(); + } + } + + /** + * + * @param literal + * @param key + * @param defa + * @param ctx + * @return the literal value if it's not null. Otherwise it returns the + * context attribute under the given key. If both are null it + * returns the given default value. + */ + public static int getIntAttr( + String literal, + String key, + int defa, + Context ctx) + { + String retu = getAttr(literal, key, ctx); + if (retu == null) + { + return defa; + } else + { + return Integer.parseInt(retu); + } + } + + /** + * + * @param literal + * @param key + * @param defa + * @param ctx + * @return the literal value if it's not null. Otherwise it returns the + * context attribute under the given key. If both are null it + * returns the given default value. + * @throws JcrCommandException + */ + public static String getAttr( + String literal, + String key, + String defa, + Context ctx) throws JcrCommandException + { + String retu = getAttr(literal, key, ctx); + if (retu == null) + { + return defa; + } else + { + return retu; + } + } + +} Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/CtxHelper.java ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/JcrCommandException.java URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/JcrCommandException.java?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/JcrCommandException.java (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/JcrCommandException.java Thu Aug 11 11:04:29 2005 @@ -0,0 +1,97 @@ +/* + * Copyright 2004-2005 The Apache Software Foundation or its licensors, + * as applicable. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.chain; + +import java.text.MessageFormat; +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +/** + * JCR command Exception + */ +public class JcrCommandException extends Exception +{ + /** Resource bundle */ + private ResourceBundle bundle = ResourceBundle.getBundle(this.getClass() + .getPackage().getName() + + ".exceptions"); + + private Object[] arguments; + + /** + * Comment for serialVersionUID + */ + private static final long serialVersionUID = 3978426922931860275L; + + /** + * @param message + */ + public JcrCommandException(String message) + { + super(message); + } + + /** + * @param message + * @param arguments + */ + public JcrCommandException(String message, Object[] arguments) + { + super(message); + this.arguments = arguments; + } + + /** + * @param message + * @param cause + */ + public JcrCommandException(String message, Throwable cause) + { + super(message, cause); + } + + /** + * @param message + * @param cause + * @param arguments + */ + public JcrCommandException(String message, Throwable cause, + Object[] arguments) + { + super(message, cause); + this.arguments = arguments; + } + + public String getLocalizedMessage() + { + try + { + if (this.arguments == null) + { + return bundle.getString(this.getMessage()); + } else + { + MessageFormat f = new MessageFormat(""); + f.applyPattern(bundle.getString(this.getMessage())); + return f.format(this.arguments); + } + } catch (MissingResourceException e) + { + return this.getMessage(); + } + } +} Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/JcrCommandException.java ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/AbstractParameter.java URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/AbstractParameter.java?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/AbstractParameter.java (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/AbstractParameter.java Thu Aug 11 11:04:29 2005 @@ -0,0 +1,180 @@ +/* + * Copyright 2004-2005 The Apache Software Foundation or its licensors, + * as applicable. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.chain.cli; + +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +/** + * Command Line parameter superclass + */ +public abstract class AbstractParameter implements Cloneable +{ + + /** Resource bundle */ + protected ResourceBundle bundle = ResourceBundle.getBundle(this.getClass() + .getPackage().getName() + + ".resources"); + + /** name */ + private String name; + + /** long name */ + private String longName; + + /** description */ + private String description; + + /** command or a context attribute */ + private String commandAttribute; + + /** value */ + private String value; + + /** + * @return Returns the description. + */ + public String getDescription() + { + return description; + } + + /** + * @return localized description + */ + public String getLocalizedDescription() + { + String str = null; + if (description == null) + { + try + { + str = bundle.getString(name); + } catch (MissingResourceException e) + { + str = name; + } + } else + { + try + { + str = bundle.getString(description); + } catch (MissingResourceException e) + { + str = description; + } + } + return str; + } + + /** + * @return Returns the name. + */ + public String getName() + { + return name; + } + + /** + * @param description + * The description to set. + */ + public void setDescription(String description) + { + this.description = description; + } + + /** + * @param name + * The name to set. + */ + public void setName(String name) + { + this.name = name; + } + + /** + * @return Returns the value. + */ + public String getValue() + { + return value; + } + + /** + * @param value + * The value to set. + */ + public void setValue(String value) + { + this.value = value; + } + + /** + * @return Returns the longName. + */ + public String getLongName() + { + return longName; + } + + /** + * @param longName + * The longName to set. + */ + public void setLongName(String longName) + { + this.longName = longName; + } + + protected void clone(AbstractParameter param) + { + param.commandAttribute = this.commandAttribute; + param.description = this.description; + param.longName = this.longName; + param.name = this.name; + param.value = this.value; + } + + /** + * @return Returns the commandAttribute. + */ + public String getCommandAttribute() + { + return commandAttribute; + } + + /** + * @param commandAttribute + * The commandAttribute to set. + */ + public void setCommandAttribute(String commandAttribute) + { + this.commandAttribute = commandAttribute; + } + + /** + * @return true if this parameter is mandatory + */ + public abstract boolean isRequired(); + + /** + * @return argumentlocalized name + */ + public abstract String getLocalizedArgName(); + +} Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/AbstractParameter.java ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Argument.java URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Argument.java?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Argument.java (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Argument.java Thu Aug 11 11:04:29 2005 @@ -0,0 +1,50 @@ +/* + * Copyright 2004-2005 The Apache Software Foundation or its licensors, + * as applicable. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.chain.cli; + +/** + * Command line argument. + */ +public class Argument extends Option +{ + /** position of the argument */ + private int position; + + /** + * @return + */ + public int getPosition() + { + return position; + } + + public void setPosition(int position) + { + this.position = position; + } + + /** + * @inheritDoc + */ + public Object clone() + { + Argument arg = new Argument(); + arg.position = this.position; + this.clone(arg); + return arg; + } +} Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Argument.java ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/CommandLine.java URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/CommandLine.java?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/CommandLine.java (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/CommandLine.java Thu Aug 11 11:04:29 2005 @@ -0,0 +1,359 @@ +/* + * Copyright 2004-2005 The Apache Software Foundation or its licensors, + * as applicable. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.chain.cli; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.TreeMap; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.Predicate; +import org.apache.commons.collections.iterators.IteratorChain; + +/** + * Command Line. + */ +public class CommandLine implements Comparable, Cloneable +{ + /** Resource bundle */ + protected ResourceBundle bundle = ResourceBundle.getBundle(this.getClass() + .getPackage().getName() + + ".resources"); + + /** Name */ + private String name; + + /** Description */ + private String description; + + /** Commons chain command implementation */ + private String impl; + + /** alias */ + private Collection alias = new ArrayList(); + + /** Options */ + private Map options = new TreeMap(); + + /** Options */ + private Map flags = new TreeMap(); + + /** arguments */ + private Map arguments = new TreeMap(); + + /** + * constructor + */ + public CommandLine() + { + super(); + } + + /** + * @return required arguments + */ + public Collection getRequiredArguments() + { + Predicate p = new Predicate() + { + public boolean evaluate(Object o) + { + Argument arg = (Argument) o; + return arg.isRequired(); + } + }; + return CollectionUtils.select(this.arguments.values(), p); + } + + /** + * @return required options + */ + public Collection getRequiredOptions() + { + Predicate p = new Predicate() + { + public boolean evaluate(Object o) + { + Option opt = (Option) o; + return opt.isRequired(); + } + }; + return CollectionUtils.select(this.options.values(), p); + } + + /** + * @return Returns the description. + */ + public String getDescription() + { + return description; + } + + /** + * @return Returns the localized description. + */ + public String getLocalizedDescription() + { + String str = null; + if (description == null) + { + try + { + str = bundle.getString(this.name); + } catch (MissingResourceException e) + { + str = this.name; + } + } else + { + try + { + str = bundle.getString(this.description); + } catch (MissingResourceException e) + { + str = this.description; + } + } + return str; + } + + /** + * @param description + * The description to set. + */ + public void setDescription(String description) + { + this.description = description; + } + + /** + * @return Returns the flags. + */ + public Map getFlags() + { + return flags; + } + + /** + * @param flags + * The flags to set. + */ + public void setFlags(Map flags) + { + this.flags = flags; + } + + /** + * @return Returns the impl. + */ + public String getImpl() + { + return impl; + } + + /** + * @param impl + * The impl to set. + */ + public void setImpl(String impl) + { + this.impl = impl; + } + + /** + * @return Returns the name. + */ + public String getName() + { + return name; + } + + /** + * @param name + * The name to set. + */ + public void setName(String name) + { + this.name = name; + } + + /** + * @return Returns the options. + */ + public Map getOptions() + { + return options; + } + + /** + * @param options + * The options to set. + */ + public void setOptions(Map options) + { + this.options = options; + } + + /** + * @inheritDoc + */ + public int compareTo(Object o) + { + CommandLine cl = (CommandLine) o; + return name.compareTo(cl.name); + } + + /** + * @return all the parameters. i.e. args, options and flags. + */ + public Iterator getAllParameters() + { + IteratorChain chain = new IteratorChain(); + chain.addIterator(getArguments().values().iterator()); + chain.addIterator(getOptions().values().iterator()); + chain.addIterator(getFlags().values().iterator()); + return chain; + } + + /** + * @return the required parameters. i.e. args, options and flags. + */ + public Iterator getRequiredParameters() + { + IteratorChain chain = new IteratorChain(); + chain.addIterator(getRequiredArguments().iterator()); + chain.addIterator(getRequiredOptions().iterator()); + return chain; + } + + /** + * Add an argument + * + * @param arg + */ + public void addArgument(Argument arg) + { + if (arguments.containsKey(new Integer(arg.getPosition()))) + { + throw new IllegalArgumentException( + "there's an argument in the position"); + } + this.arguments.put(new Integer(arg.getPosition()), arg); + } + + /** + * Add an Option + * + * @param opt + */ + public void addOption(Option opt) + { + this.options.put(opt.getName(), opt); + } + + /** + * Flag + * + * @param flag + */ + public void addFlag(Flag flag) + { + this.flags.put(flag.getName(), flag); + } + + /** + * @return Returns the arguments. + */ + public Map getArguments() + { + return arguments; + } + + /** + * @param arguments + * The arguments to set. + */ + public void setArguments(Map arguments) + { + this.arguments = arguments; + } + + /** + * @return Returns the alias. + */ + public Collection getAlias() + { + return alias; + } + + /** + * @param alias + * The alias to set. + */ + public void setAlias(Collection alias) + { + this.alias = alias; + } + + /** + * Add alias + * + * @param alias + */ + public void addAlias(String alias) + { + this.alias.add(alias); + } + + /** + * @inheritDoc + */ + public Object clone() + { + CommandLine cl = new CommandLine(); + cl.alias = this.alias; + // Arguments + Iterator iter = this.arguments.values().iterator(); + while (iter.hasNext()) + { + Argument arg = (Argument) iter.next(); + cl.addArgument((Argument) arg.clone()); + } + cl.description = this.description; + // Flags + iter = this.flags.values().iterator(); + while (iter.hasNext()) + { + Flag f = (Flag) iter.next(); + cl.addFlag((Flag) f.clone()); + } + cl.impl = this.impl; + cl.name = this.name; + // Flags + iter = this.options.values().iterator(); + while (iter.hasNext()) + { + Option o = (Option) iter.next(); + cl.addOption((Option) o.clone()); + } + return cl; + } +} Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/CommandLine.java ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/CommandLineFactory.java URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/CommandLineFactory.java?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/CommandLineFactory.java (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/CommandLineFactory.java Thu Aug 11 11:04:29 2005 @@ -0,0 +1,196 @@ +/* + * Copyright 2004-2005 The Apache Software Foundation or its licensors, + * as applicable. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.chain.cli; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.apache.commons.digester.Digester; +import org.apache.commons.digester.xmlrules.DigesterLoader; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.jackrabbit.chain.JcrCommandException; +import org.xml.sax.SAXException; + +/** + * Command line factory. + */ +public class CommandLineFactory +{ + /** logger */ + private static Log log = LogFactory.getLog(CommandLineFactory.class); + + /** file name */ + private static String COMMAND_LINE_FILE = "command-line.xml"; + + /** rules file name */ + private static String COMMAND_LINE_RULES_FILE = "command-line-rules.xml"; + + /** singleton */ + private static CommandLineFactory singleton; + + /** command cache */ + private Map cache = new TreeMap(); + + /** alias cache */ + private Map alias = new HashMap(); + + /** + * private Constructor + */ + private CommandLineFactory() + { + super(); + } + + /** + * @return CliCommandFactory singleton + */ + public static CommandLineFactory getInstance() + { + if (singleton == null) + { + try + { + CommandLineFactory factory = new CommandLineFactory(); + factory.init(); + singleton = factory; + } catch (Exception e) + { + log.error("unable to init CommandLineFactory", e); + e.printStackTrace(); + } + } + return singleton; + } + + /** + * @return all registered commands + * @throws JcrCommandException + */ + public Collection getCommandLines() throws JcrCommandException + { + List cls = new ArrayList(); + Iterator iter = cache.values().iterator(); + while (iter.hasNext()) + { + CommandLine cl = (CommandLine) iter.next(); + cls.add(cl.clone()); + } + return cls; + } + + /** + * @param name + * @return a new Command Line Instance for the given command name + * @throws JcrParserException + */ + public CommandLine getCommandLine(String name) throws JcrParserException + { + log.debug("lookup command " + name); + // get Command line + CommandLine original = (CommandLine) cache.get(name); + + if (original == null) + { + log.debug("lookup alias " + name); + original = (CommandLine) alias.get(name); + } + + if (original == null) + { + log.warn("command not found " + name); + throw new JcrParserException("no.command.for.name", new String[] + { + name + }); + } + + // Return a clone + return (CommandLine) original.clone(); + } + + /** + * Parse configuration file + * + * @throws IOException + * @throws SAXException + * @throws ConfigurationException + */ + private void init() throws IOException, SAXException, + ConfigurationException + { + // Configure Digester from XML ruleset + URL rulesFile = getClass().getResource(COMMAND_LINE_RULES_FILE); + URL clFile = getClass().getResource(COMMAND_LINE_FILE); + + // init digester + Digester digester = DigesterLoader.createDigester(rulesFile); + + // Push empty List onto Digester's Stack + List cls = new ArrayList(); + digester.push(cls); + + // Parse the XML document + InputStream input = clFile.openStream(); + digester.parse(input); + input.close(); + + // Add to cache + Iterator iter = cls.iterator(); + while (iter.hasNext()) + { + CommandLine cl = (CommandLine) iter.next(); + cache.put(cl.getName(), cl); + // Add to alias cache + Iterator aliasIt = cl.getAlias().iterator(); + while (aliasIt.hasNext()) + { + String aliasName = (String) aliasIt.next(); + if (alias.containsKey(aliasName)) + { + throw new ConfigurationException("alias.already.in.use", + new String[] + { + aliasName, cl.getName() + }); + } + alias.put(aliasName, cl); + } + } + } + + /** + * @param args + * @throws Exception + */ + public static void main(String[] args) throws Exception + { + // TODO: remove this + Collection c = CommandLineFactory.getInstance().getCommandLines(); + System.out.println(c.size()); + } + +} Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/CommandLineFactory.java ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/ConfigurationException.java URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/ConfigurationException.java?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/ConfigurationException.java (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/ConfigurationException.java Thu Aug 11 11:04:29 2005 @@ -0,0 +1,68 @@ +/* + * Copyright 2004-2005 The Apache Software Foundation or its licensors, + * as applicable. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.chain.cli; + +import org.apache.jackrabbit.chain.JcrCommandException; + +/** + * This Exception is thrown when there's an error in the command config file. + */ +public class ConfigurationException extends JcrCommandException +{ + + /** + * serialVersionUID + */ + private static final long serialVersionUID = 3257848770644621622L; + + /** + * @param message + */ + public ConfigurationException(String message) + { + super(message); + } + + /** + * @param message + * @param arguments + */ + public ConfigurationException(String message, Object[] arguments) + { + super(message, arguments); + } + + /** + * @param message + * @param cause + */ + public ConfigurationException(String message, Throwable cause) + { + super(message, cause); + } + + /** + * @param message + * @param cause + * @param arguments + */ + public ConfigurationException(String message, Throwable cause, + Object[] arguments) + { + super(message, cause, arguments); + } +} Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/ConfigurationException.java ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Flag.java URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Flag.java?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Flag.java (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Flag.java Thu Aug 11 11:04:29 2005 @@ -0,0 +1,86 @@ +/* + * Copyright 2004-2005 The Apache Software Foundation or its licensors, + * as applicable. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.chain.cli; + +/** + * Command line flag. A flag is a parameter that has no other value that the + * option name. e.g. -[flag name]. + */ +public class Flag extends AbstractParameter +{ + private boolean present = false; + + /** + * @return Returns the present. + */ + public boolean isPresent() + { + return present; + } + + /** + * @param present + * The present to set. + */ + public void setPresent(boolean present) + { + this.present = present; + } + + /** + * @inheritDoc + */ + public String getValue() + { + return Boolean.toString(present); + } + + /** + * @inheritDoc + */ + public void setValue(String value) + { + present = Boolean.getBoolean(value); + } + + /** + * @inheritDoc + */ + public Object clone() + { + Flag f = new Flag(); + f.present = this.present; + this.clone(f); + return f; + } + + /** + * @inheritDoc + */ + public boolean isRequired() + { + return false; + } + + /** + * @inheritDoc + */ + public String getLocalizedArgName() + { + return ""; + } +} Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Flag.java ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrClient.java URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrClient.java?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrClient.java (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrClient.java Thu Aug 11 11:04:29 2005 @@ -0,0 +1,268 @@ +/* + * Copyright 2004-2005 The Apache Software Foundation or its licensors, + * as applicable. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.chain.cli; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.Locale; +import java.util.ResourceBundle; + +import javax.jcr.Node; +import javax.jcr.Repository; +import javax.jcr.Session; + +import org.apache.commons.chain.Context; +import org.apache.commons.chain.impl.ContextBase; +import org.apache.commons.cli.BasicParser; +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.apache.commons.cli.Parser; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.jackrabbit.chain.CtxHelper; + +/** + * Command line interface client + */ +public class JcrClient +{ + private static Log log = LogFactory.getLog(JcrClient.class); + + /** Resource bundle */ + private ResourceBundle bundle = ResourceBundle.getBundle(this.getClass() + .getPackage().getName() + + ".resources"); + + /** exit control variable */ + private boolean exit = false; + + /** Execution context */ + private Context ctx = new ContextBase(); + + /** run options */ + private Options options; + + /** + * Constructor + */ + private JcrClient() + { + super(); + initOptions(); + initContext(); + } + + /** + * @param args + */ + public static void main(String[] args) + { + JcrClient client = new JcrClient(); + client.run(args); + } + + /** + * Run client + * + * @param args + */ + private void run(String[] args) + { + try + { + // parse arguments + Parser parser = new BasicParser(); + CommandLine cl = parser.parse(options, args); + + // Set locale + this.setLocale(cl); + + // Welcome message + System.out.println(bundle.getString("welcome")); + } catch (Exception e) + { + HelpFormatter hf = new HelpFormatter(); + hf.printHelp("jcrclient", options); + e.printStackTrace(); + return; + } + + // Prompt command + while (!exit) + { + try + { + System.out.print(this.getPrompt() + ">"); + // Read input + BufferedReader br = new BufferedReader(new InputStreamReader( + System.in)); + String input = br.readLine(); + if (input.trim().equals("exit") || input.trim().equals("quit")) + { // exit? + exit = true; + System.out.println("Good bye.."); + } else if (input.trim().length() == 0) + { + // Do nothing + } else + { + // Process user input + JcrParser parser = new JcrParser(); + parser.parse(input); + + // populate ctx + parser.populateContext(ctx); + + // Execute command + long start = System.currentTimeMillis(); + parser.getCommand().execute(ctx); + long elapsed = System.currentTimeMillis() - start; + + // depopulate ctx + parser.dePopulateContext(ctx); + + // Display elapsed timed + System.out.println(); + System.out.println(bundle.getString("elapsedtime") + ": " + + elapsed + " ms."); + System.out.println(); + } + } catch (JcrParserException e) + { + System.out.println(e.getLocalizedMessage()); + System.out.println(); + } catch (Exception e) + { + handleException(e); + } + } + + } + + /** + * Handle the Exception.
+ * Shows a short message and prompt the user to show the entire stacktrace. + * + * @param e + */ + private void handleException(Exception ex) + { + System.out.println(); + System.out.println(bundle.getString("exception.occurred")); + System.out.println(); + System.out.println(bundle.getString("exception") + ": " + + ex.getClass().getName()); + System.out.println(bundle.getString("message") + ": " + + ex.getLocalizedMessage()); + System.out.println(); + String prompt = bundle.getString("prompt.display.stacktrace"); + int counter = 0; + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + String str = ""; + int tries = 0; + while (!str.equals("y") && !str.equals("n") && tries < 3) + { + tries++; + System.out.print(prompt); + try + { + str = in.readLine(); + } catch (IOException e) + { + e.printStackTrace(); + } + } + if (str.equals("y")) + { + ex.printStackTrace(); + } + } + + /** + * Prompt message + * + * @return prompt + * @throws Exception + */ + private String getPrompt() throws Exception + { + + Repository r = CtxHelper.getRepository(ctx); + if (r == null) + { + return bundle.getString("not.connected"); + } + + Session s = CtxHelper.getSession(ctx); + if (s == null) + { + return bundle.getString("not.logged.in"); + } + + Node n = CtxHelper.getCurrentNode(ctx); + + return n.getPath(); + } + + /** + * Init allowed CommandLine options + */ + private void initOptions() + { + options = new Options(); + options.addOption("lang", "code", true, "Language code"); + options.addOption("country", "code", true, "Country code"); + } + + /** + * Sets the default Locale for the given CommandLine + * + * @param cl + * @throws ParseException + */ + private void setLocale(CommandLine cl) throws ParseException + { + Locale locale = null; + if (cl.hasOption("lang") && cl.hasOption("country")) + { + locale = new Locale(cl.getOptionValue("lang"), cl + .getOptionValue("country")); + } + if (cl.hasOption("lang") && !cl.hasOption("country")) + { + locale = new Locale(cl.getOptionValue("lang")); + } + if (locale != null) + { + Locale.setDefault(locale); + } + } + + /** + * Init context.
+ * Sets the Context Output to the console + */ + private void initContext() + { + CtxHelper.setOutput(ctx, new PrintWriter(System.out, true)); + } + +} Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrClient.java ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrParser.java URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrParser.java?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrParser.java (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrParser.java Thu Aug 11 11:04:29 2005 @@ -0,0 +1,404 @@ +/* + * Copyright 2004-2005 The Apache Software Foundation or its licensors, + * as applicable. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.chain.cli; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.beanutils.BeanUtils; +import org.apache.commons.chain.Catalog; +import org.apache.commons.chain.Command; +import org.apache.commons.chain.Context; +import org.apache.commons.chain.config.ConfigParser; +import org.apache.commons.chain.impl.CatalogFactoryBase; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * User's Input Parser.
+ * + *
    + *
  • Lookup the CommandLine.
  • + *
  • Populate CommandLine
  • + *
  • Validate CommandLine
  • + *
  • Get a Chain Command either from the the Catalog or by creating a new + * Instance.
  • + *
+ * + */ +public class JcrParser +{ + /** parser */ + private static Log log = LogFactory.getLog(JcrParser.class); + + static + { + try + { + ConfigParser parser = new ConfigParser(); + parser.parse(JcrParser.class.getResource("chains.xml")); + } catch (Exception e) + { + e.printStackTrace(); + log.error(e); + } + } + + /** catalog */ + private Catalog catalog = CatalogFactoryBase.getInstance().getCatalog(); + + /** Command */ + private Command cmd; + + /** Command Line */ + private CommandLine cl; + + /** + * Constructor + */ + public JcrParser() + { + super(); + } + + /** + * Parse the user's input. + * + * @param input + * @return a Command + * @throws JcrParserException + * if the input is illegal + * @throws ConfigurationException + * if the mapped command can't be mapped to a Commons Chain + * Command + */ + public void parse(String input) throws JcrParserException, + ConfigurationException + { + this.cl = null; + this.cmd = null; + + // Validate input + if (input == null || input.length() == 0) + { + throw new JcrParserException("parse.input.empty"); + } + + // Extract arguments + LinkedList args = this.getArguments(input); + + // The first arg is the command name + String cmdName = (String) args.getFirst(); + args.removeFirst(); + + // parse command line + cl = CommandLineFactory.getInstance().getCommandLine(cmdName); + + // populate with params + populate(cl, args); + + // populate with params + validate(cl); + + // Create Chain Command + createCommand(); + + } + + /** + * If the CommandLine specifies an implementation a new Command instance + * will created an populated with the given parameters. If the CommandLine + * doesn't specify an implementation the parser will lookup the Command in + * the Catalog, and the attributes will be used to populate the Context. + * + * @throws ConfigurationException + * if the Command can not be instantiated or found in the + * Catalog + */ + private void createCommand() throws ConfigurationException + { + if (cl.getImpl() != null) + { + try + { + log.debug("create command instance " + cl.getName()); + // Get command + cmd = (Command) Class.forName(cl.getImpl()).newInstance(); + + Map attrs = BeanUtils.describe(cmd); + + Iterator iter = cl.getAllParameters(); + + while (iter.hasNext()) + { + AbstractParameter param = (AbstractParameter) iter.next(); + + // Command attribute + String commandAttr = param.getCommandAttribute(); + if (commandAttr == null) + { + commandAttr = param.getName(); + } + + // Check that the Command has the attribute + if (!attrs.containsKey(commandAttr)) + { + throw new ConfigurationException( + "no.attribute.for.name", new String[] + { + param.getName(), cmd.getClass().getName() + }); + } + + BeanUtils.setProperty(cmd, commandAttr, param.getValue()); + } + + } catch (Exception e) + { + throw new ConfigurationException("parse.instantiate.command", + e, new String[] + { + cl.getImpl() + }); + } + } else + { + log.debug("lookup command " + cl.getName() + "in default catalog"); + cmd = catalog.getCommand(cl.getName()); + if (cmd == null) + { + throw new ConfigurationException( + "no.command.in.catalog.for.name", new String[] + { + cl.getName() + }); + } + } + + } + + /** + * Tokenize user's input + * + * @param input + * @return + */ + private LinkedList getArguments(String input) + { + LinkedList args = new LinkedList(); + int length = input.length(); + + boolean exit = false; + boolean insideSingleQuote = false; + boolean insideDoubleQuote = false; + int escape = -1; + + StringBuffer arg = new StringBuffer(); + + for (int i = 0; i < length; ++i) + { + char c = input.charAt(i); + + // end of argument? + if ((!insideSingleQuote & !insideDoubleQuote & Character + .isWhitespace(c))) + { + if (arg.toString().trim().length() > 0) + { + args.add(arg.toString().trim()); + arg = new StringBuffer(); + } + continue; + } + + if (i == escape) + { // escaped char + arg.append(c); + } else + { // unescaped char + switch (c) + { + case '\\': + escape = i + 1; + break; + case '"': + insideDoubleQuote = !insideDoubleQuote; + break; + case '\'': + insideSingleQuote = !insideSingleQuote; + break; + default: + arg.append(c); + break; + } + } + } + + if (arg.toString().trim().length() > 0) + { + args.add(arg.toString()); + } + + return args; + } + + /** + * Populate the context with the attributes needed by the Command + */ + public void populateContext(Context ctx) + { + if (cl.getImpl() == null) + { + Iterator iter = cl.getAllParameters(); + while (iter.hasNext()) + { + AbstractParameter param = (AbstractParameter) iter.next(); + log.debug("add ctx attr: " + param.getName() + "=" + + param.getValue()); + ctx.put(param.getName(), param.getValue()); + } + } + } + + /** + * Remove context attribute specific to the parsed command + */ + public void dePopulateContext(Context ctx) + { + if (cl.getImpl() == null) + { + Iterator iter = cl.getAllParameters(); + while (iter.hasNext()) + { + AbstractParameter param = (AbstractParameter) iter.next(); + log.debug("remove ctx attr: " + param.getName() + "=" + + param.getValue()); + ctx.remove(param.getName()); + } + } + } + + /** + * @return the Command + */ + public Command getCommand() + { + return cmd; + } + + /** + * Populate the CommandLine with the given parameters + * + * @param cl + * @param values + * @throws JcrParserException + */ + private void populate(CommandLine cl, List valList) + throws JcrParserException + { + String[] values = (String[]) valList + .toArray(new String[valList.size()]); + + // Command Line parameters + Map options = cl.getOptions(); + Map flags = cl.getFlags(); + Map clArgs = cl.getArguments(); + + // Input arguments + List args = new ArrayList(); + + for (int i = 0; i < values.length; i++) + { + String value = values[i]; + + if (value.startsWith("-")) + { + // option + if (i + 1 < values.length && !values[i + 1].startsWith("-")) + { + Option opt = (Option) options.get(value.substring(1)); + if (opt == null) + { + throw new JcrParserException("no.opt.for.name", + new String[] + { + value.substring(1) + }); + } + opt.setValue(values[i + 1]); + i++; + } else + { + // flag + Flag flag = (Flag) flags.get(value.substring(1)); + if (flag == null) + { + throw new JcrParserException("no.flag.for.name", + new String[] + { + value + }); + } + flag.setPresent(true); + } + } else + { + // collect arguments + args.add(value); + } + } + + // set arguments + String[] argValues = (String[]) args.toArray(new String[args.size()]); + for (int j = 0; j < argValues.length; j++) + { + Argument arg = (Argument) clArgs.get(new Integer(j)); + if (arg == null) + { + throw new JcrParserException("more.arguments.than.expected"); + } + arg.setValue(argValues[j]); + } + + } + + /** + * Validate the CommandLine. + * + * @param cl + * @throws JcrParserException + */ + private void validate(CommandLine cl) throws JcrParserException + { + Iterator iter = cl.getRequiredParameters(); + while (iter.hasNext()) + { + AbstractParameter param = (AbstractParameter) iter.next(); + if (param.getValue() == null) + { + throw new JcrParserException("missing.paramater", new String[] + { + param.getName() + }); + } + } + } + +} Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrParser.java ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrParserException.java URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrParserException.java?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrParserException.java (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrParserException.java Thu Aug 11 11:04:29 2005 @@ -0,0 +1,68 @@ +/* + * Copyright 2004-2005 The Apache Software Foundation or its licensors, + * as applicable. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.chain.cli; + +import org.apache.jackrabbit.chain.JcrCommandException; + +/** + * Exception thrown if any error occurs while parsing the user's input. + */ +public class JcrParserException extends JcrCommandException +{ + + /** + * serialVersionUID + */ + private static final long serialVersionUID = 3761694498056713525L; + + /** + * @param message + * @param arguments + */ + public JcrParserException(String message, Object[] arguments) + { + super(message, arguments); + } + + /** + * @param message + * @param cause + * @param arguments + */ + public JcrParserException(String message, Throwable cause, + Object[] arguments) + { + super(message, cause, arguments); + } + + /** + * @param message + */ + public JcrParserException(String message) + { + super(message); + } + + /** + * @param message + * @param cause + */ + public JcrParserException(String message, Throwable cause) + { + super(message, cause); + } +} Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/JcrParserException.java ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Option.java URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Option.java?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Option.java (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Option.java Thu Aug 11 11:04:29 2005 @@ -0,0 +1,107 @@ +/* + * Copyright 2004-2005 The Apache Software Foundation or its licensors, + * as applicable. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.chain.cli; + +import java.util.MissingResourceException; + +/** + * Command Line option. An option is a pair of parameters with the following + * pattern -[option name] [option value] + */ +public class Option extends AbstractParameter +{ + + /** argument name */ + private String argName; + + /** required */ + private boolean required = false; + + /** + * @return Returns the required. + */ + public boolean isRequired() + { + return required; + } + + /** + * @param required + * The required to set. + */ + public void setRequired(boolean required) + { + this.required = required; + } + + /** + * @return Returns the argName. + */ + public String getArgName() + { + return argName; + } + + /** + * @return localized argument name + */ + public String getLocalizedArgName() + { + String str = null; + if (argName == null) + { + str = this.getName(); + } else + { + try + { + str = bundle.getString(argName); + } catch (MissingResourceException e) + { + str = argName; + } + } + return str; + } + + /** + * @param argName + * The argName to set. + */ + public void setArgName(String argName) + { + this.argName = argName; + } + + /** + * @inheritDoc + */ + public Object clone() + { + Option o = new Option(); + this.clone(o); + return o; + } + + protected void clone(Option opt) + { + super.clone(opt); + opt.argName = this.argName; + opt.required = this.required; + + } +} Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/Option.java ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/SourceCommand.java URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/SourceCommand.java?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/SourceCommand.java (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/SourceCommand.java Thu Aug 11 11:04:29 2005 @@ -0,0 +1,102 @@ +/* + * Copyright 2004-2005 The Apache Software Foundation or its licensors, + * as applicable. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.chain.cli; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.PrintWriter; +import java.util.ResourceBundle; + +import org.apache.commons.chain.Command; +import org.apache.commons.chain.Context; +import org.apache.jackrabbit.chain.CtxHelper; +import org.apache.jackrabbit.chain.JcrCommandException; + +/** + * Executes a CLI script from the given file. + */ +public class SourceCommand implements Command +{ + /** Resource bundle */ + private ResourceBundle bundle = ResourceBundle.getBundle(this.getClass() + .getPackage().getName() + + ".resources"); + + /** file */ + private String file; + + /** cli parser */ + JcrParser parser = new JcrParser(); + + /** + * @return Returns the file. + */ + public String getFile() + { + return file; + } + + /** + * @param file + * The file to set. + */ + public void setFile(String file) + { + this.file = file; + } + + /** + * @inheritDoc + */ + public boolean execute(Context ctx) throws Exception + { + File f = new File(file); + if (!f.exists()) + { + throw new JcrCommandException("file.not.found", new String[] + { + file + }); + } + BufferedReader in = new BufferedReader(new FileReader(f)); + PrintWriter out = CtxHelper.getOutput(ctx); + String line = null; + while ((line = in.readLine()) != null) + { + out.println(bundle.getString("running") + ": " + line); + + parser.parse(line); + // populate ctx + parser.populateContext(ctx); + + // Execute command + long start = System.currentTimeMillis(); + parser.getCommand().execute(ctx); + long elapsed = System.currentTimeMillis() - start; + + // depopulate ctx + parser.dePopulateContext(ctx); + + out + .println(" " + bundle.getString("in") + ": " + elapsed + + " ms"); + } + in.close(); + return false; + } +} Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/SourceCommand.java ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/chains.xml URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/chains.xml?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/chains.xml (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/chains.xml Thu Aug 11 11:04:29 2005 @@ -0,0 +1,143 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/chains.xml ------------------------------------------------------------------------------ svn:eol-style = native Added: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/command-line-rules.xml URL: http://svn.apache.org/viewcvs/incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/command-line-rules.xml?rev=231495&view=auto ============================================================================== --- incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/command-line-rules.xml (added) +++ incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/command-line-rules.xml Thu Aug 11 11:04:29 2005 @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Propchange: incubator/jackrabbit/trunk/contrib/jcr-commands/src/java/org/apache/jackrabbit/chain/cli/command-line-rules.xml ------------------------------------------------------------------------------ svn:eol-style = native