source: main/trunk/greenstone3/src/java/org/greenstone/gsdl3/action/DepositorAction.java@ 32448

Last change on this file since 32448 was 32448, checked in by kjdon, 6 years ago

params class changed, now returns false by default for shouldsave. so don't need to add any that we don't want saving in the session. turned hard coded strings into static string variables

  • Property svn:executable set to *
File size: 14.6 KB
Line 
1package org.greenstone.gsdl3.action;
2
3import java.io.BufferedWriter;
4import java.io.File;
5import java.io.FileWriter;
6import java.io.Serializable;
7import java.lang.reflect.Type;
8import java.util.ArrayList;
9import java.util.HashMap;
10import java.util.Iterator;
11import java.util.List;
12import java.util.Map;
13
14import javax.xml.parsers.DocumentBuilderFactory;
15import javax.xml.transform.Transformer;
16import javax.xml.transform.TransformerFactory;
17import javax.xml.transform.dom.DOMSource;
18import javax.xml.transform.stream.StreamResult;
19
20import org.apache.commons.io.FileUtils;
21import org.greenstone.gsdl3.util.DerbyWrapper;
22import org.greenstone.gsdl3.util.GSConstants;
23import org.greenstone.gsdl3.util.GSParams;
24import org.greenstone.gsdl3.util.GSXML;
25import org.greenstone.gsdl3.util.GSXSLT;
26import org.greenstone.gsdl3.util.UserContext;
27import org.greenstone.util.GlobalProperties;
28import org.w3c.dom.Document;
29import org.w3c.dom.Element;
30import org.w3c.dom.Node;
31
32import com.google.gson.Gson;
33import com.google.gson.reflect.TypeToken;
34
35public class DepositorAction extends Action
36{
37 //Sub actions
38 private final String DE_RETRIEVE_WIZARD = "getwizard";
39 private final String DE_DEPOSIT_FILE = "depositfile";
40 private final String DE_CLEAR_CACHE = "clearcache";
41 private final String DE_CLEAR_DATABASE = "cleardatabase";
42
43 // cgi args
44 private final String DE_PAGE_ARG = "dePage";
45 private final String CURRENT_PAGE_ARG = "currentPage";
46 private final String FILE_TO_ADD_ARG = "fileToAdd";
47
48 public Node process(Node message)
49 {
50 Element request = (Element) GSXML.getChildByTagName(message, GSXML.REQUEST_ELEM);
51 Document doc = request.getOwnerDocument();
52
53 UserContext uc = new UserContext((Element) request);
54 String currentUsername = uc.getUsername();
55
56 Element responseMessage = doc.createElement(GSXML.MESSAGE_ELEM);
57 Element response = GSXML.createBasicResponse(doc, this.getClass().getSimpleName());
58 responseMessage.appendChild(response);
59
60 Element param_list = (Element) GSXML.getChildByTagName(request, GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
61 HashMap<String, Serializable> params = GSXML.extractParams(param_list, false);
62
63 String collection = (String) params.get(GSParams.COLLECTION);
64
65 int pageNum = -1;
66 boolean pageNumParseFail = false;
67 try
68 {
69 pageNum = Integer.parseInt(((String) params.get(DE_PAGE_ARG)));
70 }
71 catch (Exception ex)
72 {
73 pageNumParseFail = true;
74 }
75
76 int prevPageNum = -1;
77 boolean prevPageNumFail = false;
78 try
79 {
80 prevPageNum = Integer.parseInt((String) params.get(CURRENT_PAGE_ARG));
81 }
82 catch (Exception ex)
83 {
84 prevPageNumFail = true;
85 }
86
87 DerbyWrapper database = new DerbyWrapper(GlobalProperties.getGSDL3Home() + File.separatorChar + "etc" + File.separatorChar + "usersDB");
88 if (pageNumParseFail)
89 {
90 try
91 {
92 pageNum = Integer.parseInt(database.getUserData(currentUsername, "DE___" + collection + "___CACHED_PAGE"));
93 }
94 catch (Exception ex)
95 {
96 pageNum = 1;
97 }
98 }
99
100 int highestVisitedPage = -1;
101 String result = "";
102 int counter = 1;
103 while (result != null)
104 {
105 result = database.getUserData(currentUsername, "DE___" + collection + "___" + counter + "___VISITED_PAGE");
106 if (result != null)
107 {
108 counter++;
109 }
110 }
111 highestVisitedPage = counter - 1;
112 if (highestVisitedPage == 0)
113 {
114 highestVisitedPage = 1;
115 }
116
117 if (pageNum > highestVisitedPage + 1)
118 {
119 pageNum = highestVisitedPage + 1;
120 }
121
122 database.addUserData(currentUsername, "DE___" + collection + "___" + pageNum + "___VISITED_PAGE", "VISITED");
123
124 String subaction = ((Element) request).getAttribute(GSXML.SUBACTION_ATT);
125 if (subaction.toLowerCase().equals(DE_RETRIEVE_WIZARD))
126 {
127 //Save given metadata
128 StringBuilder saveString = new StringBuilder("[");
129 Iterator<String> paramIter = params.keySet().iterator();
130 while (paramIter.hasNext())
131 {
132 String paramName = paramIter.next();
133 if (paramName.startsWith(GSParams.MD_PREFIX))
134 {
135 Object paramValue = params.get(paramName);
136
137 if (paramValue instanceof String)
138 {
139 saveString.append("{name:\"" + paramName + "\", value:\"" + (String) paramValue + "\"},");
140 }
141 else if (paramValue instanceof HashMap)
142 {
143 HashMap<String, String> subMap = (HashMap<String, String>) paramValue;
144 Iterator<String> subKeyIter = subMap.keySet().iterator();
145 while (subKeyIter.hasNext())
146 {
147 String subName = subKeyIter.next();
148 saveString.append("{name:\"" + paramName + "." + subName + "\", value:\"" + subMap.get(subName) + "\"},");
149 }
150 }
151 }
152 }
153 if (saveString.length() > 2)
154 {
155 saveString.deleteCharAt(saveString.length() - 1);
156 saveString.append("]");
157
158 if (!prevPageNumFail)
159 {
160 database.addUserData(currentUsername, "DE___" + collection + "___" + prevPageNum + "___CACHED_VALUES", saveString.toString());
161 }
162 }
163
164 //Construct the xsl
165 Document compiledDepositorFile = null;
166 try
167 {
168 compiledDepositorFile = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
169 }
170 catch (Exception ex)
171 {
172 ex.printStackTrace();
173 }
174 Document depositorBaseFile = GSXSLT.mergedXSLTDocumentCascade("depositor/depositor.xsl", (String) this.config_params.get(GSConstants.SITE_NAME), collection, (String) this.config_params.get(GSConstants.INTERFACE_NAME), (ArrayList<String>) this.config_params.get(GSConstants.BASE_INTERFACES), false);
175
176 Element numOfPagesElement = GSXML.getNamedElement(depositorBaseFile.getDocumentElement(), "xsl:variable", "name", "numOfPages");
177 int numberOfPages = Integer.parseInt(numOfPagesElement.getTextContent());
178
179 compiledDepositorFile.appendChild(compiledDepositorFile.importNode(depositorBaseFile.getDocumentElement(), true));
180
181 ArrayList<Document> pageDocs = new ArrayList<Document>();
182 ArrayList<String> pageNames = new ArrayList<String>();
183 for (int i = 1; i <= numberOfPages; i++)
184 {
185 Document page = GSXSLT.mergedXSLTDocumentCascade("depositor/de_page" + i + ".xsl", (String) this.config_params.get(GSConstants.SITE_NAME), collection, (String) this.config_params.get(GSConstants.INTERFACE_NAME), (ArrayList<String>) this.config_params.get(GSConstants.BASE_INTERFACES), false);
186 pageDocs.add(page);
187
188 Element pageTitleElem = (Element) GSXML.getNamedElement(page.getDocumentElement(), "xsl:variable", "name", "title");
189 pageNames.add(pageTitleElem.getTextContent());
190
191 Element wizardPageElem = (Element) GSXML.getNamedElement(page.getDocumentElement(), "xsl:template", "name", "wizardPage");
192 wizardPageElem.setAttribute("name", "wizardPage" + i);
193 compiledDepositorFile.getDocumentElement().appendChild(compiledDepositorFile.importNode(wizardPageElem, true));
194 }
195
196 //Create the wizard bar
197 Element wizardBarTemplate = GSXML.getNamedElement(compiledDepositorFile.getDocumentElement(), "xsl:template", "name", "wizardBar");
198 Element wizardBar = compiledDepositorFile.createElement("ul");
199 wizardBar.setAttribute("id", "wizardBar");
200 wizardBarTemplate.appendChild(wizardBar);
201
202 for (int i = 0; i < pageNames.size(); i++)
203 {
204 String pageName = pageNames.get(i);
205 Element pageLi = compiledDepositorFile.createElement("li");
206 if (pageNum == i + 1)
207 {
208 pageLi.setAttribute("class", "wizardStepLink ui-state-active ui-corner-all");
209 }
210 else if (i + 1 > highestVisitedPage + 1 && i + 1 > pageNum + 1)
211 {
212 pageLi.setAttribute("class", "wizardStepLink ui-state-disabled ui-corner-all");
213 }
214 else
215 {
216 pageLi.setAttribute("class", "wizardStepLink ui-state-default ui-corner-all");
217 }
218 Element link = compiledDepositorFile.createElement("a");
219 pageLi.appendChild(link);
220
221 link.setAttribute(GSXML.HREF_ATT, "javascript:;");
222 link.setAttribute("page", "" + (i + 1));
223 link.appendChild(compiledDepositorFile.createTextNode(pageName));
224 wizardBar.appendChild(pageLi);
225 }
226
227 //Add a call-template call to the appropriate page in the xsl
228 Element mainDePageElem = GSXML.getNamedElement(compiledDepositorFile.getDocumentElement(), "xsl:template", "match", "/page");
229 Element wizardContainer = GSXML.getNamedElement(mainDePageElem, "div", "id", "wizardContainer");
230 Element formContainer = GSXML.getNamedElement(wizardContainer, "form", "name", "depositorform");
231 Element callToPage = compiledDepositorFile.createElement("xsl:call-template");
232 callToPage.setAttribute("name", "wizardPage" + pageNum);
233 formContainer.appendChild(callToPage);
234
235 Element cachedValueElement = doc.createElement("cachedValues");
236 response.appendChild(cachedValueElement);
237 try
238 {
239 for (int i = pageNum; i > 0; i--)
240 {
241 Element page = doc.createElement("pageCache");
242 page.setAttribute("pageNum", "" + i);
243 String cachedValues = database.getUserData(currentUsername, "DE___" + collection + "___" + i + "___CACHED_VALUES");
244 if (cachedValues != null)
245 {
246 page.appendChild(doc.createTextNode(cachedValues));
247 cachedValueElement.appendChild(page);
248 }
249 }
250 }
251 catch (Exception ex)
252 {
253 ex.printStackTrace();
254 }
255
256 try
257 {
258 Transformer transformer = TransformerFactory.newInstance().newTransformer();
259
260 File newFileDir = new File(GlobalProperties.getGSDL3Home() + File.separator + "sites" + File.separator + this.config_params.get(GSConstants.SITE_NAME) + File.separator + "collect" + File.separator + collection + File.separator + "transform" + File.separator + "depositor");
261 newFileDir.mkdirs();
262
263 File newFile = new File(newFileDir, File.separator + "compiledDepositor.xsl");
264
265 //initialize StreamResult with File object to save to file
266 StreamResult sresult = new StreamResult(new FileWriter(newFile));
267 DOMSource source = new DOMSource(compiledDepositorFile);
268 transformer.transform(source, sresult);
269 }
270 catch (Exception ex)
271 {
272 ex.printStackTrace();
273 }
274 database.closeDatabase();
275 }
276 else if (subaction.toLowerCase().equals(DE_DEPOSIT_FILE))
277 {
278 String fileToAdd = (String) params.get(FILE_TO_ADD_ARG);
279 File tempFile = new File(GlobalProperties.getGSDL3Home() + File.separator + "tmp" + File.separator + fileToAdd);
280 if (tempFile.exists())
281 {
282 File newFileLocationDir = new File(GlobalProperties.getGSDL3Home() + File.separator + "sites" + File.separator + this.config_params.get(GSConstants.SITE_NAME) + File.separator + "collect" + File.separator + collection + File.separator + "import" + File.separator + fileToAdd);
283 if (!newFileLocationDir.exists())
284 {
285 newFileLocationDir.mkdir();
286 }
287 File newFileLocation = new File(newFileLocationDir, fileToAdd);
288
289 try
290 {
291 FileUtils.copyFile(tempFile, newFileLocation);
292 }
293 catch (Exception ex)
294 {
295 ex.printStackTrace();
296 GSXML.addError(responseMessage, "Failed to copy the deposited file into the collection.");
297 return responseMessage;
298 }
299
300 HashMap<String, String> metadataMap = new HashMap<String, String>();
301 for (int i = pageNum; i > 0; i--)
302 {
303 String cachedValues = database.getUserData(currentUsername, "DE___" + collection + "___" + i + "___CACHED_VALUES");
304 if (cachedValues != null)
305 {
306 Type type = new TypeToken<List<Map<String, String>>>()
307 {
308 }.getType();
309
310 Gson gson = new Gson();
311 List<Map<String, String>> metadataList = gson.fromJson(cachedValues, type);
312 for (Map<String, String> metadata : metadataList)
313 {
314 metadataMap.put(metadata.get("name"), metadata.get("value"));
315 }
316 }
317 }
318
319 String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><!DOCTYPE DirectoryMetadata SYSTEM \"http://greenstone.org/dtd/DirectoryMetadata/1.0/DirectoryMetadata.dtd\"><DirectoryMetadata><FileSet>";
320 xmlString += "<FileName>.*</FileName><Description>";
321 for (String key : metadataMap.keySet())
322 {
323 xmlString += "<Metadata name=\"" + key.substring("MD___".length()) + "\" mode=\"accumulate\">" + metadataMap.get(key) + "</Metadata>";
324 }
325 xmlString += "</Description></FileSet></DirectoryMetadata>";
326
327 File metadataFile = new File(GlobalProperties.getGSDL3Home() + File.separator + "sites" + File.separator + this.config_params.get(GSConstants.SITE_NAME) + File.separator + "collect" + File.separator + collection + File.separator + "import" + File.separator + fileToAdd + File.separator + "metadata.xml");
328
329 try
330 {
331 BufferedWriter bw = new BufferedWriter(new FileWriter(metadataFile));
332 bw.write(xmlString);
333 bw.close();
334 }
335 catch (Exception ex)
336 {
337 ex.printStackTrace();
338 }
339
340 Element buildMessage = doc.createElement(GSXML.MESSAGE_ELEM);
341 Element buildRequest = GSXML.createBasicRequest(doc, GSXML.REQUEST_TYPE_PROCESS, "ImportCollection", uc);
342 buildMessage.appendChild(buildRequest);
343
344 Element paramListElem = doc.createElement(GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
345 buildRequest.appendChild(paramListElem);
346
347 Element collectionParam = doc.createElement(GSXML.PARAM_ELEM);
348 paramListElem.appendChild(collectionParam);
349 collectionParam.setAttribute(GSXML.NAME_ATT, GSXML.COLLECTION_ATT);
350 collectionParam.setAttribute(GSXML.VALUE_ATT, collection);
351
352 Element documentsParam = doc.createElement(GSXML.PARAM_ELEM);
353 paramListElem.appendChild(documentsParam);
354 documentsParam.setAttribute(GSXML.NAME_ATT, "documents");
355 documentsParam.setAttribute(GSXML.VALUE_ATT, fileToAdd);
356
357 Element buildResponseMessage = (Element) this.mr.process(buildMessage);
358
359 response.appendChild(doc.importNode(buildResponseMessage, true));
360 }
361 }
362 else if (subaction.toLowerCase().equals(DE_CLEAR_CACHE))
363 {
364 database.clearUserDataWithPrefix(currentUsername, "DE___");
365 }
366 else if (subaction.toLowerCase().equals(DE_CLEAR_DATABASE))
367 {
368 database.clearUserData();
369 database.clearTrackerData();
370 }
371 else
372 {
373 Element depositorPage = doc.createElement("depositorPage");
374 response.appendChild(depositorPage);
375
376 Element collList = getCollectionsInSite(doc);
377 depositorPage.appendChild(doc.importNode(collList, true));
378 }
379
380 return responseMessage;
381 }
382
383 public Element getCollectionsInSite(Document doc)
384 {
385 Element message = doc.createElement(GSXML.MESSAGE_ELEM);
386 Element request = GSXML.createBasicRequest(doc, GSXML.REQUEST_TYPE_DESCRIBE, "", new UserContext());
387 message.appendChild(request);
388 Element responseMessage = (Element) this.mr.process(message);
389
390 Element response = (Element) GSXML.getChildByTagName(responseMessage, GSXML.RESPONSE_ELEM);
391 Element collectionList = (Element) GSXML.getChildByTagName(response, GSXML.COLLECTION_ELEM + GSXML.LIST_MODIFIER);
392
393 return collectionList;
394 }
395}
Note: See TracBrowser for help on using the repository browser.