Project

General

Profile

1
/*
2
 * ClientViewHelper.java
3
 *
4
 * Created on June 25, 2007, 9:57 AM
5
 *
6
 * To change this template, choose Tools | Template Manager
7
 * and open the template in the editor.
8
 */
9

    
10
package edu.ucsb.nceas.metacat.clientview;
11

    
12
import com.oreilly.servlet.multipart.FilePart;
13
import com.oreilly.servlet.multipart.MultipartParser;
14
import com.oreilly.servlet.multipart.ParamPart;
15
import com.oreilly.servlet.multipart.Part;
16
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
17
import edu.ucsb.nceas.metacat.client.MetacatClient;
18
import edu.ucsb.nceas.metacat.client.MetacatException;
19
import edu.ucsb.nceas.metacat.client.MetacatFactory;
20
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
21
import edu.ucsb.nceas.metacat.properties.PropertyService;
22
import edu.ucsb.nceas.metacat.service.SessionService;
23
import edu.ucsb.nceas.metacat.util.SessionData;
24
import edu.ucsb.nceas.utilities.XMLUtilities;
25
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
26
import java.io.BufferedReader;
27
import java.io.ByteArrayOutputStream;
28
import java.io.IOException;
29
import java.io.InputStream;
30
import java.io.InputStreamReader;
31
import java.io.Reader;
32
import java.io.StringReader;
33
import java.util.HashMap;
34
import java.util.Iterator;
35
import java.util.Properties;
36
import java.util.Stack;
37
import java.util.TreeMap;
38
import java.util.Vector;
39
import javax.servlet.http.Cookie;
40
import javax.servlet.http.HttpServletRequest;
41
import javax.servlet.http.HttpServletResponse;
42
import javax.servlet.http.HttpSession;
43
import javax.xml.xpath.XPath;
44
import javax.xml.xpath.XPathConstants;
45
import javax.xml.xpath.XPathExpressionException;
46
import javax.xml.xpath.XPathFactory;
47
import org.w3c.dom.DOMException;
48
import org.w3c.dom.Document;
49
import org.w3c.dom.Node;
50
import org.w3c.dom.NodeList;
51
import org.w3c.dom.Text;
52

    
53
/**
54
 *
55
 * @author barteau
56
 */
57
public class ClientViewHelper {
58
    private XPath                                       xpath = XPathFactory.newInstance().newXPath();
59
    private HttpSession                                 clientSession;
60
    private ClientView                                  clientViewBean = null;
61
    private MetacatClient                               metacatClient = null;
62
    private boolean                                     loggedIn = false;
63
    private Document                                    metadataDoc = null;
64
    private int                                         sizeLimit;
65
    private String                                      contactName = "";
66
    
67
    private static final String                         LDAP_TEMPLATE = "uid=%1s,o=%2s,dc=ecoinformatics,dc=org";
68
    
69
    public static final String                          DOWNLOAD_ACTION = "Download";
70
    
71
    public static final String                          PERMISSION_TYPE_ALLOW = "allow";
72
    
73
    public static final String                          PERMISSION_TYPE_DISALLOW = "deny";
74
    
75
    /**
76
     * Creates a new instance of ClientViewHelper, using info in an HttpServletRequest
77
     * for initializing.
78
     * @param request HttpServletRequest, sent from the client browser.
79
     * @throws edu.ucsb.nceas.metacat.client.MetacatInaccessibleException Thrown
80
     */
81
    public ClientViewHelper(HttpServletRequest request) throws MetacatInaccessibleException {
82
        String                              host, context;
83
        
84
        clientSession = request.getSession(false);
85
        host = request.getHeader("host");
86
        context = request.getContextPath();
87
        init(host, context);
88
    }
89
    
90
    /**
91
     * Creates a new instance of ClientViewHelper, using parameter values
92
     * for initializing.  This constructor is plain java code so it's the portal of
93
     * choice for JUnit testing.
94
     * @param host The host with port (if needed), such as "localhost:8084".
95
     * @param context The application root context.
96
     * @param bean ClientView instance, with pre-populated values.
97
     * @throws edu.ucsb.nceas.metacat.client.MetacatInaccessibleException thrown
98
     */
99
    public ClientViewHelper(String host, String context, ClientView bean) throws MetacatInaccessibleException {
100
        clientViewBean = bean;
101
        init(host, context);
102
    }
103
    
104
    private void init(String host, String context) throws MetacatInaccessibleException {
105
        String                              metacatPath = "http://%1s%2s/metacat";
106
        String                              tmp;
107
        
108
        tmp = metacatPath.replaceFirst("%1s", host);
109
        metacatPath = tmp.replaceFirst("%2s", context);
110
        metacatClient = (MetacatClient) MetacatFactory.createMetacatConnection(metacatPath);
111
        try {
112
        	sizeLimit = 
113
        		(new Integer(PropertyService.getProperty("replication.datafilesizelimit"))).intValue();
114
        } catch (PropertyNotFoundException pnfe) {
115
        	throw new MetacatInaccessibleException(pnfe.getMessage());
116
        }
117
    }
118
    
119
    /**
120
     * Main web API method for handling various actions.
121
     * @param request HttpServletRequest
122
     * @param response HttpServletResponse
123
     * @return String message
124
     */
125
    public String clientRequest(HttpServletRequest request, HttpServletResponse response)  {
126
        String                              result = null, action, contentType;
127
        MultipartParser                     multipartParser;
128
        HashMap<String, Object>             responseMap;
129
        
130
        getMetacatClient().setSessionId(request.getSession().getId());
131
        
132
        if (clientViewBean == null) {
133
            clientViewBean = (ClientView) clientSession.getAttribute(ClientView.CLIENT_VIEW_BEAN);
134
            
135
            if (clientViewBean == null) {
136
            	//make a new one and shove it in the session
137
            	clientViewBean = new ClientView();
138
            	clientSession.setAttribute(ClientView.CLIENT_VIEW_BEAN, clientViewBean);
139
            }
140
        }
141
        
142
        if (clientViewBean != null) {
143
            action = clientViewBean.getAction();
144
            contentType = request.getContentType();
145
            
146
            //*** BEGIN: manual bind params to bean (if we arrived here via the ClientViewHelper.jspx).
147
            if (action == null || action.equals("")) {
148
                if (contentType != null && contentType.indexOf("multipart/form-data") > -1) {
149
                    action = "Upload";
150
                } else {
151
                    action = request.getParameter("action");
152
                    clientViewBean.setDocId(request.getParameter("docid"));
153
                    clientViewBean.setMetaFileDocId(request.getParameter("metadataDocId"));
154
                    clientViewBean.setQformat(request.getParameter("qformat"));
155
                    clientViewBean.setPublicAccess(request.getParameter("publicAccess") != null);
156
                    clientViewBean.setContentStandard(request.getParameter("contentStandard"));
157
                }
158
                clientViewBean.setAction(action);
159
            }
160
            //*** END: manual bind params to bean.
161
            
162
            if (action != null) {
163
                if (action.equals("Login")) {
164
                    responseMap = handleClientRequest(null);
165
                    //*** Now that the action has been processed, clear it.
166
                    clientViewBean.setAction("");
167
                    if (isLoggedIn()) {
168
//                    	HttpSession session = request.getSession(false);                 	
169
//                    	session.setAttribute("ClientViewHelper", this);
170
                    	Cookie jSessionCookie = new Cookie("JSESSIONID", clientViewBean.getSessionid());
171
                    	response.addCookie(jSessionCookie);
172
                    }
173
                } else if (action.equals("Logout")) {
174
                    responseMap = handleClientRequest(null);
175
                    clientViewBean.setAction("");
176
                } else if (action.equals("Upload")) {
177
                    try {
178
                        //*** Init the MultipartParser.
179
                        multipartParser = new MultipartParser(request, sizeLimit * 1024 * 1024);
180
                        responseMap = handleClientRequest(multipartParser);
181
                    } catch (IOException ex) {
182
                        responseMap = new HashMap<String, Object>();
183
                        responseMap.put("message", ex.getMessage());
184
                    }
185
                    clientViewBean.setAction("");
186
                } else if (action.equals("Download")) {
187
                    responseMap = handleClientRequest(null);
188
                    try {
189
                        handleDownloadResponse(responseMap, response);
190
                    } catch (IOException ex) {
191
                        responseMap = new HashMap<String, Object>();
192
                        responseMap.put("message", ex.getMessage());
193
                    }
194
                    
195
                } else if (action.equals("Set Access")) {
196
                    responseMap = handleClientRequest(null);
197
                    clientViewBean.setAction("");
198
                } else {
199
                    responseMap = handleClientRequest(null);
200
                }
201
                result = (String) responseMap.get("message");
202
            }
203
        } else {
204
            result = "ClientViewHelper.clientRequest: ClientView bean is not instantiated.";
205
        }
206
        return(result);
207
    }
208
    
209
    /**
210
     * Main method for handling various actions.
211
     *
212
     * Note: This is mostly plain java code so it is JUnit friendly
213
     * (pass null as the MulipartParser).
214
     *
215
     * @param multipartParser Only needed if the action is "Upload".
216
     * @return HashMap containing "message", and possibly several other values.  If
217
     * the action is Download, than this will contain all needed values
218
     * to pass to handleDownloadResponse.
219
     */
220
    public HashMap<String, Object> handleClientRequest(MultipartParser multipartParser)  {
221
        String                              result = "", serverResponse;
222
        String                              posted_ldapUserName, tmp, action;
223
        HashMap<String, Object>             responseMap = new HashMap<String, Object>();
224
        
225
        
226
        if (clientViewBean != null) {
227
            action = clientViewBean.getAction();
228
            if (action != null) {
229
                try {
230
                    if (action.equals("Login")) {
231
                        tmp = LDAP_TEMPLATE.replaceFirst("%1s", clientViewBean.getUsername());
232
                        posted_ldapUserName = tmp.replaceFirst("%2s", clientViewBean.getOrganization());
233
                        
234
//                        if (metacatSessionId != null) {
235
//                        	metacatClient.setSessionId(metacatSessionId);
236
//                        }                       
237
                        serverResponse = metacatClient.login(posted_ldapUserName, clientViewBean.getPassword());
238
                        setLoggedIn(serverResponse);
239
                        result = parseXml("message", serverResponse);
240
                        contactName = parseXml("name", serverResponse);
241
                        clientViewBean.setMessage(ClientView.LOGIN_MESSAGE, result);
242
                        clientViewBean.setMessage(ClientView.UPLOAD_MESSAGE, "");
243
                        if (isLoggedIn()) {
244
                            clientViewBean.setSessionid(metacatClient.getSessionId());
245
                            
246
                        }
247
                    } else if (action.equals("Logout")) {
248
                        result = metacatClient.logout();
249
                        setLoggedIn(result);
250
                        result = parseXml("message", result);
251
                        clientViewBean.setMessage(ClientView.LOGIN_MESSAGE, result);
252
                        clientViewBean.setMessage(ClientView.UPLOAD_MESSAGE, "");
253
                        if (!isLoggedIn()) {
254
                            clientViewBean.setUsername("");
255
                            clientViewBean.setPassword("");
256
                            clientViewBean.setOrganization("");
257
                            clientViewBean.setSessionid(null);
258
                        }
259
                    } else if (action.equals("Delete")) {
260
                        ClientFgdcHelper.clientDeleteRequest(clientViewBean, this);
261
                        clientViewBean.setAction("read"); //*** Set for re-query.
262
                        //*** Note: the clientViewBean will already have the updated Meta Doc Id.
263
                        
264
                    } else if (action.equals("Upload")) {
265
                        //*** Only process request if logged in.
266
                        if (isLoggedIn()) {
267
                            if (multipartParser == null)
268
                                result = "ClientViewHelper.handleClientRequest: MultipartParser is not instantiated.";
269
                            else
270
                                result = handlePackageUpload(clientViewBean, multipartParser);
271
                        } else {
272
                            result = "You must be logged in to perform an upload.";
273
                        }
274
                        clientViewBean.setMessage(ClientView.UPLOAD_MESSAGE, result);
275
                    } else if (action.equals("Update")) {
276
                        result = "This is not implemented here.  Call ClientViewHelper.jspx";
277
                    } else if (action.equals("Scope")) {
278
                        result = handleDocIdSelect();
279
                        clientViewBean.setMessage(ClientView.SELECT_MESSAGE, result);
280
                    } else if (action.equals("Download")) {
281
                        responseMap = download(clientViewBean);
282
                    } else if (action.equals("Set Access")) {
283
                        result = handleChangeAccess(clientViewBean.getMetaFileDocId(),
284
                                (clientViewBean.isPublicAccess()? PERMISSION_TYPE_ALLOW: PERMISSION_TYPE_DISALLOW));
285
                        clientViewBean.setMessage(ClientView.UPDATE_MESSAGE, result);
286
                    } else {
287
                        result = action + " action not recognized.";
288
                    }
289
                } catch (Exception ex) {
290
                    result = ex.getMessage();
291
                    clientViewBean.setMessage(ClientView.ERROR_MESSAGE, result);
292
                    ex.printStackTrace();
293
                }
294
            }
295
        } else {
296
            result = "ClientViewHelper.clientRequest: ClientView bean is not instantiated.";
297
        }
298
        responseMap.put("message", result);
299
        return(responseMap);
300
    }
301
    
302
    /**
303
     * This is a convenience method to reduce the amount of code in a Metacat Client.
304
     * It handles creating/reusing (per session) an instance of a ClientViewHelper.
305
     * @param request Since this is intended to be used by an Http client, it is passed the
306
     * available "request" variable (the HttpServletRequest).
307
     * @throws edu.ucsb.nceas.metacat.client.MetacatInaccessibleException Received by MetacatFactory.
308
     * @return ClientViewHelper instance.
309
     */
310
    public static ClientViewHelper clientViewHelperInstance(HttpServletRequest request) {
311
        ClientViewHelper result;
312
        
313
        String sessionId = request.getSession(false).getId();
314
        
315
        result = (ClientViewHelper) request.getSession().getAttribute("ClientViewHelper");
316
        if (result == null) {
317
            try {
318
                result = new ClientViewHelper(request);
319
                request.getSession().setAttribute("ClientViewHelper", result);
320
            } catch (MetacatInaccessibleException ex) {
321
                ex.printStackTrace();
322
            }
323
        }
324
        
325
        if (result.clientViewBean == null) {
326
        	result.clientViewBean = (ClientView) request.getSession().getAttribute(ClientView.CLIENT_VIEW_BEAN);
327
            
328
            if (result.clientViewBean == null) {
329
            	//make a new one and shove it in the session
330
            	result.clientViewBean = new ClientView();
331
            	request.getSession().setAttribute(ClientView.CLIENT_VIEW_BEAN, result.clientViewBean);
332
            }
333
        }
334
        
335
        boolean oldLoginValue = result.loggedIn;
336
        result.setLoggedIn(SessionService.getInstance().validateSession(sessionId));
337
        if (result.isLoggedIn()) {
338
        	SessionData sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
339
        	result.setUserName(sessionData.getName());
340
        }
341
        
342
        if (!oldLoginValue || result.loggedIn) {
343
        	result.clientViewBean.setMessage(ClientView.UPLOAD_MESSAGE, "");
344
        }
345
        
346
        return(result);
347
    }
348
    
349
    /**
350
     * A convenience method to be used by client code that requires
351
     * the user to be logged in.  NOTE: setUser() must have been called first,
352
     * otherwise it will always return false.
353
     * @return boolean  true if user has logged in for this session, false otherwise.
354
     */
355
    public boolean isLoggedIn() {
356
        return(loggedIn);
357
    }
358
    
359
    /**
360
     * After calling "login(ldapUserName, pwd)", call this with the username
361
     * and servers response message.  You can than use isLoggedIn() to determine if
362
     * the user is logged in, getLoginResponseElement(), etc.  The user name will also
363
     * used by calls to doMetadataUpload() for Document Id creation (scope).
364
     * @param userName User name
365
     * @param serverResponse XML login response sent from Metacat.
366
     */
367
    public void setLoggedIn(String serverResponse) {
368
        loggedIn = (serverResponse != null && serverResponse.indexOf("login") > -1);
369
    }
370
    
371
    public void setLoggedIn(boolean isLoggedIn) {
372
        this.loggedIn = isLoggedIn;
373
    }
374
    
375
    public void setUserName(String userName) {
376
        clientViewBean.setUsername(userName);
377
    }
378
    
379
    public String parseXml(String elementName, String xml) {
380
        String                      result = null;
381
        Document                    doc;
382
        
383
        try {
384
            doc = XMLUtilities.getXMLReaderAsDOMDocument(new StringReader(xml));
385
            result = (String) xpath.evaluate(elementName, doc.getDocumentElement(), XPathConstants.STRING);
386
            if (result != null)
387
                result = result.trim();
388
        } catch (IOException ex) {
389
            ex.printStackTrace();
390
        } catch (XPathExpressionException ex) {
391
            ex.printStackTrace();
392
        }
393
        return(result);
394
    }
395
    
396
    public String handleDocIdSelect() {
397
        String                              result = "";
398
        TreeMap                             allDocIds;
399
        
400
        if (!clientViewBean.getPathValue().equals("")) {
401
            allDocIds = getSelectQueryMap();
402
            result = ClientHtmlHelper.mapToHtmlSelect(allDocIds, "docId", "width: 240", 10);
403
        }
404
        return(result);
405
    }
406
    
407
    /**
408
     * Handles metadata file and data file uploads for inserting new
409
     * Metacat data packages.  Note: if content type is not "multipart/form-data",
410
     * nothing will happen.
411
     * @param request HTTP request.
412
     * @return A 1-line status message for the user.
413
     */
414
    public String handlePackageUpload(ClientView clientViewBean, MultipartParser multipartParser) throws Exception {
415
        String                      result = "", contentType, formatType;
416
        String                      lastDocId, nextDocId, metaDocId, metaFileName;
417
        String                      fileInfo[];
418
        Reader                      reader;
419
        int                         sizeLimit, idx;
420
        InputStream                 inputStream;
421
        HashMap                     paramsMap, dataDocIDs;
422
        StringBuffer                fileName;
423
        boolean                     sendIt;
424
        Iterator                    iterIt;
425
        Stack                       docIdStack;
426
        
427
        //*** Get the First file, which should be the metadata file.
428
        paramsMap = new HashMap();
429
        fileName = new StringBuffer();
430
        inputStream = getNextInputStream(multipartParser, fileName, paramsMap);
431
        metaFileName = fileName.toString();
432
        if (metaFileName.toLowerCase().endsWith(".xml")) {
433
            //*** Keep it here for updating.
434
            setMetadataDoc(inputStream);
435
            //*** Get the Metadata File's DOC ID.
436
            lastDocId = getMetacatClient().getLastDocid(clientViewBean.getUsername());
437
            metaDocId = lastDocId = nextDocId(lastDocId, clientViewBean.getUsername());
438
            
439
            //*** Loop thru all of the data files, get fileName and inputStream.
440
            dataDocIDs = new HashMap();
441
            fileName = new StringBuffer();
442
            while ((inputStream = getNextInputStream(multipartParser, fileName, paramsMap)) != null) {
443
                //*** Get the data file's DOC ID.
444
                nextDocId = nextDocId(lastDocId, clientViewBean.getUsername());
445
                
446
                fileInfo = parseFileInfo(fileName.toString());
447
                dataDocIDs.put(nextDocId, fileInfo);
448
                
449
                //*** Upload the data file to metacat.
450
                getMetacatClient().upload(nextDocId, fileName.toString(), inputStream, Integer.MAX_VALUE);
451
                
452
                lastDocId = nextDocId;
453
                fileName = new StringBuffer();
454
            }
455
            
456
            if (ClientFgdcHelper.isFGDC(getMetadataDoc())) {
457
                sendIt = ClientFgdcHelper.handlePackageUpload(metaDocId, dataDocIDs, contactName, metaFileName, getMetadataDoc());
458
            } else {
459
                //TODO add other types of metadata grammars here...
460
                System.out.println("ClientViewHelper.handlePackageUpload: not an FGDC file = " + fileName);
461
                result = fileName + " is not an FGDC file.  Files not uploaded.";
462
                sendIt = false;
463
            }
464
            
465
            if (sendIt) {
466
                //*** Upload the metadata file to metacat.
467
                reader = XMLUtilities.getDOMTreeAsReader(metadataDoc.getDocumentElement(), false);
468
                getMetacatClient().insert(metaDocId, reader, null);
469
                
470
                result = "MetaCat Package Inserted:  the Document Identifier is " + metaDocId;
471
                reader.close();
472
                //*** Grant the public read access to the meta file.
473
                if (paramsMap.containsKey("publicAccess")) {
474
                    docIdStack = new Stack();
475
                    docIdStack.addAll(dataDocIDs.keySet());
476
                    setPublicAccess(this.PERMISSION_TYPE_ALLOW, metaDocId, docIdStack);
477
                }
478
            }
479
        } else {
480
            result = "The first file must be an XML Metadata file.  Files not uploaded.";
481
        }
482
        if (inputStream != null)
483
            inputStream.close();
484
        return(result);
485
    }
486
    
487
    private String setPublicAccess(String permissionType, String metaDocId, Stack docIdStack)
488
    throws InsufficientKarmaException, MetacatException, MetacatInaccessibleException {
489
        String                      result = " for Documents ";
490
        String                      docId, lst = metaDocId, permOrder;
491
        
492
        if (permissionType.equals("allow"))
493
            permOrder = "denyFirst";
494
        else
495
            permOrder = "allowFirst";
496
        
497
        getMetacatClient().setAccess(metaDocId, "public", "read", permissionType, permOrder);
498
        //*** Grant the public read access to the data files.
499
        while(!docIdStack.isEmpty()) {
500
            docId = (String) docIdStack.pop();
501
            getMetacatClient().setAccess(docId, "public", "read", permissionType, permOrder);
502
            lst += ", " + docId;
503
        }
504
        result = "Changed public read access to '" + permissionType + "' for " + result + lst;
505
        return(result);
506
    }
507
    
508
    private String handleChangeAccess(String metaDocId, String permissionType) throws Exception {
509
        Stack                       dataDocIDs;
510
        String                      result = "", xpathExpr = null;
511
        
512
        setMetadataDoc(metaDocId);
513
        //*** Build list of sub-documents.
514
        if (clientViewBean.getContentStandard().equals(ClientView.FEDERAL_GEOGRAPHIC_DATA_COMMITTEE)) {
515
            xpathExpr = ClientFgdcHelper.SUB_DOCS_PATH;
516
        } else if (clientViewBean.getContentStandard().equals(ClientView.ECOLOGICAL_METADATA_LANGUAGE)) {
517
            xpathExpr = null; //TODO  - EML
518
        }
519
        if (xpathExpr != null) {
520
            dataDocIDs = getNodeTextStack(xpath, xpathExpr, getMetadataDoc().getDocumentElement());
521
            result = setPublicAccess(permissionType, metaDocId, dataDocIDs);
522
        }
523
        return(result);
524
    }
525
    
526
    public String handleFileUpdate(MultipartParser multipartParser) throws Exception {
527
        String                      result = "", fNm, action, lastDocId, newDocId, xPathQuery, qFrmt;
528
        InputStream                 inputStream;
529
        HashMap                     paramsMap;
530
        StringBuffer                fileName;
531
        Iterator                    iterIt;
532
        boolean                     sendIt;
533
        String                      metadataDocId, fileInfo[];
534
        
535
        paramsMap = new HashMap();
536
        fileName = new StringBuffer();
537
        if ((inputStream = getNextInputStream(multipartParser, fileName, paramsMap)) != null) {
538
            action = (String) paramsMap.get("action");
539
            //*** Get the Doc Id.
540
            lastDocId = (String) paramsMap.get("docid");
541
            
542
            //*** Get the metadata Doc Id.
543
            metadataDocId = (String) paramsMap.get("metadataDocId");
544
            clientViewBean.setMetaFileDocId(metadataDocId);
545
            
546
            //*** Get the qformat.
547
            qFrmt = (String) paramsMap.get("qformat");
548
            clientViewBean.setQformat(qFrmt);
549
            
550
            fNm = fileName.toString();
551
            
552
            try {
553
                if (lastDocId.equals(metadataDocId)) { //*** This is the metadata file.
554
                    //*** Keep it here for updating.
555
                    setMetadataDoc(inputStream);
556
                    if (ClientFgdcHelper.isFGDC(getMetadataDoc())) {
557
                        clientViewBean.setContentStandard(ClientView.FEDERAL_GEOGRAPHIC_DATA_COMMITTEE);
558
                        if (!ClientFgdcHelper.hasMetacatInfo(lastDocId, getMetadataDoc())) {
559
                            
560
                            //*** Save the Doc Id for re-query.
561
                            clientViewBean.setMetaFileDocId(lastDocId);
562
                            clientViewBean.setAction("read"); //*** Set for re-query.
563
                            result = "Update not performed: the Metadata file has no prior Metacat info in it.";
564
                        } else {
565
                            xPathQuery = ClientFgdcHelper.XPATH_QUERY_TEMPLATE.replaceFirst("%1s", lastDocId);
566
                            newDocId = updateMetadataDoc(lastDocId, xPathQuery, fNm);
567
                            
568
                            //*** Save the Doc Id for re-query.
569
                            clientViewBean.setMetaFileDocId(newDocId);
570
                            clientViewBean.setAction("read"); //*** Set for re-query.
571
                            result = "Updated to new document (from " + lastDocId + " to " + newDocId + ")";
572
                        }
573
                    } else {
574
                        //***TODO This is EML.
575
                        clientViewBean.setContentStandard(ClientView.ECOLOGICAL_METADATA_LANGUAGE);
576
                        
577
                        //*** Save the Doc Id for re-query.
578
                        clientViewBean.setMetaFileDocId(lastDocId);
579
                        clientViewBean.setAction("read"); //*** Set for re-query.
580
                        result = "Currently this functionality only supports FGDC metadata.";
581
                    }
582
                } else {
583
                    //*** This is a data file.
584
                    //*** Query for the metadata, we need to update it with the new data file doc id.
585
                    setMetadataDoc(metadataDocId);
586
                    
587
                    if (ClientFgdcHelper.isFGDC(getMetadataDoc())) {
588
                        clientViewBean.setContentStandard(ClientView.FEDERAL_GEOGRAPHIC_DATA_COMMITTEE);
589
                        fileInfo = parseFileInfo(fNm);
590
                        
591
                        xPathQuery = ClientFgdcHelper.FGDC_DATA_FILE_QUERY_XPATH.replaceFirst("%1s", lastDocId);
592
                        newDocId = nextVersion(lastDocId, xPathQuery);
593
                        ClientFgdcHelper.updateFileNameAndType(getMetadataDoc().getDocumentElement(), newDocId, fileInfo);
594
                        //*** Upload the data file to metacat.
595
                        getMetacatClient().upload(newDocId, fNm, inputStream, Integer.MAX_VALUE);
596
                        result = "Updated to new document (from " + lastDocId + " to " + newDocId + ")";
597
                        
598
                        //*** Upload the metadata file to metacat.
599
                        xPathQuery = ClientFgdcHelper.XPATH_QUERY_TEMPLATE.replaceFirst("%1s", metadataDocId);
600
                        newDocId = updateMetadataDoc(metadataDocId, xPathQuery, null);
601
                        
602
                        //*** Save the new meta Doc Id for re-query.
603
                        clientViewBean.setMetaFileDocId(newDocId);
604
                        clientViewBean.setAction("read"); //*** Set for re-query.
605
                        
606
                    } else {
607
                        //***TODO This is EML.
608
                        clientViewBean.setContentStandard(ClientView.ECOLOGICAL_METADATA_LANGUAGE);
609
                        
610
                        //*** Save the old meta Doc Id for re-query.
611
                        clientViewBean.setMetaFileDocId(metadataDocId);
612
                        clientViewBean.setAction("read"); //*** Set for re-query.
613
                        result = "Currently this functionality only supports FGDC metadata.";
614
                    }
615
                }
616
            } catch (java.io.IOException ex) {
617
                ex.printStackTrace();
618
            }
619
        } else {
620
            result = "Please enter the updated file path/name.";
621
        }
622
        clientViewBean.setMessage(ClientView.UPDATE_MESSAGE, result);
623
        return(result);
624
    }
625
    
626
    private String updateMetadataDoc(String lastDocId, String docIdPath, String origFileName) {
627
        String                      newDocId = null;
628
        Reader                      reader;
629
        
630
        //*** Update the metadata with the new Doc Id version.
631
        try {
632
            newDocId = nextVersion(lastDocId, docIdPath);
633
            if (origFileName != null) {
634
                if (clientViewBean.getContentStandard().equals(ClientView.FEDERAL_GEOGRAPHIC_DATA_COMMITTEE))
635
                    ClientFgdcHelper.updateMetadataFileName(getMetadataDoc().getDocumentElement(), newDocId, origFileName);
636
                else
637
                    ; //TODO EML, etc.
638
            }
639
            //*** Upload the metadata file to metacat.
640
            reader = XMLUtilities.getDOMTreeAsReader(getMetadataDoc().getDocumentElement(), false);
641
            getMetacatClient().update(newDocId, reader, null);
642
            reader.close();
643
        } catch (Exception ex) {
644
            ex.printStackTrace();
645
        }
646
        return(newDocId);
647
    }
648
    
649
    private InputStream getNextInputStream(MultipartParser multipartParser, StringBuffer fileName, HashMap paramsMap)
650
    throws IOException {
651
        InputStream                     result = null;
652
        Part                            part;
653
        String                          parmName = null, value = null, fnam;
654
        
655
        while ((part = multipartParser.readNextPart()) != null) {
656
            if (part.isParam()) {
657
                parmName = part.getName();
658
                value = ((ParamPart) part).getStringValue();
659
                paramsMap.put(parmName, value);
660
                
661
            } else if (part.isFile()) {
662
                fnam = ((FilePart) part).getFileName();
663
                if (fnam != null && !fnam.equals("")) {
664
                    //*** File name is passed back via StringBuffer fileName param.
665
                    fileName.append(fnam);
666
                    result = ((FilePart) part).getInputStream();
667
                    break;
668
                }
669
            }
670
        }
671
        return(result);
672
    }
673
    
674
    private void getRemainingParameters(MultipartParser multipartParser, HashMap paramsMap)
675
    throws IOException {
676
        InputStream                     result = null;
677
        Part                            part;
678
        String                          parmName = null, value = null, fnam;
679
        
680
        while ((part = multipartParser.readNextPart()) != null) {
681
            if (part.isParam()) {
682
                parmName = part.getName();
683
                value = ((ParamPart) part).getStringValue();
684
                paramsMap.put(parmName, value);
685
            }
686
        }
687
    }
688
    
689
    /**
690
     * Queries Metacat for document listings, and returns the results in a TreeMap,
691
     * where the key is the Doc Id, and the value is the Create Date.  If the document
692
     * contains the specified 'returnfield', an addtional entry will be created with
693
     * the value being a Vector of sub-DocId's.  The key of this entry will be the
694
     * original DocId with some addtional text added.
695
     * Reads bean properties 'pathExpr' (String[]), 'pathValue' (String)
696
     * and 'returnfield' (String).
697
     * @return TreeMap
698
     */
699
    public TreeMap getSelectQueryMap() {
700
        TreeMap                         result;
701
        Document                        doc;
702
        NodeList                        nodeLst, subNodeLst;
703
        Node                            node, subNode;
704
        String                          key, val, paramExpr, paramVal;
705
        String                          value, returnFld;
706
        String                          path;
707
        Vector                          optGroup;
708
        final String                    DOCID_EXPR = "./docid";
709
        final String                    DOCNAME_EXPR = "./createdate";
710
        final String                    PARAM_EXPR = "./param[@name='%1s']";
711
        
712
        path = clientViewBean.getPathExpr();
713
        returnFld = clientViewBean.getReturnfield();
714
        value = clientViewBean.getPathValue();
715
        
716
        result = new TreeMap();
717
        //paramExpr = String.format(PARAM_EXPR, returnFld);
718
        paramExpr = PARAM_EXPR.replaceFirst("%1s", returnFld);
719
        //*** Query the database ***
720
        doc = query(path, value, returnFld);
721
        //*** Build the TreeMap to return ***
722
        try {
723
            nodeLst = (NodeList) xpath.evaluate("/resultset/document", doc, XPathConstants.NODESET);
724
            for (int i = 0; i < nodeLst.getLength(); i++) {
725
                node = nodeLst.item(i);
726
                key = xpath.evaluate(DOCID_EXPR, node);
727
                val = xpath.evaluate(DOCNAME_EXPR, node);
728
                result.put(key, key + " (" + val + ")");
729
                
730
                //*** returnfield values ***
731
                subNodeLst = (NodeList) xpath.evaluate(paramExpr, node, XPathConstants.NODESET);
732
                if (subNodeLst.getLength() > 0) {
733
                    optGroup = new Vector();
734
                    for (int k = 0; k < subNodeLst.getLength(); k++) {
735
                        subNode =  subNodeLst.item(k);
736
                        paramVal = xpath.evaluate("text()", subNode);
737
                        optGroup.add(paramVal);
738
                    }
739
                    result.put(key + " Data Files", optGroup);
740
                }
741
                
742
            }
743
        } catch (XPathExpressionException ex) {
744
            ex.printStackTrace();
745
        }
746
        return(result);
747
    }
748
    
749
    /**
750
     * Query metacat for documents that 'CONTAINS' the value at the specified XPath
751
     * expression.  Additionally, returns another non-standard field value.
752
     * Standard info contains: DocId, DocName, DocType, CreateDate, and UpdateDate.
753
     * @param pathExpr String contianing an XPath expression.
754
     * @param pathValue String containing a comparison value at the XPath expression.
755
     * @param returnFld String containing an XPath expression to a field which will be returned
756
     * in addition to the standard info.
757
     * @return DOM Document containing the results.
758
     */
759
    public Document query(String pathExpr, String pathValue, String returnFld) {
760
        Document                        result = null;
761
        InputStream                     response;
762
        BufferedReader                  buffy;
763
        Properties                      prop;
764
        
765
        try {
766
            prop = new Properties();
767
            prop.put("action", "query");
768
            prop.put("qformat", "xml");
769
            prop.put(pathExpr, pathValue);
770
            if (returnFld != null) {
771
                prop.put("returnfield", returnFld);
772
            }
773
            
774
            response = metacatClient.sendParameters(prop);
775
            if (response != null) {
776
                buffy = new BufferedReader(new InputStreamReader(response));
777
                result = XMLUtilities.getXMLReaderAsDOMDocument(buffy);
778
            }
779
        } catch (IOException ex) {
780
            ex.printStackTrace();
781
        } catch (Exception ex) {
782
            ex.printStackTrace();
783
        }
784
        return(result);
785
    }
786
    
787
    public void setMetadataDoc(Document doc) {
788
        metadataDoc = doc;
789
    }
790
    
791
    public void setMetadataDoc(String docId) throws Exception {
792
        Document                        doc = null;
793
        BufferedReader                  buffy;
794
        InputStream                     response;
795

    
796
        response = metacatClient.read(docId);
797
        if (response != null) {
798
            buffy = new BufferedReader(new InputStreamReader(response));
799
            doc = XMLUtilities.getXMLReaderAsDOMDocument(buffy);
800
            response.close();
801
        }
802
        setMetadataDoc(doc);
803
    }
804
    
805
    public void setMetadataDoc(InputStream ioStream) throws IOException {
806
        BufferedReader                          buffy;
807
        
808
        if (ioStream != null) {
809
            buffy = new BufferedReader(new InputStreamReader(ioStream));
810
            metadataDoc = XMLUtilities.getXMLReaderAsDOMDocument(buffy);
811
        }
812
    }
813
    
814
    public Document getMetadataDoc() {
815
        return(metadataDoc);
816
    }
817
    
818
    public String nextVersion(String lastDocId, String xPathQuery) throws XPathExpressionException {
819
        String                      result = null, tokens[], scope, ready2Split, tmp;
820
        int                         vers, docNum;
821
        final int                   LAST_TOKEN = 2;
822
        final String                TEMPLATE = "%1s.%2d.%3d";
823
        Node                        node;
824
        
825
        //*** Parse the last Doc Id, and increment the version number.
826
        if(lastDocId != null && lastDocId.indexOf(".") > -1) {
827
            ready2Split = lastDocId.replace('.','~'); //*** This is necessary for the split to work.
828
            tokens = ready2Split.split("~");
829
            if(tokens.length > LAST_TOKEN && !tokens[LAST_TOKEN].equals("")) {
830
                scope = tokens[LAST_TOKEN - 2];
831
                docNum = Integer.parseInt(tokens[LAST_TOKEN - 1]);
832
                try {
833
                    vers = Integer.parseInt(tokens[LAST_TOKEN]);
834
                    //result = String.format(TEMPLATE, scope, docNum, 1 + vers);
835
                    tmp = TEMPLATE.replaceFirst("%1s", scope);
836
                    tmp = tmp.replaceFirst("%2d", String.valueOf(docNum));
837
                    result = tmp.replaceFirst("%3d", String.valueOf(vers + 1));
838
                    
839
                } catch (NumberFormatException ex) {
840
                    //*** In case the lastDocId has something other than a number.
841
                    //result = String.format(TEMPLATE, scope, docNum, 1);
842
                    tmp = TEMPLATE.replaceFirst("%1s", scope);
843
                    tmp = tmp.replaceFirst("%2d", String.valueOf(docNum));
844
                    result = tmp.replaceFirst("%3d", "1");
845
                }
846
            } else {
847
                //*** In case the lastDocId ends with a '.'
848
                result = lastDocId + "1";
849
            }
850
        } else {
851
            //*** In case of missing doc Id.
852
            result = null;
853
        }
854
        //*** Update the Doc Id in the metadata file.
855
        if (getMetadataDoc() != null) {
856
            node = (Node) xpath.evaluate(xPathQuery, getMetadataDoc().getDocumentElement(), XPathConstants.NODE);
857
            setTextContent(xpath, node, result);
858
        }
859
        return(result);
860
    }
861
    
862
    private String nextDocId(String lastDocId, String scope) {
863
        String                      result = null, tokens[], tmp;
864
        int                         vers;
865
        String                      template = scope.toLowerCase() + ".%1d.%2d";
866
        
867
        if(lastDocId != null && lastDocId.indexOf(".") > -1) {
868
            lastDocId = lastDocId.replace('.','~'); //*** This is necessary for the split to work.
869
            tokens = lastDocId.split("~");
870
            if(tokens.length > 1 && !tokens[1].equals("")) {
871
                try {
872
                    vers = Integer.parseInt(tokens[1]);
873
                    //result = String.format(template, 1 + vers, 1);
874
                    tmp = template.replaceFirst("%1d", String.valueOf(1 + vers));
875
                    result = tmp.replaceFirst("%2d", "1");
876
                } catch (NumberFormatException ex) {
877
                    //*** In case the lastDocId has something other than a number.
878
                    //result = String.format(template, 1, 1);
879
                    tmp = template.replaceFirst("%1d", "1");
880
                    result = tmp.replaceFirst("%2d", "1");
881
                }
882
            } else {
883
                //*** In case the lastDocId ends with a '.'
884
                //result = String.format(template, 1, 1);
885
                tmp = template.replaceFirst("%1d", "1");
886
                result = tmp.replaceFirst("%2d", "1");
887
            }
888
        } else {
889
            //*** In case there isn't any doc Id's with the user name.
890
            //result = String.format(template, 1, 1);
891
            tmp = template.replaceFirst("%1d", "1");
892
            result = tmp.replaceFirst("%2d", "1");
893
        }
894
        return(result);
895
    }
896
    
897
    public MetacatClient getMetacatClient() {
898
        return(metacatClient);
899
    }
900
    
901
    //*** BEGIN: Static utility methods ***
902
    
903
    public static String[] parseFileInfo(String fileName) {
904
        String[]                        result = new String[2];
905
        int                             idx;
906
        String                          formatType;
907
        
908
        //*** Set the file format (just using file extension for now).
909
        idx = fileName.lastIndexOf(".");
910
        if (idx > 1)
911
            formatType = fileName.substring(idx+1).toUpperCase();
912
        else
913
            formatType = "";
914
        
915
        result[ClientView.FORMAT_TYPE] = formatType;
916
        result[ClientView.FILE_NAME] = fileName.toString();
917
        return(result);
918
    }
919
    
920
    public static void updateNodeText(Node root, XPath xPath, String expression, String text) {
921
        Node                    targetNode;
922
        
923
        if (text != null && !text.equals("")) {
924
            try {
925
                targetNode = (Node) xPath.evaluate(expression, root, XPathConstants.NODE);
926
                setTextContent(xPath, targetNode, text);
927
                //targetNode.setTextContent(text);
928
            } catch (XPathExpressionException ex) {
929
                ex.printStackTrace();
930
            }
931
        }
932
    }
933
    
934
    
935
    public static Node getNode(XPath xPath, String expression, Node root) {
936
        Node                        result = null;
937
        
938
        try {
939
            result = (Node) xPath.evaluate(expression, root, XPathConstants.NODE);
940
        } catch (XPathExpressionException ex) {
941
            ex.printStackTrace();
942
        }
943
        return(result);
944
        
945
    }
946
    
947
    public static String getNodeText(XPath xPath, String expression, Node root) {
948
        Node                        node;
949
        String                      result = null;
950
        
951
        node = getNode(xPath, expression, root);
952
        if (node != null && !node.equals(""))
953
            result = getTextContent(xPath, node);
954
        //result = node.getTextContent(); Not in java 1.4
955
        return(result);
956
    }
957
    
958
    public static String[] getNodeTextList(XPath xPath, String expression, Node root) {
959
        NodeList                    nodes;
960
        String                      result[] = new String[0];
961
        int                         size;
962
        
963
        try {
964
            nodes = (NodeList) xPath.evaluate(expression, root, XPathConstants.NODESET);
965
            if (nodes != null && (size = nodes.getLength()) > 0) {
966
                result = new String[size];
967
                for(int i = 0; i < size; i++)
968
                    result[i] = getTextContent(xPath, nodes.item(i));
969
                //result[i] = nodes.item(i).getTextContent(); Not in java 1.4
970
            }
971
        } catch (XPathExpressionException ex) {
972
            ex.printStackTrace();
973
        }
974
        return(result);
975
    }
976
    
977
    public static Stack getNodeTextStack(XPath xpathInstance, String xpathExpr, Node parentNode) {
978
        String                      nodeLst[];
979
        Stack                       result = new Stack();
980
        
981
        nodeLst = getNodeTextList(xpathInstance, xpathExpr, parentNode);
982
        for(int i = 0; i < nodeLst.length; i++)
983
            result.push(nodeLst[i]);
984
        return(result);
985
    }
986
    
987
    public static String getStringFromInputStream(InputStream input) {
988
        StringBuffer result = new StringBuffer();
989
        BufferedReader in = new BufferedReader(new InputStreamReader(input));
990
        String line;
991
        try {
992
            while ((line = in.readLine()) != null) {
993
                result.append(line);
994
            }
995
        } catch (IOException e) {
996
            System.out.println("ClientViewHelper.getStringFromInputStream: " + e);
997
        }
998
        return result.toString();
999
    }
1000
    
1001
    //*** END: Static utility methods ***
1002
    
1003
    public String makeRedirectUrl() {
1004
        String                      result, docId, message;
1005
        
1006
        docId = clientViewBean.getMetaFileDocId();
1007
        if (clientViewBean.getAction().equals(DOWNLOAD_ACTION)) {
1008
            result = null;
1009
        } else if (docId != null && !docId.equals("")) {
1010
            message = clientViewBean.getMessage(ClientView.UPDATE_MESSAGE);
1011
            result = "metacat?action=read&qformat=" +clientViewBean.getQformat()
1012
            + "&docid=" + docId + "&sessionid=" + clientViewBean.getSessionid() + "&message=" + message;
1013
        } else {
1014
            result = "style/skins/" + clientViewBean.getQformat() + "/confirm.jsp";
1015
        }
1016
        //*** Reset bean action property.
1017
        clientViewBean.setAction("");
1018
        return(result);
1019
    }
1020
    
1021
    private HashMap<String, Object> download(ClientView bean) {
1022
        Properties                      args;
1023
        InputStream                     inStream;
1024
        String                          docId, metaId, fNm = null, pth, txtLst[];
1025
        String                          msg = "File '~' (~) downloaded";
1026
        Node                            branchRoot, metaRoot;
1027
        ByteArrayOutputStream           outStream;
1028
        int                             intMe;
1029
        HashMap<String, Object>         responseMap = new HashMap<String, Object>();
1030
        
1031
        docId = bean.getDocId();
1032
        metaId = bean.getMetaFileDocId();
1033
        if (docId != null && metaId != null && !docId.equals("") && !metaId.equals("")) {
1034
            //*** Properties args: key=param_value, value=param_name.
1035
            args = new Properties();
1036
            args.put("read", "action");
1037
            try {
1038
                //*** First, retrieve the metadata and get the original filename.
1039
                //*** Also, if this is the metadata, get a list of docId's for the package.
1040
                setMetadataDoc(metaId);
1041
                metaRoot = getMetadataDoc().getDocumentElement();
1042
                if (ClientFgdcHelper.isFGDC(getMetadataDoc())) {
1043
                    //*** FGDC
1044
                    if (docId.equals(metaId)) { //*** This is the metadata file.
1045
                        pth = ClientFgdcHelper.FGDC_DOCID_ROOT_XPATH.replaceFirst("%1s", docId);
1046
                        branchRoot = getNode(xpath, pth, getMetadataDoc());
1047
                        fNm = getNodeText(xpath, ClientFgdcHelper.FGDC_FILE_NAME_XPATH, branchRoot);
1048
                        //include the filename for the docid
1049
                        args.put(fNm, docId);
1050
                        fNm = toZipFileName(fNm);
1051
                        responseMap.put("contentType", "application/zip");
1052
                        //*** Get the list of docId's for the entire package.
1053
                        args.put(metaId, "docid");
1054
                        txtLst = getNodeTextList(xpath, ClientFgdcHelper.FGDC_DATA_FILE_NODES_XPATH, branchRoot);
1055
                        for (int i = 0; i < txtLst.length; i++) {
1056
                        	String additionalDocId = txtLst[i];
1057
                        	if (additionalDocId != null && additionalDocId.length() > 1) {
1058
                        		//look up the filename from the metadata
1059
                        		String tempPath = ClientFgdcHelper.PATH4ANCESTOR.replaceFirst("%1s", additionalDocId);
1060
                        		tempPath = tempPath.replaceFirst("%2s", "digform");
1061
                                Node tempBranchRoot = getNode(xpath, tempPath, getMetadataDoc());
1062
                                String tempFileName = getNodeText(xpath, ClientFgdcHelper.FGDC_DATA_FILE_NAME_XPATH, tempBranchRoot);
1063
                                //include the docid
1064
                        		args.put(additionalDocId, "docid");
1065
                        		//include the filename for the docid
1066
                        		args.put(tempFileName, additionalDocId);
1067
                        	}
1068
                        }
1069
                        args.put("zip", "qformat");
1070
                    } else { //*** This is a data file.
1071
                        pth = ClientFgdcHelper.PATH4ANCESTOR.replaceFirst("%1s", docId);
1072
                        pth = pth.replaceFirst("%2s", "digform");
1073
                        branchRoot = getNode(xpath, pth, getMetadataDoc());
1074
                        fNm = getNodeText(xpath, ClientFgdcHelper.FGDC_DATA_FILE_NAME_XPATH, branchRoot);
1075
                        responseMap.put("contentType", "application/octet-stream");
1076
                        args.put(docId, "docid");
1077
                        args.put("xml", "qformat");
1078
                    }
1079
                } else {
1080
                    //*** TODO: EML -  this is just some basic code to start with.
1081
                    if (docId.equals(metaId)) {
1082
                        fNm = "emlMetadata.xml";
1083
                        txtLst = new String[] {docId};
1084
                        args.put(txtLst[0], "docid");
1085
                        args.put("zip", "qformat");
1086
                        responseMap.put("contentType", "application/zip");
1087
                    } else {
1088
                        fNm = "emlData.dat";
1089
                        args.put("xml", "qformat");
1090
                        args.put(docId, "docid");
1091
                        responseMap.put("contentType", "application/octet-stream");
1092
                    }
1093
                }
1094
                
1095
                //*** Set the filename in the response.
1096
                responseMap.put("Content-Disposition", "attachment; filename=" + fNm);
1097
                
1098
                //*** Next, read the file from metacat.
1099
                inStream = metacatClient.sendParameters(args);
1100
                
1101
                //*** Then, convert the input stream into an output stream.
1102
                outStream = new ByteArrayOutputStream();
1103
                while ((intMe = inStream.read()) != -1) {
1104
                    outStream.write(intMe);
1105
                }
1106
                
1107
                //*** Now, write the output stream to the response.
1108
                responseMap.put("outputStream", outStream);
1109
                
1110
                //*** Finally, set the message for the user interface to display.
1111
                msg = msg.replaceFirst("~", fNm);
1112
                msg = msg.replaceFirst("~", docId);
1113
                bean.setMessage(ClientView.SELECT_MESSAGE, msg);
1114
            } catch (Exception ex) {
1115
                ex.printStackTrace();
1116
                bean.setMessage(ClientView.SELECT_MESSAGE, ex.getMessage());
1117
            }
1118
        }
1119
        responseMap.put("message", bean.getMessage(ClientView.SELECT_MESSAGE));
1120
        return(responseMap);
1121
    }
1122
    
1123
    private void handleDownloadResponse(HashMap responseMap, HttpServletResponse response) throws IOException {
1124
        ByteArrayOutputStream                       outStream;
1125
        String                                      contentDisposition, contentType;
1126
        
1127
        contentType = (String) responseMap.get("contentType");
1128
        contentDisposition = (String) responseMap.get("Content-Disposition");
1129
        outStream = (ByteArrayOutputStream) responseMap.get("outputStream");
1130
        
1131
        response.setContentType(contentType);
1132
        response.setHeader("Content-Disposition", contentDisposition);
1133
        response.setContentLength(outStream.size());
1134
        outStream.writeTo(response.getOutputStream());
1135
        response.flushBuffer();
1136
    }
1137
    
1138
    public static String toZipFileName(String fileName) {
1139
        String                      result = "metacat";
1140
        int                         idx;
1141
        
1142
        if (fileName != null && !fileName.equals("") && !fileName.equals(".")) {
1143
            idx = fileName.indexOf('.');
1144
            if (idx > -1)
1145
                result = fileName.substring(0, idx);
1146
            else
1147
                result = fileName;
1148
        }
1149
        result += ".zip";
1150
        return(result);
1151
    }
1152
    
1153
    public static void setTextContent(XPath xPath, Node elementNode, String content) throws DOMException {
1154
        Text                        textNode, newTxtNode;
1155
        Document                    document;
1156
        
1157
        textNode = (Text) getNode(xPath, "text()", elementNode);
1158
        if (textNode != null) {
1159
            if (isElementContentWhitespace(textNode)) {
1160
                //*** If there is an existing text node, and it's whitespace,
1161
                //*** create a new text node and insert it before whitespace.
1162
                document = elementNode.getOwnerDocument();
1163
                newTxtNode = document.createTextNode(content);
1164
                elementNode.insertBefore(newTxtNode, textNode);
1165
            } else {
1166
                //*** If there is an existing text node, and it has content,
1167
                //*** overwrite the existing text.
1168
                textNode.setNodeValue(content);
1169
            }
1170
        } else {
1171
            //*** If there isn't an existing text node,
1172
            //*** create a new text node and append it to the elementNode.
1173
            document = elementNode.getOwnerDocument();
1174
            newTxtNode = document.createTextNode(content);
1175
            elementNode.appendChild(newTxtNode);
1176
        }
1177
    }
1178
    
1179
    public static String getTextContent(XPath xPath, Node elementNode) throws DOMException {
1180
        String                      result = "";
1181
        Text                        textNode;
1182
        
1183
        if (elementNode.getNodeType() != Node.TEXT_NODE)
1184
            textNode = (Text) getNode(xPath, "text()", elementNode);
1185
        else
1186
            textNode = (Text) elementNode;
1187
        if (textNode != null)
1188
            result = textNode.getNodeValue();
1189
        return(result);
1190
    }
1191
    
1192
    public static boolean isElementContentWhitespace(Text textNode) {
1193
        boolean                     result = false;
1194
        String                      val;
1195
        
1196
        if ((val = textNode.getNodeValue()) != null) {
1197
            if (val != null) {
1198
                val = val.trim();
1199
                result = (val.length() == 0);
1200
            }
1201
        }
1202
        return(result);
1203
    }
1204
    
1205
}
(5-5/5)