You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@oozie.apache.org by vi...@apache.org on 2013/02/25 22:42:09 UTC

svn commit: r1449911 [4/8] - in /oozie/trunk: ./ client/src/main/java/org/apache/oozie/cli/ client/src/main/java/org/apache/oozie/client/ client/src/main/java/org/apache/oozie/client/rest/ client/src/test/java/org/apache/oozie/client/rest/ core/ core/s...

Added: oozie/trunk/core/src/main/java/org/apache/oozie/jms/JMSExceptionListener.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/jms/JMSExceptionListener.java?rev=1449911&view=auto
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/jms/JMSExceptionListener.java (added)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/jms/JMSExceptionListener.java Mon Feb 25 21:42:07 2013
@@ -0,0 +1,52 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.oozie.jms;
+
+import javax.jms.ExceptionListener;
+import javax.jms.JMSException;
+
+import org.apache.oozie.service.JMSAccessorService;
+import org.apache.oozie.service.Services;
+import org.apache.oozie.util.XLog;
+
+public class JMSExceptionListener implements ExceptionListener {
+
+    private static XLog LOG = XLog.getLog(JMSExceptionListener.class);
+    private JMSConnectionInfo connInfo;
+    private ConnectionContext connCtxt;
+
+    /**
+     * Create ExceptionLister for a JMS Connection
+     *
+     * @param connInfo Information to connect to the JMS compliant messaging service
+     * @param connCtxt The actual connection on which this listener will be registered
+     */
+    public JMSExceptionListener(JMSConnectionInfo connInfo, ConnectionContext connCtxt) {
+        this.connInfo = connInfo;
+        this.connCtxt = connCtxt;
+    }
+
+    @Override
+    public void onException(JMSException exception) {
+        LOG.warn("Received JMSException for [{0}]. Reestablishing connection", connInfo, exception);
+        connCtxt.close();
+        JMSAccessorService jmsService = Services.get().get(JMSAccessorService.class);
+        jmsService.reestablishConnection(connInfo);
+    }
+
+}

Added: oozie/trunk/core/src/main/java/org/apache/oozie/jms/MessageHandler.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/jms/MessageHandler.java?rev=1449911&view=auto
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/jms/MessageHandler.java (added)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/jms/MessageHandler.java Mon Feb 25 21:42:07 2013
@@ -0,0 +1,29 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.oozie.jms;
+
+import javax.jms.Message;
+
+public interface MessageHandler {
+    /**
+     * Process a generic JMS message.
+     *
+     * @param msg : to be processed
+     */
+    public void process(Message msg);
+}

Added: oozie/trunk/core/src/main/java/org/apache/oozie/jms/MessageReceiver.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/jms/MessageReceiver.java?rev=1449911&view=auto
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/jms/MessageReceiver.java (added)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/jms/MessageReceiver.java Mon Feb 25 21:42:07 2013
@@ -0,0 +1,79 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.oozie.jms;
+
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.Session;
+
+import org.apache.oozie.util.XLog;
+
+public class MessageReceiver implements MessageListener {
+
+    private static XLog LOG = XLog.getLog(MessageReceiver.class);
+
+    private MessageHandler msgHandler;
+    private Session session;
+    private MessageConsumer consumer;
+
+    public MessageReceiver(MessageHandler handler, Session session, MessageConsumer consumer) {
+        this.msgHandler = handler;
+        this.session = session;
+        this.consumer = consumer;
+    }
+
+    /**
+     * Get the JMS message consumer object for this message receiver
+     *
+     * @return MessageConsumer
+     */
+    public MessageConsumer getConsumer() {
+        return this.consumer;
+    }
+
+    /**
+     * Get the MessageHandler that will process the message
+     *
+     * @return message handler
+     */
+    public MessageHandler getMessageHandler() {
+        return msgHandler;
+    }
+
+    /**
+     * Get the JMS session for this message receiver
+     *
+     * @return JMS session
+     */
+    public Session getSession() {
+        return session;
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
+     */
+    @Override
+    public void onMessage(Message msg) {
+        LOG.trace("Received a JMS message ");
+        msgHandler.process(msg);
+    }
+
+}

Added: oozie/trunk/core/src/main/java/org/apache/oozie/service/HCatAccessorException.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/service/HCatAccessorException.java?rev=1449911&view=auto
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/service/HCatAccessorException.java (added)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/service/HCatAccessorException.java Mon Feb 25 21:42:07 2013
@@ -0,0 +1,44 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.oozie.service;
+
+import org.apache.oozie.ErrorCode;
+import org.apache.oozie.XException;
+import org.apache.oozie.dependency.URIHandlerException;
+
+public class HCatAccessorException extends URIHandlerException {
+
+    /**
+     * Create an HCatAccessorException exception from a XException.
+     *
+     * @param cause the XException cause.
+     */
+    public HCatAccessorException(XException cause) {
+        super(cause);
+    }
+
+    /**
+     * Create a HCatAccessorException exception.
+     *
+     * @param errorCode error code.
+     * @param params parameters for the error code message template.
+     */
+    public HCatAccessorException(ErrorCode errorCode, Object... params) {
+        super(errorCode, params);
+    }
+}

Added: oozie/trunk/core/src/main/java/org/apache/oozie/service/HCatAccessorService.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/service/HCatAccessorService.java?rev=1449911&view=auto
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/service/HCatAccessorService.java (added)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/service/HCatAccessorService.java Mon Feb 25 21:42:07 2013
@@ -0,0 +1,207 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.oozie.service;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.oozie.dependency.hcat.HCatMessageHandler;
+import org.apache.oozie.jms.JMSConnectionInfo;
+import org.apache.oozie.util.HCatURI;
+import org.apache.oozie.util.MappingRule;
+import org.apache.oozie.util.XLog;
+
+public class HCatAccessorService implements Service {
+
+    public static final String CONF_PREFIX = Service.CONF_PREFIX + "HCatAccessorService.";
+    public static final String JMS_CONNECTIONS_PROPERTIES = CONF_PREFIX + "jmsconnections";
+
+    private static XLog LOG;
+    private static String DELIMITER = "#";
+    private Configuration conf;
+    private JMSAccessorService jmsService;
+    private List<MappingRule> mappingRules;
+    private JMSConnectionInfo defaultJMSConnInfo;
+    /**
+     * Map of publisher(host:port) to JMS connection info
+     */
+    private Map<String, JMSConnectionInfo> publisherJMSConnInfoMap;
+    /**
+     * List of non publishers(host:port)
+     */
+    private Set<String> nonJMSPublishers;
+    /**
+     * Mapping of table to the topic name for the table
+     */
+    private Map<String, String> registeredTopicsMap;
+
+    @Override
+    public void init(Services services) throws ServiceException {
+        LOG = XLog.getLog(getClass());
+        conf = services.getConf();
+        this.jmsService = services.get(JMSAccessorService.class);
+        initializeMappingRules();
+        this.nonJMSPublishers = new HashSet<String>();
+        this.publisherJMSConnInfoMap = new HashMap<String, JMSConnectionInfo>();
+        this.registeredTopicsMap = new HashMap<String, String>();
+    }
+
+    private void initializeMappingRules() {
+        String[] connections = conf.getStrings(JMS_CONNECTIONS_PROPERTIES);
+        if (connections != null) {
+            mappingRules = new ArrayList<MappingRule>(connections.length);
+            for (String connection : connections) {
+                String[] values = connection.split("=", 2);
+                String key = values[0].trim();
+                String value = values[1].trim();
+                if (key.equals("default")) {
+                    defaultJMSConnInfo = new JMSConnectionInfo(value);
+                }
+                else {
+                    mappingRules.add(new MappingRule(key, value));
+                }
+            }
+        }
+        else {
+            LOG.warn("No JMS connection defined");
+        }
+    }
+
+    /**
+     * Determine whether a given source URI publishes JMS messages
+     *
+     * @param sourceURI URI of the publisher
+     * @return true if we have JMS connection information for the source URI, else false
+     */
+    public boolean isKnownPublisher(URI sourceURI) {
+        if (nonJMSPublishers.contains(sourceURI.getAuthority())) {
+            return true;
+        }
+        else {
+            JMSConnectionInfo connInfo = publisherJMSConnInfoMap.get(sourceURI.getAuthority());
+            return connInfo == null ? (getJMSConnectionInfo(sourceURI) != null) : true;
+        }
+    }
+
+    /**
+     * Given a publisher host:port return the connection details of JMS server that the publisher
+     * publishes to
+     *
+     * @param publisherURI URI of the publisher
+     * @return JMSConnectionInfo to connect to the JMS server that the publisher publishes to
+     */
+    public JMSConnectionInfo getJMSConnectionInfo(URI publisherURI) {
+        String publisherAuthority = publisherURI.getAuthority();
+        JMSConnectionInfo connInfo = null;
+        if (publisherJMSConnInfoMap.containsKey(publisherAuthority)) {
+            connInfo = publisherJMSConnInfoMap.get(publisherAuthority);
+        }
+        else {
+            String schemeWithAuthority = publisherURI.getScheme() + "://" + publisherAuthority;
+            for (MappingRule mr : mappingRules) {
+                String jndiPropertiesString = mr.applyRule(schemeWithAuthority);
+                if (jndiPropertiesString != null) {
+                    connInfo = new JMSConnectionInfo(jndiPropertiesString);
+                    publisherJMSConnInfoMap.put(publisherAuthority, connInfo);
+                    LOG.info("Adding hcat server [{0}] to the list of JMS publishers", schemeWithAuthority);
+                    break;
+                }
+            }
+            if (connInfo == null && defaultJMSConnInfo != null) {
+                connInfo = defaultJMSConnInfo;
+                publisherJMSConnInfoMap.put(publisherAuthority, defaultJMSConnInfo);
+                LOG.info("Adding hcat server [{0}] to the list of JMS publishers", schemeWithAuthority);
+            }
+            else {
+                nonJMSPublishers.add(publisherAuthority);
+                LOG.info("Adding hcat server [{0}] to the list of non JMS publishers", schemeWithAuthority);
+            }
+
+        }
+        return connInfo;
+    }
+
+    /**
+     * Check if we are already listening to the JMS topic for the table in the given hcatURI
+     *
+     * @param hcatURI hcatalog partition URI
+     * @return true if registered to a JMS topic for the table in the given hcatURI
+     */
+    public boolean isRegisteredForNotification(HCatURI hcatURI) {
+        return registeredTopicsMap.containsKey(getKeyForRegisteredTopicsMap(hcatURI));
+    }
+
+    /**
+     * Register for notifications on a JMS topic for the specified hcatalog table.
+     *
+     * @param hcatURI hcatalog partition URI
+     * @param topic JMS topic to register to
+     * @param msgHandler Handler which will process the messages received on the topic
+     */
+    public void registerForNotification(HCatURI hcatURI, String topic, HCatMessageHandler msgHandler) {
+        JMSConnectionInfo connInfo = getJMSConnectionInfo(hcatURI.getURI());
+        jmsService.registerForNotification(connInfo, topic, msgHandler);
+        registeredTopicsMap.put(
+                getKeyForRegisteredTopicsMap(hcatURI), topic);
+    }
+
+    public void unregisterFromNotification(HCatURI hcatURI) {
+        String topic = registeredTopicsMap.remove(getKeyForRegisteredTopicsMap(hcatURI));
+        if (topic != null) {
+            JMSConnectionInfo connInfo = getJMSConnectionInfo(hcatURI.getURI());
+            jmsService.unregisterFromNotification(connInfo, topic);
+        }
+    }
+
+    public void unregisterFromNotification(String server, String database, String table) {
+        String key = server + DELIMITER + database + DELIMITER + table;
+        String topic = registeredTopicsMap.remove(key);
+        if (topic != null) {
+            try {
+                JMSConnectionInfo connInfo = getJMSConnectionInfo(new URI("hcat://" + server));
+                jmsService.unregisterFromNotification(connInfo, topic);
+            }
+            catch (URISyntaxException e) {
+                LOG.warn("Error unregistering from notification for topic [{0}]. Hcat table=[{1}]", topic, key, e);
+            }
+        }
+    }
+
+    private String getKeyForRegisteredTopicsMap(HCatURI hcatURI) {
+        return hcatURI.getURI().getAuthority() + DELIMITER + hcatURI.getDb()
+                + DELIMITER + hcatURI.getTable();
+    }
+
+    @Override
+    public void destroy() {
+        publisherJMSConnInfoMap.clear();
+    }
+
+    @Override
+    public Class<? extends Service> getInterface() {
+        return HCatAccessorService.class;
+    }
+
+}

Modified: oozie/trunk/core/src/main/java/org/apache/oozie/service/HadoopAccessorException.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/service/HadoopAccessorException.java?rev=1449911&r1=1449910&r2=1449911&view=diff
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/service/HadoopAccessorException.java (original)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/service/HadoopAccessorException.java Mon Feb 25 21:42:07 2013
@@ -6,9 +6,9 @@
  * to you 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.
@@ -19,12 +19,13 @@ package org.apache.oozie.service;
 
 import org.apache.oozie.XException;
 import org.apache.oozie.ErrorCode;
+import org.apache.oozie.dependency.URIHandlerException;
 
-public class HadoopAccessorException extends XException {
+public class HadoopAccessorException extends URIHandlerException {
 
     /**
      * Create an HadoopAccessor exception from a XException.
-     * 
+     *
      * @param cause the XException cause.
      */
     public HadoopAccessorException(XException cause) {
@@ -33,7 +34,7 @@ public class HadoopAccessorException ext
 
     /**
      * Create a HadoopAccessor exception.
-     * 
+     *
      * @param errorCode error code.
      * @param params parameters for the error code message template.
      */

Modified: oozie/trunk/core/src/main/java/org/apache/oozie/service/HadoopAccessorService.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/service/HadoopAccessorService.java?rev=1449911&r1=1449910&r2=1449911&view=diff
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/service/HadoopAccessorService.java (original)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/service/HadoopAccessorService.java Mon Feb 25 21:42:07 2013
@@ -47,7 +47,6 @@ import java.util.Map;
 import java.util.Set;
 import java.util.HashSet;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
 
 /**
  * The HadoopAccessorService returns HadoopAccessor instances configured to work on behalf of a user-group. <p/> The
@@ -85,15 +84,18 @@ public class HadoopAccessorService imple
     private Map<String, File> actionConfigDirs = new HashMap<String, File>();
     private Map<String, Map<String, XConfiguration>> actionConfigs = new HashMap<String, Map<String, XConfiguration>>();
 
-    private ConcurrentMap<String, UserGroupInformation> userUgiMap;
+    private UserGroupInformationService ugiService;
 
     /**
      * Supported filesystem schemes for namespace federation
      */
     public static final String SUPPORTED_FILESYSTEMS = CONF_PREFIX + "supported.filesystems";
+    public static final String[] DEFAULT_SUPPORTED_SCHEMES = new String[]{"hdfs","hftp","webhdfs"};
     private Set<String> supportedSchemes;
+    private boolean allSchemesSupported;
 
     public void init(Services services) throws ServiceException {
+        this.ugiService = services.get(UserGroupInformationService.class);
         init(services.getConf());
     }
 
@@ -131,13 +133,15 @@ public class HadoopAccessorService imple
             UserGroupInformation.setConfiguration(ugiConf);
         }
 
-        userUgiMap = new ConcurrentHashMap<String, UserGroupInformation>();
+        if (ugiService == null) { //for testing purposes, see XFsTestCase
+            this.ugiService = new UserGroupInformationService();
+        }
 
         loadHadoopConfigs(conf);
         preLoadActionConfigs(conf);
 
         supportedSchemes = new HashSet<String>();
-        String[] schemesFromConf = conf.getStrings(SUPPORTED_FILESYSTEMS, new String[]{"hdfs","hftp","webhdfs"});
+        String[] schemesFromConf = conf.getStrings(SUPPORTED_FILESYSTEMS, DEFAULT_SUPPORTED_SCHEMES);
         if(schemesFromConf != null) {
             for (String scheme: schemesFromConf) {
                 scheme = scheme.trim();
@@ -147,9 +151,9 @@ public class HadoopAccessorService imple
                         throw new ServiceException(ErrorCode.E0100, getClass().getName(),
                             SUPPORTED_FILESYSTEMS + " should contain either only wildcard or explicit list, not both");
                     }
-                } else {
-                    supportedSchemes.add(scheme);
+                    allSchemesSupported = true;
                 }
+                supportedSchemes.add(scheme);
             }
         }
     }
@@ -267,13 +271,7 @@ public class HadoopAccessorService imple
     }
 
     private UserGroupInformation getUGI(String user) throws IOException {
-        UserGroupInformation ugi = userUgiMap.get(user);
-        if (ugi == null) {
-            // taking care of a race condition, the latest UGI will be discarded
-            ugi = UserGroupInformation.createProxyUser(user, UserGroupInformation.getLoginUser());
-            userUgiMap.putIfAbsent(user, ugi);
-        }
-        return ugi;
+        return ugiService.getProxyUser(user);
     }
 
     /**
@@ -527,6 +525,8 @@ public class HadoopAccessorService imple
      */
 
     public void checkSupportedFilesystem(URI uri) throws HadoopAccessorException {
+        if (allSchemesSupported)
+            return;
         String uriScheme = uri.getScheme();
         if (uriScheme != null) {    // skip the check if no scheme is given
             if(!supportedSchemes.isEmpty()) {
@@ -534,8 +534,12 @@ public class HadoopAccessorService imple
                 if (!supportedSchemes.contains(uriScheme)) {
                     throw new HadoopAccessorException(ErrorCode.E0904, uriScheme, uri.toString());
                 }
-            }
-        }
+             }
+         }
+    }
+
+    public Set<String> getSupportedSchemes() {
+        return supportedSchemes;
     }
 
 }

Added: oozie/trunk/core/src/main/java/org/apache/oozie/service/JMSAccessorService.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/service/JMSAccessorService.java?rev=1449911&view=auto
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/service/JMSAccessorService.java (added)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/service/JMSAccessorService.java Mon Feb 25 21:42:07 2013
@@ -0,0 +1,463 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.oozie.service;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import javax.jms.JMSException;
+import javax.jms.MessageConsumer;
+import javax.jms.Session;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.util.ReflectionUtils;
+import org.apache.oozie.jms.ConnectionContext;
+import org.apache.oozie.jms.DefaultConnectionContext;
+import org.apache.oozie.jms.JMSConnectionInfo;
+import org.apache.oozie.jms.JMSExceptionListener;
+import org.apache.oozie.jms.MessageHandler;
+import org.apache.oozie.jms.MessageReceiver;
+import org.apache.oozie.util.XLog;
+
+import com.google.common.annotations.VisibleForTesting;
+
+/**
+ * This class will <ul>
+ * <li> Create/Manage JMS connections using user configured JNDI properties. </li>
+ * <li> Create/Manage session for specific connection/topic and reconnects on failures. </li>
+ * <li> Provide a way to create a subscriber and publisher </li>
+ * <li> Pure JMS compliant (implementation independent but primarily tested against Apache ActiveMQ). </li>
+ * </ul>
+ */
+public class JMSAccessorService implements Service {
+    public static final String CONF_PREFIX = Service.CONF_PREFIX + "JMSAccessorService.";
+    public static final String JMS_CONNECTION_CONTEXT_IMPL = CONF_PREFIX + "connectioncontext.impl";
+    public static final String SESSION_OPTS = CONF_PREFIX + "jms.sessionOpts";
+    public static final String CONF_RETRY_INITIAL_DELAY = CONF_PREFIX + "retry.initial.delay";
+    public static final String CONF_RETRY_MULTIPLIER = CONF_PREFIX + "retry.multiplier";
+    public static final String CONF_RETRY_MAX_ATTEMPTS = CONF_PREFIX + "retry.max.attempts";
+    private static XLog LOG;
+
+    private Configuration conf;
+    private int sessionOpts;
+    private int retryInitialDelay;
+    private int retryMultiplier;
+    private int retryMaxAttempts;
+
+    /**
+     * Map of JMS connection info to established JMS Connection
+     */
+    private ConcurrentMap<JMSConnectionInfo, ConnectionContext> connectionMap =
+            new ConcurrentHashMap<JMSConnectionInfo, ConnectionContext>();
+    /**
+     * Map of JMS connection info to topic names to MessageReceiver
+     */
+    private ConcurrentMap<JMSConnectionInfo, Map<String, MessageReceiver>> receiversMap =
+            new ConcurrentHashMap<JMSConnectionInfo, Map<String, MessageReceiver>>();
+
+    /**
+     * Map of JMS connection info to connection retry information
+     */
+    private Map<JMSConnectionInfo, ConnectionRetryInfo> retryConnectionsMap = new HashMap<JMSConnectionInfo, ConnectionRetryInfo>();
+
+    @Override
+    public void init(Services services) throws ServiceException {
+        LOG = XLog.getLog(getClass());
+        conf = services.getConf();
+        sessionOpts = conf.getInt(SESSION_OPTS, Session.AUTO_ACKNOWLEDGE);
+        retryInitialDelay = conf.getInt(CONF_RETRY_INITIAL_DELAY, 60); // initial delay in seconds
+        retryMultiplier = conf.getInt(CONF_RETRY_MULTIPLIER, 2);
+        retryMaxAttempts = conf.getInt(CONF_RETRY_MAX_ATTEMPTS, 10);
+    }
+
+    /**
+     * Register for notifications on a JMS topic.
+     *
+     * @param connInfo Information to connect to a JMS compliant messaging service.
+     * @param topic Topic in which the JMS messages are published
+     * @param msgHandler Handler which will process the messages received on the topic
+     */
+    public void registerForNotification(JMSConnectionInfo connInfo, String topic, MessageHandler msgHandler) {
+        if (!isTopicInRetryList(connInfo, topic)) {
+            if (isConnectionInRetryList(connInfo)) {
+                queueTopicForRetry(connInfo, topic, msgHandler);
+            }
+            else {
+                Map<String, MessageReceiver> topicsMap = getReceiversTopicsMap(connInfo);
+                if (!topicsMap.containsKey(topic)) {
+                    synchronized (topicsMap) {
+                        if (!topicsMap.containsKey(topic)) {
+                            ConnectionContext connCtxt = createConnectionContext(connInfo);
+                            if (connCtxt == null) {
+                                queueTopicForRetry(connInfo, topic, msgHandler);
+                                return;
+                            }
+                            MessageReceiver receiver = registerForTopic(connInfo, connCtxt, topic, msgHandler);
+                            if (receiver == null) {
+                                queueTopicForRetry(connInfo, topic, msgHandler);
+                            }
+                            else {
+                                LOG.info("Registered a listener for topic {0} on {1}", topic, connInfo);
+                                topicsMap.put(topic, receiver);
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * Unregister from listening to JMS messages on a topic.
+     *
+     * @param connInfo Information to connect to the JMS compliant messaging service.
+     * @param topic Topic in which the JMS messages are published
+     */
+    public void unregisterFromNotification(JMSConnectionInfo connInfo, String topic) {
+        LOG.info("Unregistering JMS listener. Clossing session for {0} and topic {1}", connInfo, topic);
+
+        if (isTopicInRetryList(connInfo, topic)) {
+            removeTopicFromRetryList(connInfo, topic);
+        }
+        else {
+            Map<String, MessageReceiver> topicsMap = receiversMap.get(connInfo);
+            if (topicsMap != null) {
+                MessageReceiver receiver = null;
+                synchronized (topicsMap) {
+                    receiver = topicsMap.remove(topic);
+                    if (topicsMap.isEmpty()) {
+                        receiversMap.remove(connInfo);
+                    }
+                }
+                if (receiver != null) {
+                    try {
+                        receiver.getSession().close();
+                    }
+                    catch (JMSException e) {
+                        LOG.warn("Unable to close session " + receiver.getSession(), e);
+                    }
+                }
+                else {
+                    LOG.warn("Received request to unregister from topic [{0}] on [{1}], but no matching session.",
+                            topic, connInfo);
+                }
+            }
+        }
+    }
+
+    private Map<String, MessageReceiver> getReceiversTopicsMap(JMSConnectionInfo connInfo) {
+        Map<String, MessageReceiver> topicsMap = receiversMap.get(connInfo);
+        if (topicsMap == null) {
+            topicsMap = new HashMap<String, MessageReceiver>();
+            Map<String, MessageReceiver> exists = receiversMap.putIfAbsent(connInfo, topicsMap);
+            if (exists != null) {
+                topicsMap = exists;
+            }
+        }
+        return topicsMap;
+    }
+
+    /**
+     * Determine if currently listening to JMS messages on a topic.
+     *
+     * @param connInfo Information to connect to the JMS compliant messaging service.
+     * @param topic Topic in which the JMS messages are published
+     * @return true if listening to the topic, else false
+     */
+    @VisibleForTesting
+    boolean isListeningToTopic(JMSConnectionInfo connInfo, String topic) {
+        Map<String, MessageReceiver> topicsMap = receiversMap.get(connInfo);
+        return (topicsMap != null && topicsMap.containsKey(topic));
+    }
+
+    @VisibleForTesting
+    boolean isConnectionInRetryList(JMSConnectionInfo connInfo) {
+        return retryConnectionsMap.containsKey(connInfo);
+    }
+
+    @VisibleForTesting
+    boolean isTopicInRetryList(JMSConnectionInfo connInfo, String topic) {
+        ConnectionRetryInfo connRetryInfo = retryConnectionsMap.get(connInfo);
+        if (connRetryInfo == null) {
+            return false;
+        }
+        else {
+            Map<String, MessageHandler> topicsMap = connRetryInfo.getTopicsToRetry();
+            return topicsMap.containsKey(topic);
+        }
+    }
+
+    // For unit testing
+    @VisibleForTesting
+    int getNumConnectionAttempts(JMSConnectionInfo connInfo) {
+        return retryConnectionsMap.get(connInfo).getNumAttempt();
+    }
+
+    private ConnectionRetryInfo queueConnectionForRetry(JMSConnectionInfo connInfo) {
+        ConnectionRetryInfo connRetryInfo = retryConnectionsMap.get(connInfo);
+        if (connRetryInfo == null) {
+            LOG.info("Queueing connection {0} for retry", connInfo);
+            connRetryInfo = new ConnectionRetryInfo(0, retryInitialDelay);
+            retryConnectionsMap.put(connInfo, connRetryInfo);
+            scheduleRetry(connInfo, retryInitialDelay);
+        }
+        return connRetryInfo;
+    }
+
+    private ConnectionRetryInfo queueTopicForRetry(JMSConnectionInfo connInfo, String topic, MessageHandler msgHandler) {
+        LOG.info("Queueing topic {0} for {1} for retry", topic, connInfo);
+        ConnectionRetryInfo connRetryInfo = queueConnectionForRetry(connInfo);
+        Map<String, MessageHandler> topicsMap = connRetryInfo.getTopicsToRetry();
+        topicsMap.put(topic, msgHandler);
+        return connRetryInfo;
+    }
+
+    private void removeTopicFromRetryList(JMSConnectionInfo connInfo, String topic) {
+        LOG.info("Removing topic {0} from {1} from retry list", topic, connInfo);
+        ConnectionRetryInfo connRetryInfo = retryConnectionsMap.get(connInfo);
+        if (connRetryInfo != null) {
+            Map<String, MessageHandler> topicsMap = connRetryInfo.getTopicsToRetry();
+            topicsMap.remove(topic);
+        }
+    }
+
+    private MessageReceiver registerForTopic(JMSConnectionInfo connInfo, ConnectionContext connCtxt, String topic,
+            MessageHandler msgHandler) {
+        try {
+            Session session = connCtxt.createSession(sessionOpts);
+            MessageConsumer consumer = connCtxt.createConsumer(session, topic);
+            MessageReceiver receiver = new MessageReceiver(msgHandler, session, consumer);
+            consumer.setMessageListener(receiver);
+            return receiver;
+        }
+        catch (JMSException e) {
+            LOG.warn("Error while registering to listen to topic {0} from {1}", topic, connInfo, e);
+            return null;
+        }
+    }
+
+    protected ConnectionContext createConnectionContext(JMSConnectionInfo connInfo) {
+        ConnectionContext connCtxt = connectionMap.get(connInfo);
+        if (connCtxt == null) {
+            try {
+                connCtxt = getConnectionContextImpl();
+                connCtxt.createConnection(connInfo.getJNDIProperties());
+                connCtxt.setExceptionListener(new JMSExceptionListener(connInfo, connCtxt));
+                connectionMap.put(connInfo, connCtxt);
+                LOG.info("Connection established to JMS Server for [{0}]", connInfo);
+            }
+            catch (Exception e) {
+                LOG.warn("Exception while establishing connection to JMS Server for [{0}]", connInfo, e);
+                return null;
+            }
+        }
+        return connCtxt;
+    }
+
+    private ConnectionContext getConnectionContextImpl() {
+        Class<?> defaultClazz = conf.getClass(JMS_CONNECTION_CONTEXT_IMPL, DefaultConnectionContext.class);
+        ConnectionContext connCtx = null;
+        if (defaultClazz == DefaultConnectionContext.class) {
+            connCtx = new DefaultConnectionContext();
+        }
+        else {
+            connCtx = (ConnectionContext) ReflectionUtils.newInstance(defaultClazz, null);
+        }
+        return connCtx;
+    }
+
+    @VisibleForTesting
+    MessageReceiver getMessageReceiver(JMSConnectionInfo connInfo, String topic) {
+        Map<String, MessageReceiver> topicsMap = receiversMap.get(connInfo);
+        if (topicsMap != null) {
+            return topicsMap.get(topic);
+        }
+        return null;
+    }
+
+    @Override
+    public void destroy() {
+        LOG.info("Destroying JMSAccessor service ");
+        LOG.info("Closing JMS sessions");
+        for (Map<String, MessageReceiver> topicsMap : receiversMap.values()) {
+            for (MessageReceiver receiver : topicsMap.values()) {
+                try {
+                    receiver.getSession().close();
+                }
+                catch (JMSException e) {
+                    LOG.warn("Unable to close session " + receiver.getSession(), e);
+                }
+            }
+        }
+        receiversMap.clear();
+
+        LOG.info("Closing JMS connections");
+        for (ConnectionContext conn : connectionMap.values()) {
+            conn.close();
+        }
+        connectionMap.clear();
+    }
+
+    @Override
+    public Class<? extends Service> getInterface() {
+        return JMSAccessorService.class;
+    }
+
+    /**
+     * Reestablish connection for the given JMS connect information
+     * @param connInfo JMS connection info
+     */
+    public void reestablishConnection(JMSConnectionInfo connInfo) {
+        connectionMap.remove(connInfo);
+        // Queue the connection and topics for retry
+        ConnectionRetryInfo connRetryInfo = queueConnectionForRetry(connInfo);
+        Map<String, MessageReceiver> listeningTopicsMap = receiversMap.remove(connInfo);
+        if (listeningTopicsMap != null) {
+            Map<String, MessageHandler> retryTopicsMap = connRetryInfo.getTopicsToRetry();
+            for (Entry<String, MessageReceiver> topicEntry : listeningTopicsMap.entrySet()) {
+                MessageReceiver receiver = topicEntry.getValue();
+                retryTopicsMap.put(topicEntry.getKey(), receiver.getMessageHandler());
+                try {
+                    receiver.getSession().close();
+                }
+                catch (JMSException e) {
+                    LOG.warn("Unable to close session " + receiver.getSession(), e);
+                }
+            }
+        }
+    }
+
+    private void scheduleRetry(JMSConnectionInfo connInfo, long delay) {
+        LOG.info("Scheduling retry of connection [{0}] in [{1}] seconds", connInfo, delay);
+        JMSRetryRunnable runnable = new JMSRetryRunnable(connInfo);
+        SchedulerService scheduler = Services.get().get(SchedulerService.class);
+        scheduler.schedule(runnable, delay, SchedulerService.Unit.SEC);
+    }
+
+    @VisibleForTesting
+    boolean retryConnection(JMSConnectionInfo connInfo) {
+        ConnectionRetryInfo connRetryInfo = retryConnectionsMap.get(connInfo);
+        if (connRetryInfo.getNumAttempt() >= retryMaxAttempts) {
+            LOG.info("Not attempting connection [{0}] again. Reached max attempts [{1}]", connInfo, retryMaxAttempts);
+            return false;
+        }
+        LOG.info("Attempting retry of connection [{0}]", connInfo);
+        connRetryInfo.setNumAttempt(connRetryInfo.getNumAttempt() + 1);
+        connRetryInfo.setNextDelay(connRetryInfo.getNextDelay() * retryMultiplier);
+        ConnectionContext connCtxt = createConnectionContext(connInfo);
+        boolean shouldRetry = false;
+        if (connCtxt == null) {
+            shouldRetry = true;
+        }
+        else {
+            Map<String, MessageHandler> retryTopicsMap = connRetryInfo.getTopicsToRetry();
+            Map<String, MessageReceiver> listeningTopicsMap = getReceiversTopicsMap(connInfo);
+            List<String> topicsToRemoveList = new ArrayList<String>();
+            // For each topic in the retry list, try to register the MessageHandler for that topic
+            for (Entry<String, MessageHandler> topicEntry : retryTopicsMap.entrySet()) {
+                String topic = topicEntry.getKey();
+                if (listeningTopicsMap.containsKey(topic)) {
+                    continue;
+                }
+                synchronized (listeningTopicsMap) {
+                    if (!listeningTopicsMap.containsKey(topic)) {
+                        MessageReceiver receiver = registerForTopic(connInfo, connCtxt, topic, topicEntry.getValue());
+                        if (receiver == null) {
+                            LOG.warn("Failed to register a listener for topic {0} on {1}", topic, connInfo);
+                        }
+                        else {
+                            listeningTopicsMap.put(topic, receiver);
+                            topicsToRemoveList.add(topic);
+                            LOG.info("Registered a listener for topic {0} on {1}", topic, connInfo);
+                        }
+                    }
+                }
+            }
+            for (String topic : topicsToRemoveList) {
+                retryTopicsMap.remove(topic);
+            }
+            if (retryTopicsMap.isEmpty()) {
+                shouldRetry = false;
+            }
+        }
+
+        if (shouldRetry) {
+            scheduleRetry(connInfo, connRetryInfo.getNextDelay());
+        }
+        else {
+            retryConnectionsMap.remove(connInfo);
+        }
+        return true;
+    }
+
+    private static class ConnectionRetryInfo {
+        private int numAttempt;
+        private int nextDelay;
+        private Map<String, MessageHandler> retryTopicsMap;
+
+        public ConnectionRetryInfo(int numAttempt, int nextDelay) {
+            this.numAttempt = numAttempt;
+            this.nextDelay = nextDelay;
+            this.retryTopicsMap = new HashMap<String, MessageHandler>();
+        }
+
+        public int getNumAttempt() {
+            return numAttempt;
+        }
+
+        public void setNumAttempt(int numAttempt) {
+            this.numAttempt = numAttempt;
+        }
+
+        public int getNextDelay() {
+            return nextDelay;
+        }
+
+        public void setNextDelay(int nextDelay) {
+            this.nextDelay = nextDelay;
+        }
+
+        public Map<String, MessageHandler> getTopicsToRetry() {
+            return retryTopicsMap;
+        }
+
+    }
+
+    public class JMSRetryRunnable implements Runnable {
+
+        private JMSConnectionInfo connInfo;
+
+        public JMSRetryRunnable(JMSConnectionInfo connInfo) {
+            this.connInfo = connInfo;
+        }
+
+        public JMSConnectionInfo getJMSConnectionInfo() {
+            return connInfo;
+        }
+
+        @Override
+        public void run() {
+            retryConnection(connInfo);
+        }
+
+    }
+
+}

Added: oozie/trunk/core/src/main/java/org/apache/oozie/service/PartitionDependencyManagerService.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/service/PartitionDependencyManagerService.java?rev=1449911&view=auto
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/service/PartitionDependencyManagerService.java (added)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/service/PartitionDependencyManagerService.java Mon Feb 25 21:42:07 2013
@@ -0,0 +1,145 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.oozie.service;
+
+import java.util.Collection;
+import java.util.Map;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.util.ReflectionUtils;
+import org.apache.oozie.command.coord.CoordActionUpdatePushMissingDependency;
+import org.apache.oozie.dependency.hcat.HCatDependencyCache;
+import org.apache.oozie.dependency.hcat.SimpleHCatDependencyCache;
+import org.apache.oozie.util.HCatURI;
+import org.apache.oozie.util.XLog;
+
+/**
+ * Module that functions like a caching service to maintain partition dependency mappings
+ */
+public class PartitionDependencyManagerService implements Service {
+
+    public static final String CONF_PREFIX = Service.CONF_PREFIX + "PartitionDependencyManagerService.";
+    public static final String CACHE_MANAGER_IMPL = CONF_PREFIX + "cache.manager.impl";
+
+    private static XLog LOG = XLog.getLog(PartitionDependencyManagerService.class);
+
+    private HCatDependencyCache dependencyCache;
+
+    @Override
+    public void init(Services services) throws ServiceException {
+        init(services.getConf());
+    }
+
+    private void init(Configuration conf) throws ServiceException {
+        Class<?> defaultClass = conf.getClass(CACHE_MANAGER_IMPL, null);
+        dependencyCache = (defaultClass == null) ? new SimpleHCatDependencyCache()
+                : (HCatDependencyCache) ReflectionUtils.newInstance(defaultClass, null);
+        dependencyCache.init(conf);
+        LOG.info("PartitionDependencyManagerService initialized. Dependency cache is {0} ", dependencyCache.getClass()
+                .getName());
+    }
+
+    @Override
+    public void destroy() {
+        dependencyCache.destroy();
+    }
+
+    @Override
+    public Class<? extends Service> getInterface() {
+        return PartitionDependencyManagerService.class;
+    }
+
+    /**
+     * Add a missing partition dependency and the actionID waiting on it
+     *
+     * @param hcatURI dependency URI
+     * @param actionID ID of action which is waiting for the dependency
+     */
+    public void addMissingDependency(HCatURI hcatURI, String actionID) {
+        dependencyCache.addMissingDependency(hcatURI, actionID);
+    }
+
+    /**
+     * Remove a missing partition dependency associated with a actionID
+     *
+     * @param hcatURI dependency URI
+     * @param actionID ID of action which is waiting for the dependency
+     * @return true if successful, else false
+     */
+    public boolean removeMissingDependency(HCatURI hcatURI, String actionID) {
+        return dependencyCache.removeMissingDependency(hcatURI, actionID);
+    }
+
+    /**
+     * Get the list of actionIDs waiting for a partition
+     *
+     * @param hcatURI dependency URI
+     * @return list of actionIDs
+     */
+    public Collection<String> getWaitingActions(HCatURI hcatURI) {
+        return dependencyCache.getWaitingActions(hcatURI);
+    }
+
+    /**
+     * Mark a partition dependency as available
+     *
+     * @param server host:port of the server
+     * @param db name of the database
+     * @param table name of the table
+     * @param partitions list of available partitions
+     * @return list of actionIDs for which the dependency is now available
+     */
+    public void partitionAvailable(String server, String db, String table, Map<String, String> partitions) {
+        Collection<String> actionsWithAvailableDep = dependencyCache.markDependencyAvailable(server, db, table,
+                partitions);
+        if (actionsWithAvailableDep != null) {
+            for (String actionID : actionsWithAvailableDep) {
+                boolean ret = Services.get().get(CallableQueueService.class)
+                        .queue(new CoordActionUpdatePushMissingDependency(actionID), 100);
+                if (ret == false) {
+                    XLog.getLog(getClass()).warn(
+                            "Unable to queue the callable commands for PartitionDependencyManagerService for actionID "
+                                    + actionID + ".Most possibly command queue is full. Queue size is :"
+                                    + Services.get().get(CallableQueueService.class).queueSize());
+                }
+            }
+        }
+    }
+
+    /**
+     * Get a list of available dependency URIs for a actionID
+     *
+     * @param actionID action id
+     * @return list of available dependency URIs
+     */
+    public Collection<String> getAvailableDependencyURIs(String actionID) {
+        return dependencyCache.getAvailableDependencyURIs(actionID);
+    }
+
+    /**
+     * Remove the list of available dependency URIs for a actionID once the missing dependencies are processed.
+     *
+     * @param actionID action id
+     * @param dependencyURIs set of dependency URIs
+     * @return true if successful, else false
+     */
+    public boolean removeAvailableDependencyURIs(String actionID, Collection<String> dependencyURIs) {
+        return dependencyCache.removeAvailableDependencyURIs(actionID, dependencyURIs);
+    }
+
+}

Modified: oozie/trunk/core/src/main/java/org/apache/oozie/service/RecoveryService.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/service/RecoveryService.java?rev=1449911&r1=1449910&r2=1449911&view=diff
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/service/RecoveryService.java (original)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/service/RecoveryService.java Mon Feb 25 21:42:07 2013
@@ -37,6 +37,7 @@ import org.apache.oozie.command.coord.Co
 import org.apache.oozie.command.coord.CoordActionReadyXCommand;
 import org.apache.oozie.command.coord.CoordActionStartXCommand;
 import org.apache.oozie.command.coord.CoordKillXCommand;
+import org.apache.oozie.command.coord.CoordPushDependencyCheckXCommand;
 import org.apache.oozie.command.coord.CoordResumeXCommand;
 import org.apache.oozie.command.coord.CoordSubmitXCommand;
 import org.apache.oozie.command.coord.CoordSuspendXCommand;
@@ -60,7 +61,6 @@ import org.apache.oozie.util.XLog;
 import org.apache.oozie.util.XmlUtils;
 import org.jdom.Attribute;
 import org.jdom.Element;
-import org.jdom.JDOMException;
 
 /**
  * The Recovery Service checks for pending actions and premater coordinator jobs older than a configured age and then
@@ -80,6 +80,12 @@ public class RecoveryService implements 
      * The number of callables to be queued in a batch.
      */
     public static final String CONF_CALLABLE_BATCH_SIZE = CONF_PREFIX + "callable.batch.size";
+
+    /**
+     * Delay for the push missing dependencies in milliseconds.
+     */
+    public static final String CONF_PUSH_DEPENDENCY_INTERVAL = CONF_PREFIX + "push.dependency.interval";
+
     /**
      * Age of actions to queue, in seconds.
      */
@@ -210,7 +216,6 @@ public class RecoveryService implements 
                 }
             }
 
-
         }
 
         /**
@@ -219,6 +224,8 @@ public class RecoveryService implements 
         private void runCoordActionRecovery() {
             XLog.Info.get().clear();
             XLog log = XLog.getLog(getClass());
+            long pushMissingDepInterval = Services.get().getConf().getLong(CONF_PUSH_DEPENDENCY_INTERVAL, 200);
+            long pushMissingDepDelay = pushMissingDepInterval;
             List<CoordinatorActionBean> cactions = null;
             try {
                 cactions = jpaService.execute(new CoordActionsGetForRecoveryJPAExecutor(coordOlderThan));
@@ -234,9 +241,16 @@ public class RecoveryService implements 
                             .incr(INSTRUMENTATION_GROUP, INSTR_RECOVERED_COORD_ACTIONS_COUNTER, 1);
                     if (caction.getStatus() == CoordinatorActionBean.Status.WAITING) {
                         queueCallable(new CoordActionInputCheckXCommand(caction.getId(), caction.getJobId()));
-
-                        log.info("Recover a WAITTING coord action and resubmit CoordActionInputCheckXCommand :"
+                        log.info("Recover a WAITING coord action and resubmit CoordActionInputCheckXCommand :"
                                 + caction.getId());
+                        if (caction.getPushMissingDependencies() != null
+                                && caction.getPushMissingDependencies().length() != 0) {
+                            queueCallable(new CoordPushDependencyCheckXCommand(caction.getId(), true),
+                                    pushMissingDepDelay);
+                            pushMissingDepDelay = pushMissingDepDelay + pushMissingDepInterval;
+                            log.info("Recover a WAITING coord action and resubmit CoordPushDependencyCheckX :"
+                                    + caction.getId());
+                        }
                     }
                     else if (caction.getStatus() == CoordinatorActionBean.Status.SUBMITTED) {
                         CoordinatorJobBean coordJob = jpaService

Modified: oozie/trunk/core/src/main/java/org/apache/oozie/service/SchedulerService.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/service/SchedulerService.java?rev=1449911&r1=1449910&r2=1449911&view=diff
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/service/SchedulerService.java (original)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/service/SchedulerService.java Mon Feb 25 21:42:07 2013
@@ -6,9 +6,9 @@
  * to you 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.
@@ -178,4 +178,37 @@ public class SchedulerService implements
         }
     }
 
+    /**
+     * Schedule a Runnable for execution.
+     *
+     * @param runnable Runnable to schedule for execution.
+     * @param delay the time from now to delay execution.
+     * @param unit scheduling unit.
+     */
+    public void schedule(final Runnable runnable, long delay, Unit unit) {
+        log.trace("Scheduling runnable [{0}], delay [{1}] in [{2}]",
+                  runnable.getClass(), delay, unit);
+        Runnable r = new Runnable() {
+            public void run() {
+                if (Services.get().getSystemMode() == SYSTEM_MODE.SAFEMODE) {
+                    log.trace("schedule[run/Runnable] System is in SAFEMODE. Therefore nothing will run");
+                    return;
+                }
+                try {
+                    runnable.run();
+                }
+                catch (Exception ex) {
+                    log.warn("Error executing runnable [{0}], {1}", runnable.getClass().getSimpleName(),
+                             ex.getMessage(), ex);
+                }
+            }
+        };
+        if (!scheduler.isShutdown()) {
+            scheduler.schedule(r, delay * unit.getMillis(), TimeUnit.MILLISECONDS);
+        }
+        else {
+            log.warn("Scheduler shutting down, ignoring scheduling of [{0}]", runnable.getClass());
+        }
+    }
+
 }

Added: oozie/trunk/core/src/main/java/org/apache/oozie/service/URIHandlerService.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/service/URIHandlerService.java?rev=1449911&view=auto
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/service/URIHandlerService.java (added)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/service/URIHandlerService.java Mon Feb 25 21:42:07 2013
@@ -0,0 +1,219 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.oozie.service;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.util.ReflectionUtils;
+import org.apache.oozie.ErrorCode;
+import org.apache.oozie.action.hadoop.LauncherURIHandler;
+import org.apache.oozie.action.hadoop.LauncherURIHandlerFactory;
+import org.apache.oozie.dependency.FSURIHandler;
+import org.apache.oozie.dependency.URIHandler;
+import org.apache.oozie.dependency.URIHandlerException;
+import org.apache.oozie.util.XLog;
+
+public class URIHandlerService implements Service {
+
+    private static final String CONF_PREFIX = Service.CONF_PREFIX + "URIHandlerService.";
+    public static final String URI_HANDLERS = CONF_PREFIX + "uri.handlers";
+    public static final String URI_HANDLER_DEFAULT = CONF_PREFIX + "uri.handler.default";
+    public static final String URI_HANDLER_SUPPORTED_SCHEMES_PREFIX = CONF_PREFIX + "uri.handler.";
+    public static final String URI_HANDLER_SUPPORTED_SCHEMES_SUFFIX = ".supported.schemes";
+
+    private static XLog LOG = XLog.getLog(URIHandlerService.class);
+    private Configuration launcherConf;
+    private Set<Class<?>> launcherClassesToShip;
+    private Map<String, URIHandler> cache;
+    private URIHandler defaultHandler;
+
+    @Override
+    public void init(Services services) throws ServiceException {
+        try {
+            init(services.getConf());
+        }
+        catch (Exception e) {
+            throw new ServiceException(ErrorCode.E0902, e);
+        }
+    }
+
+    private void init(Configuration conf) throws ClassNotFoundException {
+        cache = new HashMap<String, URIHandler>();
+
+        String[] classes = conf.getStrings(URI_HANDLERS, FSURIHandler.class.getName());
+        for (String classname : classes) {
+            Class<?> clazz = Class.forName(classname.trim());
+            URIHandler uriHandler = (URIHandler) ReflectionUtils.newInstance(clazz, null);
+            uriHandler.init(conf);
+            for (String scheme : uriHandler.getSupportedSchemes()) {
+                cache.put(scheme, uriHandler);
+            }
+        }
+
+        Class<?> defaultClass = conf.getClass(URI_HANDLER_DEFAULT, null);
+        defaultHandler = (defaultClass == null) ? new FSURIHandler() : (URIHandler) ReflectionUtils.newInstance(
+                defaultClass, null);
+        defaultHandler.init(conf);
+        for (String scheme : defaultHandler.getSupportedSchemes()) {
+            cache.put(scheme, defaultHandler);
+        }
+
+        initLauncherClassesToShip();
+        initLauncherURIHandlerConf();
+
+        LOG.info("Loaded urihandlers {0}", Arrays.toString(classes));
+        LOG.info("Loaded default urihandler {0}", defaultHandler.getClass().getName());
+    }
+
+    /**
+     * Initialize classes that need to be shipped for using LauncherURIHandler in the launcher job
+     */
+    private void initLauncherClassesToShip(){
+        launcherClassesToShip = new HashSet<Class<?>>();
+        launcherClassesToShip.add(LauncherURIHandlerFactory.class);
+        launcherClassesToShip.add(LauncherURIHandler.class);
+        for (URIHandler handler : cache.values()) {
+            launcherClassesToShip.add(handler.getLauncherURIHandlerClass());
+            List<Class<?>> classes = handler.getClassesForLauncher();
+            if (classes != null) {
+                launcherClassesToShip.addAll(classes);
+            }
+        }
+        launcherClassesToShip.add(defaultHandler.getLauncherURIHandlerClass());
+    }
+
+    /**
+     * Initialize configuration required for using LauncherURIHandler in the launcher job
+     */
+    private void initLauncherURIHandlerConf() {
+        launcherConf = new Configuration(false);
+
+        for (URIHandler handler : cache.values()) {
+            for (String scheme : handler.getSupportedSchemes()) {
+                String schemeConf = LauncherURIHandlerFactory.CONF_LAUNCHER_URIHANDLER_SCHEME_PREFIX + scheme;
+                launcherConf.set(schemeConf, handler.getLauncherURIHandlerClass().getName());
+            }
+        }
+
+        for (String scheme : defaultHandler.getSupportedSchemes()) {
+            String schemeConf = LauncherURIHandlerFactory.CONF_LAUNCHER_URIHANDLER_SCHEME_PREFIX + scheme;
+            launcherConf.set(schemeConf, defaultHandler.getLauncherURIHandlerClass().getName());
+        }
+    }
+
+    @Override
+    public void destroy() {
+        Set<URIHandler> handlers = new HashSet<URIHandler>();
+        handlers.addAll(cache.values());
+        for (URIHandler handler : handlers) {
+            handler.destroy();
+        }
+        cache.clear();
+    }
+
+    @Override
+    public Class<? extends Service> getInterface() {
+        return URIHandlerService.class;
+    }
+
+    /**
+     * Return the classes to be shipped to the launcher
+     * @return the set of classes to be shipped to the launcher
+     */
+    public Set<Class<?>> getClassesForLauncher() {
+        return launcherClassesToShip;
+    }
+
+    /**
+     * Return the configuration required to use LauncherURIHandler in the launcher
+     * @return configuration
+     */
+    public Configuration getLauncherConfig() {
+        return launcherConf;
+    }
+
+    public URIHandler getURIHandler(String uri) throws URIHandlerException {
+        try {
+            return getURIHandler(new URI(uri));
+        }
+        catch (URISyntaxException e) {
+            throw new URIHandlerException(ErrorCode.E0902, e);
+        }
+    }
+
+    public URIHandler getURIHandler(URI uri) throws URIHandlerException {
+        return getURIHandler(uri, false);
+    }
+
+    public URIHandler getURIHandler(URI uri, boolean validateURI) throws URIHandlerException {
+        if (uri.getScheme() == null) {
+            if (validateURI) {
+                throw new URIHandlerException(ErrorCode.E0905, uri);
+            }
+            else {
+                return defaultHandler;
+            }
+        }
+        else {
+            URIHandler handler = cache.get(uri.getScheme());
+            if (handler == null) {
+                handler = cache.get("*");
+                if (handler == null) {
+                    throw new URIHandlerException(ErrorCode.E0904, uri.getScheme(), uri.toString());
+                }
+            }
+            return handler;
+        }
+    }
+
+    /**
+     * Get the URI with scheme://host:port removing the path
+     * @param uri uri template
+     * @return URI with authority and scheme
+     * @throws URIHandlerException
+     */
+    public URI getAuthorityWithScheme(String uri) throws URIHandlerException {
+        int index = uri.indexOf("://");
+        if (index == -1) {
+            throw new URIHandlerException(ErrorCode.E0905, uri);
+        }
+        try {
+            if (uri.indexOf(":///") != -1) {
+                return new URI(uri.substring(0, index + 4));
+            }
+            int pathIndex = uri.indexOf("/", index + 4);
+            if (pathIndex == -1) {
+                return new URI(uri.substring(0));
+            }
+            else {
+                return new URI(uri.substring(0, pathIndex));
+            }
+        }
+        catch (URISyntaxException e) {
+            throw new URIHandlerException(ErrorCode.E0906, uri, e);
+        }
+    }
+
+}

Added: oozie/trunk/core/src/main/java/org/apache/oozie/service/UserGroupInformationService.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/service/UserGroupInformationService.java?rev=1449911&view=auto
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/service/UserGroupInformationService.java (added)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/service/UserGroupInformationService.java Mon Feb 25 21:42:07 2013
@@ -0,0 +1,51 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.oozie.service;
+
+import java.io.IOException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import org.apache.hadoop.security.UserGroupInformation;
+
+public class UserGroupInformationService implements Service {
+
+    private ConcurrentMap<String, UserGroupInformation> cache = new ConcurrentHashMap<String, UserGroupInformation>();
+
+    @Override
+    public void init(Services services) throws ServiceException {
+    }
+
+    @Override
+    public void destroy() {
+        cache.clear();
+    }
+
+    @Override
+    public Class<? extends Service> getInterface() {
+        return UserGroupInformationService.class;
+    }
+
+    public UserGroupInformation getProxyUser(String user) throws IOException {
+        if (!cache.containsKey(user)) {
+            cache.putIfAbsent(user, UserGroupInformation.createProxyUser(user, UserGroupInformation.getLoginUser()));
+        }
+        return cache.get(user);
+    }
+
+}

Added: oozie/trunk/core/src/main/java/org/apache/oozie/util/HCatURI.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/util/HCatURI.java?rev=1449911&view=auto
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/util/HCatURI.java (added)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/util/HCatURI.java Mon Feb 25 21:42:07 2013
@@ -0,0 +1,291 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.oozie.util;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+/**
+ * Utility class to parse HCatalog URI
+ */
+public class HCatURI {
+
+    public static final String PARTITION_SEPARATOR = ";";
+    public static final String PARTITION_KEYVAL_SEPARATOR = "=";
+    public static final String PATH_SEPARATOR = "/";
+    public static final String PARTITION_VALUE_QUOTE = "'";
+
+    private URI uri;
+    private String db;
+    private String table;
+    private Map<String, String> partitions;
+
+    /**
+     * Constructor using default configuration
+     *
+     * @param s HCat URI String
+     * @throws URISyntaxException
+     */
+    public HCatURI(String s) throws URISyntaxException {
+        this(new URI(s));
+    }
+
+    public HCatURI(URI uri) throws URISyntaxException {
+        parse(uri);
+    }
+
+    private void parse(URI uri) throws URISyntaxException {
+
+        this.uri = uri;
+
+        if (uri.getAuthority() == null) {
+            throw new URISyntaxException(uri.toString(), "Server host and port are missing");
+        }
+
+        String[] paths = uri.getPath().split(PATH_SEPARATOR);
+
+        if (paths.length != 4) {
+            throw new URISyntaxException(uri.toString(), "URI path is not in expected format");
+        }
+
+        db = paths[1];
+        table = paths[2];
+        String partRaw = paths[3];
+
+        if (db == null || db.length() == 0) {
+            throw new URISyntaxException(uri.toString(), "DB name is missing");
+        }
+        if (table == null || table.length() == 0) {
+            throw new URISyntaxException(uri.toString(), "Table name is missing");
+        }
+        if (partRaw == null || partRaw.length() == 0) {
+            throw new URISyntaxException(uri.toString(), "Partition details are missing");
+        }
+
+        partitions = new HashMap<String, String>();
+        String[] parts = partRaw.split(PARTITION_SEPARATOR);
+        for (String part : parts) {
+            if (part == null || part.length() == 0) {
+                continue;
+            }
+            String[] keyVal = part.split(PARTITION_KEYVAL_SEPARATOR);
+            if (keyVal.length != 2) {
+                throw new URISyntaxException(uri.toString(), "Partition key value pair is not specified properly in ("
+                        + part + ")");
+            }
+            partitions.put(keyVal[0], keyVal[1]);
+        }
+    }
+
+    public URI getURI() {
+        return uri;
+    }
+
+    public String toURIString() {
+        return uri.toString();
+    }
+
+    /**
+     * @return fully qualified server address
+     */
+    public String getServerEndPoint() {
+        return uri.getScheme() + "://" + uri.getAuthority();
+    }
+
+    /**
+     * @return server host:port
+     */
+    public String getServer() {
+        return uri.getAuthority();
+    }
+
+    /**
+     * @return DB name
+     */
+    public String getDb() {
+        return db;
+    }
+
+    /**
+     * @return table name
+     */
+    public String getTable() {
+        return table;
+    }
+
+    /**
+     * @return partitions map
+     */
+    public Map<String, String> getPartitionMap() {
+        return partitions;
+    }
+
+
+    /**
+     * @param key partition key
+     * @return partition value
+     */
+    public String getPartitionValue(String key) {
+        return partitions.get(key);
+    }
+
+    /**
+     * @param key partition key to set
+     * @param value partition value to set
+     */
+    public void setPartition(String key, String value) {
+        partitions.put(key, value);
+    }
+
+    /**
+     * @param key partition key
+     * @return if partitions map includes the key or not
+     */
+    public boolean hasPartition(String key) {
+        return partitions.containsKey(key);
+    }
+
+    public static String getHCatURI(String server, String db, String table, Map<String, String> partitions) {
+        return getHCatURI("hcat", server, db, table, partitions);
+    }
+
+    /**
+     * static method to create HCatalog URI String
+     *
+     * @param server
+     * @param db
+     * @param table
+     * @param partitions Partition Map
+     * @return
+     */
+    public static String getHCatURI(String scheme, String server, String db, String table, Map<String, String> partitions) {
+
+        StringBuilder sb = new StringBuilder();
+        sb.append(scheme);
+        sb.append("://");
+        sb.append(server);
+        sb.append(PATH_SEPARATOR);
+        sb.append(db);
+        sb.append(PATH_SEPARATOR);
+        sb.append(table);
+        sb.append(PATH_SEPARATOR);
+        for (Entry<String, String> entry : partitions.entrySet()) {
+            sb.append(entry.getKey());
+            sb.append(PARTITION_KEYVAL_SEPARATOR);
+            sb.append(entry.getValue());
+            sb.append(PARTITION_SEPARATOR);
+        }
+        sb.setLength(sb.length() - 1);
+        return sb.toString();
+    }
+
+    @Override
+    public int hashCode() {
+        return (uri == null) ? 0 : uri.hashCode();
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj)
+            return true;
+        if (obj == null)
+            return false;
+        if (getClass() != obj.getClass())
+            return false;
+        HCatURI other = (HCatURI) obj;
+        return uri.equals(other.uri);
+    }
+
+    /**
+     * Convert the partition map to filter string. Each key value pair is
+     * separated by AND
+     *
+     * @param type pig/java/mr/hive
+     * @return filter string
+     */
+    public String toPartitionFilter(String type) {
+        StringBuilder filter = new StringBuilder();
+        String comparator = null;
+        filter.append("(");
+        comparator = type.equalsIgnoreCase("pig") ? "==" : "=";
+        for (Map.Entry<String, String> entry : partitions.entrySet()) {
+            if (filter.length() > 1) {
+                filter.append(" AND ");
+            }
+            filter.append(entry.getKey());
+            filter.append(comparator);
+            filter.append(PARTITION_VALUE_QUOTE);
+            filter.append(entry.getValue());
+            filter.append(PARTITION_VALUE_QUOTE);
+        }
+        filter.append(")");
+        return filter.toString();
+    }
+
+    /**
+     * Get the partition as string for HCatStorer argument.
+     *
+     * @return filter string
+     */
+    public String toPartitionString() {
+        StringBuilder filter = new StringBuilder();
+        filter.append("'");
+        for (Map.Entry<String, String> entry : partitions.entrySet()) {
+            if (filter.length() > 1) {
+                filter.append(",");
+            }
+            filter.append(entry.getKey());
+            filter.append("=");
+            filter.append(entry.getValue());
+        }
+        filter.append("'");
+        return filter.toString();
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+        sb.append("URI: ");
+        sb.append(uri.toString());
+        sb.append("\n");
+        sb.append("SCHEME: ");
+        sb.append(uri.getScheme());
+        sb.append("\n");
+        sb.append("SERVER: ");
+        sb.append(getServer());
+        sb.append("\n");
+        sb.append("DB: ");
+        sb.append(getDb());
+        sb.append("\n");
+        sb.append("TABLE: ");
+        sb.append(getTable());
+        int partcnt = 0;
+        for (Map.Entry<String, String> entry : partitions.entrySet()) {
+            sb.append("\n");
+            sb.append("PARTITION(" + partcnt + "): ");
+            sb.append(entry.getKey());
+            sb.append("=");
+            sb.append(entry.getValue());
+            partcnt++;
+        }
+        return sb.toString();
+    }
+}

Added: oozie/trunk/core/src/main/java/org/apache/oozie/util/MappingRule.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/util/MappingRule.java?rev=1449911&view=auto
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/util/MappingRule.java (added)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/util/MappingRule.java Mon Feb 25 21:42:07 2013
@@ -0,0 +1,91 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.oozie.util;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Class for rule mapping
+ */
+public class MappingRule {
+
+    private static Pattern variableNamePattern = Pattern.compile("\\$\\{[0-9]\\}");
+    private Pattern fromPattern;
+    private String fromString;
+    private String toString;
+    private boolean patternMatch;
+
+    /**
+     * Maps from source rule to destination rule
+     * @param fromRule - Rule for which input needs to be matched
+     * @param toRule - Rule for value to be returned
+     */
+    public MappingRule(String fromRule, String toRule) {
+        if (fromRule.contains("$")) {
+            patternMatch = true;
+            fromRule = fromRule.replaceAll("\\.", "\\\\.");
+            Matcher match = variableNamePattern.matcher(fromRule);
+            fromRule = match.replaceAll("(.*)");
+            fromPattern = Pattern.compile(fromRule);
+        }
+        else {
+            fromString = fromRule;
+        }
+        toString = toRule;
+    }
+
+    /**
+     * Gets the from rule
+     * @return
+     */
+    public String getFromRule() {
+        return fromString;
+    }
+
+    /**
+     * Gets the to rule
+     * @return
+     */
+    public String getToRule() {
+        return toString;
+    }
+
+    /**
+     * Applies rules based on the input
+     * @param input
+     * @return
+     */
+    public String applyRule(String input) {
+        if (patternMatch) {
+            Matcher match = fromPattern.matcher(input);
+            if (match.matches()) {
+                String result = toString;
+                int count = match.groupCount();
+                for (int i = 1; i <= count; i++) {
+                    result = result.replace("${" + (i) + "}", match.group(i));
+                }
+                return result;
+            }
+        }
+        else if (input.equals(fromString)) {
+            return toString;
+        }
+        return null;
+    }
+}

Modified: oozie/trunk/core/src/main/java/org/apache/oozie/util/XLog.java
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/java/org/apache/oozie/util/XLog.java?rev=1449911&r1=1449910&r2=1449911&view=diff
==============================================================================
--- oozie/trunk/core/src/main/java/org/apache/oozie/util/XLog.java (original)
+++ oozie/trunk/core/src/main/java/org/apache/oozie/util/XLog.java Mon Feb 25 21:42:07 2013
@@ -6,9 +6,9 @@
  * to you 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.

Added: oozie/trunk/core/src/main/resources/ehcache-default.xml
URL: http://svn.apache.org/viewvc/oozie/trunk/core/src/main/resources/ehcache-default.xml?rev=1449911&view=auto
==============================================================================
--- oozie/trunk/core/src/main/resources/ehcache-default.xml (added)
+++ oozie/trunk/core/src/main/resources/ehcache-default.xml Mon Feb 25 21:42:07 2013
@@ -0,0 +1,27 @@
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you 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.
+-->
+<ehcache>
+    <!--  http://svn.codehaus.org/sonar/tags/1.1/sonar-commons/src/main/resources/ehcache.xml -->
+    <diskStore path="java.io.tmpdir"/>
+    <!--  Evict cache entry after 2 days (timeToLiveSeconds) -->
+    <!--  Note: overflowToDisk=true does not work well with timeToIdleSeconds or timeToLiveSeconds.
+          Returns null even for unexpired entries -->
+    <cache name="dependency-default" maxElementsInMemory="60000" eternal="false"
+        overflowToDisk="false" timeToIdleSeconds="0" timeToLiveSeconds="172800"
+        diskPersistent="false" diskExpiryThreadIntervalSeconds="1200" />
+</ehcache>
\ No newline at end of file