View Javadoc
1   /***************************************************************************
2    * Copyright (C) 2003-2009 eXo Platform SAS.
3    *
4    * This program is free software; you can redistribute it and/or
5    * modify it under the terms of the GNU Affero General Public License
6    * as published by the Free Software Foundation; either version 3
7    * of the License, or (at your option) any later version.
8    *
9    * This program is distributed in the hope that it will be useful,
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   * GNU General Public License for more details.
13   *
14   * You should have received a copy of the GNU General Public License
15   * along with this program; if not, see<http://www.gnu.org/licenses/>.
16   *
17   **************************************************************************/
18  package org.exoplatform.wcm.connector.collaboration;
19  
20  import java.text.DateFormat;
21  import java.text.SimpleDateFormat;
22  import java.util.ArrayList;
23  import java.util.Collections;
24  import java.util.Comparator;
25  import java.util.Date;
26  import java.util.List;
27  
28  import javax.jcr.Node;
29  import javax.jcr.NodeIterator;
30  import javax.jcr.RepositoryException;
31  import javax.jcr.Session;
32  import javax.jcr.Value;
33  import javax.jcr.query.Query;
34  import javax.jcr.query.QueryManager;
35  import javax.jcr.query.QueryResult;
36  import javax.ws.rs.GET;
37  import javax.ws.rs.Path;
38  import javax.ws.rs.PathParam;
39  import javax.ws.rs.QueryParam;
40  import javax.ws.rs.core.MediaType;
41  import javax.ws.rs.core.Response;
42  
43  import org.exoplatform.commons.utils.ISO8601;
44  import org.exoplatform.services.cms.drives.DriveData;
45  import org.exoplatform.services.cms.drives.ManageDriveService;
46  import org.exoplatform.services.ecm.publication.PublicationService;
47  import org.exoplatform.services.jcr.RepositoryService;
48  import org.exoplatform.services.jcr.ext.common.SessionProvider;
49  import org.exoplatform.services.jcr.impl.core.query.QueryImpl;
50  import org.exoplatform.services.log.ExoLogger;
51  import org.exoplatform.services.log.Log;
52  import org.exoplatform.services.rest.resource.ResourceContainer;
53  import org.exoplatform.services.wcm.utils.WCMCoreUtils;
54  
55  /**
56   * Returns a list of published documents.
57   *
58   * @LevelAPI Provisional
59   * 
60   * @anchor PublicationGetDocumentRESTService
61   */
62  @Path("/publication/presentation/")
63  public class PublicationGetDocumentRESTService implements ResourceContainer {
64  
65    private RepositoryService  repositoryService_;
66  
67    private PublicationService publicationService_;
68  
69    private ManageDriveService manageDriveService_;
70  
71    final static public String DEFAULT_ITEM = "5";
72  
73    /** The Constant LAST_MODIFIED_PROPERTY. */
74    private static final String LAST_MODIFIED_PROPERTY = "Last-Modified";
75  
76    /** The Constant IF_MODIFIED_SINCE_DATE_FORMAT. */
77    private static final String IF_MODIFIED_SINCE_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z";
78  
79    private static final Log LOG  = ExoLogger.getLogger(PublicationGetDocumentRESTService.class.getName());
80  
81    public PublicationGetDocumentRESTService(RepositoryService repositoryService,
82        PublicationService publicationService, ManageDriveService manageDriveService) {
83      repositoryService_ = repositoryService;
84      publicationService_ = publicationService;
85      manageDriveService_ = manageDriveService;
86    }
87  
88    /**
89     * Returns a list of published documents by the default plugin.
90     * For example: {{{/portal/rest/publication/presentation/{repository}/{workspace}/{state}?showItems={numberOfItem}}}}
91     *
92     * @param repository The repository name.
93     * @param workspace The workspace name.
94     * @param state The state is specified to classify the process.
95     * @param showItems Shows the number of items per page.
96     * @return
97     * @throws Exception
98     * 
99     * @anchor PublicationGetDocumentRESTService.getPublishDocument
100    */
101   @Path("/{repository}/{workspace}/{state}/")
102   @GET
103 //  @OutputTransformer(Bean2JsonOutputTransformer.class)
104   public Response getPublishDocument(@PathParam("repository") String repository, @PathParam("workspace")
105   String workspace, @PathParam("state") String state, @QueryParam("showItems")
106   String showItems) throws Exception {
107     return getPublishDocuments(workspace, state, null, showItems);
108   }
109 
110   /**
111    * Returns a list of published documents by a specific plugin.
112    * For example: {{{/portal/rest/publication/presentation/{repository}/{workspace}/{publicationPluginName}/{state}?showItems={numberOfItem}}}}
113    *
114    * @param repoName The repository name.
115    * @param workspace The workspace name.
116    * @param publicationPluginName The name of the plugin.
117    * @param state The state is specified to classify the process.
118    * @param showItems Shows the number of items per page.
119    * @return
120    * @throws Exception
121    * 
122    * @anchor PublicationGetDocumentRESTService.getPublishedListDocument
123    */
124   @Path("/{repository}/{workspace}/{publicationPluginName}/{state}/")
125   @GET
126 //  @OutputTransformer(Bean2JsonOutputTransformer.class)
127   public Response getPublishedListDocument(@PathParam("repository") String repoName, @PathParam("workspace")
128   String workspace, @PathParam("publicationPluginName") String publicationPluginName, @PathParam("state")
129   String state, @QueryParam("showItems")
130   String showItems) throws Exception {
131     return getPublishDocuments(workspace, state, publicationPluginName, showItems);
132   }
133 
134   @SuppressWarnings("unused")
135   private Response getPublishDocuments(String wsName,
136                                        String state,
137                                        String pluginName,
138                                        String itemPage) throws Exception {
139     List<PublishedNode> publishedNodes = new ArrayList<PublishedNode>();
140     PublishedListNode publishedListNode = new PublishedListNode();
141     if(itemPage == null) itemPage = DEFAULT_ITEM;
142     int item = Integer.parseInt(itemPage);
143     String queryStatement = "select * from publication:publication order by exo:dateModified ASC";
144     SessionProvider provider = WCMCoreUtils.createAnonimProvider();
145     Session session = provider.getSession(wsName, repositoryService_.getCurrentRepository());
146     QueryManager queryManager = session.getWorkspace().getQueryManager();
147     QueryImpl query = (QueryImpl) queryManager.createQuery(queryStatement, Query.SQL);
148     query.setLimit(item);
149     query.setOffset(0);
150     QueryResult queryResult = query.execute();
151     NodeIterator iter = queryResult.getNodes();
152     List<Node> listNode = getNodePublish(iter, pluginName);
153     Collections.sort(listNode, new DateComparator());
154     if(listNode.size() < item) item = listNode.size();
155     List<DriveData> lstDrive = manageDriveService_.getAllDrives();
156     for (int i = 0; i < item; i++) {
157       PublishedNode publishedNode = new PublishedNode();
158       Node node = listNode.get(i);
159       publishedNode.setName(node.getName());
160       publishedNode.setPath(node.getPath());
161       publishedNode.setDatePublished(getPublishedDateTime(node));
162       publishedNode.setDriveName(getDriveName(lstDrive, node));
163       publishedNodes.add(publishedNode);
164     }
165     publishedListNode.setPublishedListNode(publishedNodes);
166     session.logout();
167     DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT);
168     return Response.ok(publishedListNode, new MediaType("application", "json"))
169                    .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date()))
170                    .build();
171   }
172 
173   private List<Node> getNodePublish(NodeIterator iter, String pluginName) throws Exception {
174     List<Node> listNode = new ArrayList<Node>();
175     while (iter.hasNext()) {
176       Node node = iter.nextNode();
177       Node nodecheck = publicationService_.getNodePublish(node, pluginName);
178       if (nodecheck != null) {
179         listNode.add(node);
180       }
181     }
182     return listNode;
183   }
184 
185   private String getPublishedDateTime(Node currentNode) throws Exception {
186     Value[] history = currentNode.getProperty("publication:history").getValues();
187     String time = currentNode.getProperty("exo:dateModified").getString();
188     for (Value value : history) {
189       String[] arrHistory = value.getString().split(";");
190       time = arrHistory[3];
191     }
192     return String.valueOf(ISO8601.parse(time).getTimeInMillis());
193   }
194 
195   private static class DateComparator implements Comparator<Node> {
196     public int compare(Node node1, Node node2) {
197       try {
198         SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd.HHmmss.SSS");
199         Date date1 = formatter.parse(getDateTime(node1));
200         Date date2 = formatter.parse(getDateTime(node2));
201         return date2.compareTo(date1);
202       } catch (Exception e) {
203         if (LOG.isErrorEnabled()) {
204           LOG.error("Unexpected error", e);
205         }
206       }
207       return 0;
208     }
209 
210     private String getDateTime(Node currentNode) throws Exception {
211       Value[] history = currentNode.getProperty("publication:history").getValues();
212       for (Value value : history) {
213         String[] arrHistory = value.getString().split(";");
214         return arrHistory[3];
215       }
216       return currentNode.getProperty("exo:dateModified").getString();
217     }
218   }
219 
220   private String getDriveName(List<DriveData> lstDrive, Node node) throws RepositoryException{
221     String driveName = "";
222     for (DriveData drive : lstDrive) {
223       if (node.getSession().getWorkspace().getName().equals(drive.getWorkspace())
224           && node.getPath().contains(drive.getHomePath()) && drive.getHomePath().equals("/")) {
225         driveName = drive.getName();
226         break;
227       }
228     }
229     return driveName;
230   }
231 
232   public class PublishedNode {
233 
234     private String nodeName_;
235     private String nodePath_;
236     private String driveName_;
237     private String datePublished_;
238 
239     public void setName(String nodeName) { nodeName_ = nodeName; }
240     public String getName() { return nodeName_; }
241 
242     public void setPath(String nodePath) { nodePath_ = nodePath; }
243     public String getPath() { return nodePath_; }
244 
245     public void setDriveName(String driveName) { driveName_ = driveName; }
246     public String getDriveName() { return driveName_; }
247 
248     public void setDatePublished(String datePublished) { datePublished_ = datePublished; }
249     public String getDatePublished() { return datePublished_; }
250 
251   }
252 
253   public class PublishedListNode {
254 
255     private List<PublishedNode> publishedListNode_;
256 
257     public void setPublishedListNode(List<PublishedNode> publishedListNode) {
258       publishedListNode_ = publishedListNode;
259     }
260     public List<PublishedNode> getPublishedListNode() { return publishedListNode_; }
261 
262   }
263 }