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

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