1 package org.exoplatform.services.wcm.extensions.scheduler.impl;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.FileOutputStream;
7 import java.io.InputStream;
8 import java.io.OutputStream;
9 import java.util.ArrayList;
10 import java.util.HashMap;
11 import java.util.List;
12
13 import javax.jcr.Node;
14 import javax.jcr.RepositoryException;
15 import javax.jcr.Session;
16 import javax.xml.stream.XMLInputFactory;
17 import javax.xml.stream.XMLStreamReader;
18 import javax.xml.stream.events.XMLEvent;
19
20 import org.exoplatform.commons.utils.MimeTypeResolver;
21 import org.exoplatform.services.cms.link.LinkManager;
22 import org.exoplatform.services.ecm.publication.PublicationPlugin;
23 import org.exoplatform.services.ecm.publication.PublicationService;
24 import org.exoplatform.services.jcr.RepositoryService;
25 import org.exoplatform.services.jcr.core.ManageableRepository;
26 import org.exoplatform.services.jcr.ext.common.SessionProvider;
27 import org.exoplatform.services.log.ExoLogger;
28 import org.exoplatform.services.log.Log;
29 import org.exoplatform.services.wcm.extensions.publication.lifecycle.authoring.AuthoringPublicationConstant;
30 import org.exoplatform.services.wcm.publication.PublicationDefaultStates;
31 import org.exoplatform.services.wcm.utils.WCMCoreUtils;
32 import org.quartz.Job;
33 import org.quartz.JobDataMap;
34 import org.quartz.JobExecutionContext;
35 import org.quartz.JobExecutionException;
36
37
38
39
40 public class ImportContentsJob implements Job {
41 private static final Log LOG = ExoLogger.getLogger(ImportContentsJob.class.getName());
42
43 private static final String MIX_TARGET_PATH = "mix:targetPath";
44
45 private static final String MIX_TARGET_WORKSPACE = "mix:targetWorkspace";
46
47 private static final String JCR_File_SEPARATOR = "/";
48
49 public void execute(JobExecutionContext context) throws JobExecutionException {
50 Session session = null;
51 try {
52 if (LOG.isInfoEnabled()) {
53 LOG.info("Start Execute ImportXMLJob");
54 }
55
56 JobDataMap jdatamap = context.getJobDetail().getJobDataMap();
57 String stagingStorage = jdatamap.getString("stagingStorage");
58 String temporaryStorge = jdatamap.getString("temporaryStorge");
59 if (LOG.isDebugEnabled()) {
60 LOG.debug("Init parameters first time :");
61 }
62
63 SessionProvider sessionProvider = SessionProvider.createSystemProvider();
64 String containerName = WCMCoreUtils.getContainerNameFromJobContext(context);
65 RepositoryService repositoryService_ = WCMCoreUtils.getService(RepositoryService.class, containerName);
66 ManageableRepository manageableRepository = repositoryService_.getCurrentRepository();
67 PublicationService publicationService = WCMCoreUtils.getService(PublicationService.class, containerName);
68 PublicationPlugin publicationPlugin = publicationService.getPublicationPlugins()
69 .get(AuthoringPublicationConstant.LIFECYCLE_NAME);
70 XMLInputFactory factory = XMLInputFactory.newInstance();
71
72 File stagingFolder = new File(stagingStorage);
73 File tempfolder = new File(temporaryStorge);
74
75 File[] files = null;
76 File xmlFile = null;
77 XMLStreamReader reader = null;
78 InputStream xmlInputStream = null;
79 int eventType;
80 List<LinkObject> listLink = new ArrayList<LinkObject>();
81 LinkObject linkObj = new LinkObject();
82 boolean hasNewContent = false;
83 if (stagingFolder.exists()) {
84 files = stagingFolder.listFiles();
85 if (files != null) {
86 hasNewContent = true;
87 for (int i = 0; i < files.length; i++) {
88 xmlFile = files[i];
89 if (xmlFile.isFile()) {
90 MimeTypeResolver resolver = new MimeTypeResolver();
91 String fileName = xmlFile.getName();
92 String hashCode = fileName.split("-")[0];
93 String mimeType = resolver.getMimeType(xmlFile.getName());
94 if ("text/xml".equals(mimeType)) {
95 xmlInputStream = new FileInputStream(xmlFile);
96 reader = factory.createXMLStreamReader(xmlInputStream);
97 while (reader.hasNext()) {
98 eventType = reader.next();
99 if (eventType == XMLEvent.START_ELEMENT && "data".equals(reader.getLocalName())) {
100 String data = reader.getElementText();
101
102 if (!tempfolder.exists())
103 tempfolder.mkdirs();
104 long time = System.currentTimeMillis();
105 File file = new File(temporaryStorge + File.separator + "-" + hashCode + "-"
106 + time + ".xml.tmp");
107 InputStream inputStream = new ByteArrayInputStream(data.getBytes());
108 OutputStream out = new FileOutputStream(file);
109 byte[] buf = new byte[1024];
110 int len;
111 while ((len = inputStream.read(buf)) > 0)
112 out.write(buf, 0, len);
113 out.close();
114 inputStream.close();
115 }
116 try {
117 if (eventType == XMLEvent.START_ELEMENT
118 && "published-content".equals(reader.getLocalName())) {
119 linkObj.setSourcePath(reader.getAttributeValue(0));
120
121
122
123 }
124 if (eventType == XMLEvent.START_ELEMENT && "type".equals(reader.getLocalName())) {
125 linkObj.setLinkType(reader.getElementText());
126 }
127 if (eventType == XMLEvent.START_ELEMENT
128 && "title".equals(reader.getLocalName())) {
129 linkObj.setLinkTitle(reader.getElementText());
130 }
131 if (eventType == XMLEvent.START_ELEMENT
132 && "targetPath".equals(reader.getLocalName())) {
133 linkObj.setLinkTargetPath(reader.getElementText());
134 listLink.add(linkObj);
135 }
136
137 if (eventType == XMLEvent.START_ELEMENT
138 && "unpublished-content".equals(reader.getLocalName())) {
139
140 String contentTargetPath = reader.getAttributeValue(0);
141 String[] strContentPath = contentTargetPath.split(":");
142 StringBuffer sbContPath = new StringBuffer();
143 boolean flag = true;
144 for (int index = 2; index < strContentPath.length; index++) {
145 if (flag) {
146 sbContPath.append(strContentPath[index]);
147 flag = false;
148 } else {
149 sbContPath.append(":").append(strContentPath[index]);
150 }
151 }
152 sessionProvider = SessionProvider.createSystemProvider();
153
154 manageableRepository = repositoryService_.getCurrentRepository();
155 String workspace = strContentPath[1];
156 session = sessionProvider.getSession(workspace, manageableRepository);
157 String contentPath = sbContPath.toString();
158 if (session.itemExists(contentPath)) {
159 Node currentContent = (Node) session.getItem(contentPath);
160 HashMap<String, String> variables = new HashMap<String, String>();
161 variables.put("nodePath", contentTargetPath);
162 variables.put("workspaceName", workspace);
163 if (currentContent.hasProperty(AuthoringPublicationConstant.PUBLICATION_LIFECYCLE_NAME)
164 && AuthoringPublicationConstant.LIFECYCLE_NAME.equals(
165 currentContent.getProperty(
166 AuthoringPublicationConstant.PUBLICATION_LIFECYCLE_NAME).getString())
167 && PublicationDefaultStates.PUBLISHED.equals(
168 currentContent.getProperty(AuthoringPublicationConstant.CURRENT_STATE).getString())) {
169
170 publicationPlugin.changeState(currentContent,
171 PublicationDefaultStates.UNPUBLISHED,
172 variables);
173 if (LOG.isInfoEnabled()) {
174 LOG.info("Change the status of the node " + currentContent.getPath()
175 + " from " + PublicationDefaultStates.PUBLISHED + " to "
176 + PublicationDefaultStates.UNPUBLISHED);
177 }
178 }
179 } else {
180 if (LOG.isWarnEnabled()) {
181 LOG.warn("The node " + contentPath + " does not exist");
182 }
183 }
184
185 }
186
187 } catch (Exception ie) {
188 if (LOG.isWarnEnabled()) {
189 LOG.warn("Error in ImportContentsJob: " + ie.getMessage());
190 }
191 }
192 }
193 reader.close();
194 xmlInputStream.close();
195 xmlFile.delete();
196 }
197 }
198 }
199 }
200 }
201 files = tempfolder.listFiles();
202 if (files != null) {
203 for (int i = 0; i < files.length; i++) {
204 xmlFile = files[i];
205 InputStream inputStream = new FileInputStream(xmlFile);
206 reader = factory.createXMLStreamReader(inputStream);
207 String workspace = null;
208 String nodePath = new String();
209
210 while (reader.hasNext()) {
211 eventType = reader.next();
212 if (eventType == XMLEvent.START_ELEMENT) {
213 if (reader.getLocalName().equals("property")) {
214 String value = reader.getAttributeValue(0);
215 if (MIX_TARGET_PATH.equals(value)) {
216 eventType = reader.next();
217 if (eventType == XMLEvent.START_ELEMENT) {
218 reader.next();
219 nodePath = reader.getText();
220 }
221 } else if (MIX_TARGET_WORKSPACE.equals(value)) {
222 eventType = reader.next();
223 if (eventType == XMLEvent.START_ELEMENT) {
224 reader.next();
225 workspace = reader.getText();
226 }
227 }
228 }
229 }
230 }
231 reader.close();
232 inputStream.close();
233 session = sessionProvider.getSession(workspace, manageableRepository);
234 if (session.itemExists(nodePath))
235 session.getItem(nodePath).remove();
236 session.save();
237
238 String path = nodePath.substring(0, nodePath.lastIndexOf(JCR_File_SEPARATOR));
239 if (!session.itemExists(path)) {
240 String[] pathTab = path.split(JCR_File_SEPARATOR);
241 Node node_ = session.getRootNode();
242 StringBuffer path_ = new StringBuffer(JCR_File_SEPARATOR);
243 for (int j = 1; j < pathTab.length; j++) {
244 path_ = path_.append(pathTab[j] + JCR_File_SEPARATOR);
245 if (!session.itemExists(path_.toString())) {
246 node_.addNode(pathTab[j], "nt:unstructured");
247 }
248 node_ = (Node) session.getItem(path_.toString());
249 }
250 }
251
252 session.importXML(path, new FileInputStream(xmlFile), 0);
253 session.save();
254 xmlFile.delete();
255
256 if (hasNewContent) {
257 for (LinkObject obj : listLink) {
258 String[] linkTarget = obj.getLinkTargetPath().split(":");
259 StringBuffer itemPath = new StringBuffer();
260 boolean flag = true;
261 for (int index = 2; index < linkTarget.length; index++) {
262 if (flag) {
263 itemPath.append(linkTarget[index]);
264 flag = false;
265 } else {
266 itemPath.append(":");
267 itemPath.append(linkTarget[index]);
268 }
269 }
270 String[] linkSource = obj.getSourcePath().split(":");
271 session = sessionProvider.getSession(linkTarget[1], manageableRepository);
272 Node parentNode = (Node) session.getItem(itemPath.toString());
273
274 StringBuffer sourcePath = new StringBuffer();
275 boolean flagSource = true;
276 for (int index = 2; index < linkSource.length; index++) {
277 if (flagSource) {
278 sourcePath.append(linkSource[index]);
279 flagSource = false;
280 } else {
281 sourcePath.append(":");
282 sourcePath.append(linkSource[index]);
283 }
284 }
285
286 if (parentNode.hasNode(obj.getLinkTitle())) {
287 Node existedNode = (Node) session.getItem(itemPath + "/" + obj.getLinkTitle());
288 existedNode.remove();
289 }
290 session = sessionProvider.getSession(linkSource[1], manageableRepository);
291 Node targetNode = (Node) session.getItem(sourcePath.toString());
292 LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class, containerName);
293 linkManager.createLink(parentNode, obj.getLinkType(), targetNode, obj.getLinkTitle());
294 }
295 }
296 }
297 }
298 if (LOG.isInfoEnabled()) {
299 LOG.info("End Execute ImportXMLJob");
300 }
301 } catch (RepositoryException ex) {
302 if (LOG.isDebugEnabled()) {
303 LOG.debug("Repository 'repository ' not found.");
304 }
305 } catch (Exception ex) {
306 if (LOG.isErrorEnabled()) {
307 LOG.error("Error when importing Contents : " + ex.getMessage(), ex);
308 }
309 } finally {
310 if (session != null)
311 session.logout();
312 }
313 }
314
315 private class LinkObject {
316 private String linkType;
317
318 private String linkTitle;
319
320 private String linkTargetPath;
321
322 private String sourcePath;
323
324 public String getLinkType() {
325 return linkType;
326 }
327
328 public void setLinkType(String linkType) {
329 this.linkType = linkType;
330 }
331
332 public String getLinkTitle() {
333 return linkTitle;
334 }
335
336 public void setLinkTitle(String linkTitle) {
337 this.linkTitle = linkTitle;
338 }
339
340 public String getLinkTargetPath() {
341 return linkTargetPath;
342 }
343
344 public void setLinkTargetPath(String linkTargetPath) {
345 this.linkTargetPath = linkTargetPath;
346 }
347
348 public String getSourcePath() {
349 return sourcePath;
350 }
351
352 public void setSourcePath(String sourcePath) {
353 this.sourcePath = sourcePath;
354 }
355 }
356 }