View Javadoc

1   /**
2    * This file Copyright (c) 2003-2011 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.module.exchangesimple;
35  
36  import info.magnolia.cms.core.ItemType;
37  import info.magnolia.cms.exchange.ActivationManagerFactory;
38  import info.magnolia.cms.exchange.ExchangeException;
39  import info.magnolia.cms.exchange.Subscriber;
40  import info.magnolia.cms.exchange.Subscription;
41  import info.magnolia.cms.security.SecurityUtil;
42  
43  import java.io.IOException;
44  import java.net.MalformedURLException;
45  import java.net.URLConnection;
46  import java.util.ArrayList;
47  import java.util.Collection;
48  import java.util.Iterator;
49  import java.util.List;
50  
51  import org.apache.commons.lang.StringUtils;
52  import org.slf4j.Logger;
53  import org.slf4j.LoggerFactory;
54  
55  import EDU.oswego.cs.dl.util.concurrent.CountDown;
56  import EDU.oswego.cs.dl.util.concurrent.Sync;
57  
58  /**
59   * Implementation of syndicator that simply sends all activated content over http connection specified in the subscriber.
60   * 
61   * @author Sameer Charles $Id: SimpleSyndicator.java 53340 2012-01-12 10:11:32Z ochytil $
62   */
63  public class SimpleSyndicator extends BaseSyndicatorImpl {
64      private static final Logger log = LoggerFactory.getLogger(SimpleSyndicator.class);
65  
66      @Override
67      public void activate(final ActivationContent activationContent, String nodePath) throws ExchangeException {
68          String nodeUUID = activationContent.getproperty(NODE_UUID);
69          final ExchangeTask task;
70          // Create runnable task for subscriber execute
71          if (Boolean.parseBoolean(activationContent.getproperty(ItemType.DELETED_NODE_MIXIN))) {
72              task = getDeactivateTask(nodeUUID, nodePath);
73          } else {
74              task = getActivateTask(activationContent, nodePath);
75          }
76          List<Exception> errors = executeExchangeTask(task);
77  
78          // clean storage BEFORE re-throwing exception
79          executeInPool(new Runnable() {
80              @Override
81              public void run() {
82                  cleanTemporaryStore(activationContent);
83              }
84          });
85  
86          handleErrors(errors);
87  
88      }
89  
90      protected void handleErrors(List<Exception> errors) throws ExchangeException {
91          // collect all the errors and send them back.
92          if (!errors.isEmpty()) {
93              Exception e = errors.get(0);
94              log.error(e.getMessage(), e);
95              throw new ExchangeException("1 error detected: \n" + e.getMessage(), e);
96          }
97      }
98  
99      private ExchangeTask getActivateTask(final ActivationContent activationContent, final String nodePath) {
100         ExchangeTask r = new ExchangeTask() {
101             @Override
102             public void runTask(Subscriber subscriber) throws ExchangeException {
103                 activate(subscriber, activationContent, nodePath);
104             }
105         };
106         return r;
107     }
108 
109     @Override
110     public void doDeactivate(String nodeUUID, String nodePath) throws ExchangeException {
111         List<Exception> errors = executeExchangeTask(getDeactivateTask(nodeUUID, nodePath));
112         handleErrors(errors);
113     }
114 
115     private List<Exception> executeExchangeTask(ExchangeTask runnable) throws ExchangeException {
116         Collection<Subscriber> allSubscribers = ActivationManagerFactory.getActivationManager().getSubscribers();
117         Iterator<Subscriber> subscriberIterator = allSubscribers.iterator();
118         final Sync done = new CountDown(allSubscribers.size());
119         final List<Exception> errors = new ArrayList<Exception>();
120         int count = 0;
121         while (subscriberIterator.hasNext()) {
122             count++;
123             final Subscriber subscriber = subscriberIterator.next();
124             if (subscriber.isActive()) {
125                 // TODO: Inject?
126                 runnable.setErrors(errors);
127                 runnable.setSubscriber(subscriber);
128                 runnable.setSync(done);
129                 // Create runnable task for each subscriber.
130                 executeInPool(runnable);
131                 break;
132             } else {
133                 done.release();
134             }
135         } // end of subscriber loop
136 
137         // release unused barriers
138         for (; count < allSubscribers.size(); count++) {
139             done.release();
140         }
141 
142         // wait until all tasks are executed before returning back to user to make sure errors can be propagated back to the user.
143         acquireIgnoringInterruption(done);
144 
145         return errors;
146     }
147 
148     private ExchangeTask getDeactivateTask(final String nodeUUID, final String nodePath) {
149         ExchangeTask r = new ExchangeTask() {
150             @Override
151             public void runTask(Subscriber subscriber) throws ExchangeException {
152                 doDeactivate(subscriber, nodeUUID, nodePath);
153             }
154         };
155         return r;
156     }
157 
158     /**
159      * Deactivate from a specified subscriber.
160      * 
161      * @param subscriber
162      * @throws ExchangeException
163      */
164     @Override
165     public String doDeactivate(Subscriber subscriber, String nodeUUID, String path) throws ExchangeException {
166         Subscription subscription = subscriber.getMatchedSubscription(path, this.repositoryName);
167         if (null != subscription) {
168             String urlString = getDeactivationURL(subscriber);
169             try {
170                 URLConnection urlConnection = prepareConnection(subscriber, urlString);
171 
172                 this.addDeactivationHeaders(urlConnection, nodeUUID, null);
173                 String status = urlConnection.getHeaderField(ACTIVATION_ATTRIBUTE_STATUS);
174 
175                 if (StringUtils.equals(status, ACTIVATION_HANDSHAKE)) {
176                     String handshakeKey = urlConnection.getHeaderField(ACTIVATION_AUTH);
177                     // receive all pending data
178                     urlConnection.getContent();
179 
180                     // transport the data again
181                     urlConnection = prepareConnection(subscriber, getActivationURL(subscriber));
182                     // and get the version & status again
183                     this.addDeactivationHeaders(urlConnection, nodeUUID, handshakeKey);
184                     status = urlConnection.getHeaderField(ACTIVATION_ATTRIBUTE_STATUS);
185                 }
186 
187                 // check if the activation failed
188                 if (StringUtils.equals(status, ACTIVATION_FAILED)) {
189                     String message = urlConnection.getHeaderField(ACTIVATION_ATTRIBUTE_MESSAGE);
190                     throw new ExchangeException("Message received from subscriber: " + message);
191                 }
192 
193                 urlConnection.getContent();
194 
195             } catch (MalformedURLException e) {
196                 throw new ExchangeException("Incorrect URL for subscriber " + subscriber + "[" + SecurityUtil.stripPasswordFromUrl(urlString) + "]");
197             } catch (IOException e) {
198                 throw new ExchangeException("Not able to send the deactivation request [" + SecurityUtil.stripPasswordFromUrl(urlString) + "]: " + e.getMessage());
199             } catch (Exception e) {
200                 throw new ExchangeException(e);
201             }
202         }
203         return null;
204     }
205 
206 }