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.RequestUtil;
24
import edu.ucsb.nceas.metacat.util.SessionData;
25
import edu.ucsb.nceas.utilities.XMLUtilities;
26
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
27
import java.io.BufferedReader;
28
import java.io.ByteArrayOutputStream;
29
import java.io.IOException;
30
import java.io.InputStream;
31
import java.io.InputStreamReader;
32
import java.io.Reader;
33
import java.io.StringReader;
34
import java.util.HashMap;
35
import java.util.Iterator;
36
import java.util.Properties;
37
import java.util.Stack;
38
import java.util.TreeMap;
39
import java.util.Vector;
40
import javax.servlet.http.Cookie;
41
import javax.servlet.http.HttpServletRequest;
42
import javax.servlet.http.HttpServletResponse;
43
import javax.servlet.http.HttpSession;
44
import javax.xml.xpath.XPath;
45
import javax.xml.xpath.XPathConstants;
46
import javax.xml.xpath.XPathExpressionException;
47
import javax.xml.xpath.XPathFactory;
48
import org.w3c.dom.DOMException;
49
import org.w3c.dom.Document;
50
import org.w3c.dom.Node;
51
import org.w3c.dom.NodeList;
52
import org.w3c.dom.Text;
53

    
54
/**
55
 *
56
 * @author barteau
57
 */
58
public class ClientViewHelper {
59
    private XPath                                       xpath = XPathFactory.newInstance().newXPath();
60
    private HttpSession                                 clientSession;
61
    private ClientView                                  clientViewBean = null;
62
    private MetacatClient                               metacatClient = null;
63
    private boolean                                     loggedIn = false;
64
    private Document                                    metadataDoc = null;
65
    private int                                         sizeLimit;
66
    private String                                      contactName = "";
67
    
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, String>             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, String>();
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, String>();
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, String> handleClientRequest(MultipartParser multipartParser)  {
222
        String                              result = "", serverResponse;
223
        String                              posted_ldapUserName, tmp, action;
224
        HashMap<String, String>             responseMap = new HashMap<String, String>();
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
            lastDocId = getMetacatClient().getLastDocid(clientViewBean.getUsername());
438
            metaDocId = lastDocId = nextDocId(lastDocId, clientViewBean.getUsername());
439
            
440
            //*** Loop thru all of the data files, get fileName and inputStream.
441
            dataDocIDs = new HashMap();
442
            fileName = new StringBuffer();
443
            while ((inputStream = getNextInputStream(multipartParser, fileName, paramsMap)) != null) {
444
                //*** Get the data file's DOC ID.
445
                nextDocId = nextDocId(lastDocId, clientViewBean.getUsername());
446
                
447
                fileInfo = parseFileInfo(fileName.toString());
448
                dataDocIDs.put(nextDocId, fileInfo);
449
                
450
                //*** Upload the data file to metacat.
451
                getMetacatClient().upload(nextDocId, fileName.toString(), inputStream, Integer.MAX_VALUE);
452
                
453
                lastDocId = nextDocId;
454
                fileName = new StringBuffer();
455
            }
456
            
457
            if (ClientFgdcHelper.isFGDC(getMetadataDoc())) {
458
                sendIt = ClientFgdcHelper.handlePackageUpload(metaDocId, dataDocIDs, contactName, metaFileName, getMetadataDoc());
459
            } else {
460
                //TODO add other types of metadata grammars here...
461
                System.out.println("ClientViewHelper.handlePackageUpload: not an FGDC file = " + fileName);
462
                result = fileName + " is not an FGDC file.  Files not uploaded.";
463
                sendIt = false;
464
            }
465
            
466
            if (sendIt) {
467
                //*** Upload the metadata file to metacat.
468
                reader = XMLUtilities.getDOMTreeAsReader(metadataDoc.getDocumentElement(), false);
469
                getMetacatClient().insert(metaDocId, reader, null);
470
                
471
                result = "MetaCat Package Inserted:  the Document Identifier is " + metaDocId;
472
                reader.close();
473
                //*** Grant the public read access to the meta file.
474
                if (paramsMap.containsKey("publicAccess")) {
475
                    docIdStack = new Stack();
476
                    docIdStack.addAll(dataDocIDs.keySet());
477
                    setPublicAccess(this.PERMISSION_TYPE_ALLOW, metaDocId, docIdStack);
478
                }
479
            }
480
        } else {
481
            result = "The first file must be an XML Metadata file.  Files not uploaded.";
482
        }
483
        if (inputStream != null)
484
            inputStream.close();
485
        return(result);
486
    }
487
    
488
    private String setPublicAccess(String permissionType, String metaDocId, Stack docIdStack)
489
    throws InsufficientKarmaException, MetacatException, MetacatInaccessibleException {
490
        String                      result = " for Documents ";
491
        String                      docId, lst = metaDocId, permOrder;
492
        
493
        if (permissionType.equals("allow"))
494
            permOrder = "denyFirst";
495
        else
496
            permOrder = "allowFirst";
497
        
498
        getMetacatClient().setAccess(metaDocId, "public", "read", permissionType, permOrder);
499
        //*** Grant the public read access to the data files.
500
        while(!docIdStack.isEmpty()) {
501
            docId = (String) docIdStack.pop();
502
            getMetacatClient().setAccess(docId, "public", "read", permissionType, permOrder);
503
            lst += ", " + docId;
504
        }
505
        result = "Changed public read access to '" + permissionType + "' for " + result + lst;
506
        return(result);
507
    }
508
    
509
    private String handleChangeAccess(String metaDocId, String permissionType) throws Exception {
510
        Stack                       dataDocIDs;
511
        String                      result = "", xpathExpr = null;
512
        
513
        setMetadataDoc(metaDocId);
514
        //*** Build list of sub-documents.
515
        if (clientViewBean.getContentStandard().equals(ClientView.FEDERAL_GEOGRAPHIC_DATA_COMMITTEE)) {
516
            xpathExpr = ClientFgdcHelper.SUB_DOCS_PATH;
517
        } else if (clientViewBean.getContentStandard().equals(ClientView.ECOLOGICAL_METADATA_LANGUAGE)) {
518
            xpathExpr = null; //TODO  - EML
519
        }
520
        if (xpathExpr != null) {
521
            dataDocIDs = getNodeTextStack(xpath, xpathExpr, getMetadataDoc().getDocumentElement());
522
            result = setPublicAccess(permissionType, metaDocId, dataDocIDs);
523
        }
524
        return(result);
525
    }
526
    
527
    public String handleFileUpdate(MultipartParser multipartParser) throws Exception {
528
        String                      result = "", fNm, action, lastDocId, newDocId, xPathQuery, qFrmt;
529
        InputStream                 inputStream;
530
        HashMap                     paramsMap;
531
        StringBuffer                fileName;
532
        Iterator                    iterIt;
533
        boolean                     sendIt;
534
        String                      metadataDocId, fileInfo[];
535
        
536
        paramsMap = new HashMap();
537
        fileName = new StringBuffer();
538
        if ((inputStream = getNextInputStream(multipartParser, fileName, paramsMap)) != null) {
539
            action = (String) paramsMap.get("action");
540
            //*** Get the Doc Id.
541
            lastDocId = (String) paramsMap.get("docid");
542
            
543
            //*** Get the metadata Doc Id.
544
            metadataDocId = (String) paramsMap.get("metadataDocId");
545
            clientViewBean.setMetaFileDocId(metadataDocId);
546
            
547
            //*** Get the qformat.
548
            qFrmt = (String) paramsMap.get("qformat");
549
            clientViewBean.setQformat(qFrmt);
550
            
551
            fNm = fileName.toString();
552
            
553
            try {
554
                if (lastDocId.equals(metadataDocId)) { //*** This is the metadata file.
555
                    //*** Keep it here for updating.
556
                    setMetadataDoc(inputStream);
557
                    if (ClientFgdcHelper.isFGDC(getMetadataDoc())) {
558
                        clientViewBean.setContentStandard(ClientView.FEDERAL_GEOGRAPHIC_DATA_COMMITTEE);
559
                        if (!ClientFgdcHelper.hasMetacatInfo(lastDocId, getMetadataDoc())) {
560
                            
561
                            //*** Save the Doc Id for re-query.
562
                            clientViewBean.setMetaFileDocId(lastDocId);
563
                            clientViewBean.setAction("read"); //*** Set for re-query.
564
                            result = "Update not performed: the Metadata file has no prior Metacat info in it.";
565
                        } else {
566
                            xPathQuery = ClientFgdcHelper.XPATH_QUERY_TEMPLATE.replaceFirst("%1s", lastDocId);
567
                            newDocId = updateMetadataDoc(lastDocId, xPathQuery, fNm);
568
                            
569
                            //*** Save the Doc Id for re-query.
570
                            clientViewBean.setMetaFileDocId(newDocId);
571
                            clientViewBean.setAction("read"); //*** Set for re-query.
572
                            result = "Updated to new document (from " + lastDocId + " to " + newDocId + ")";
573
                        }
574
                    } else {
575
                        //***TODO This is EML.
576
                        clientViewBean.setContentStandard(ClientView.ECOLOGICAL_METADATA_LANGUAGE);
577
                        
578
                        //*** Save the Doc Id for re-query.
579
                        clientViewBean.setMetaFileDocId(lastDocId);
580
                        clientViewBean.setAction("read"); //*** Set for re-query.
581
                        result = "Currently this functionality only supports FGDC metadata.";
582
                    }
583
                } else {
584
                    //*** This is a data file.
585
                    //*** Query for the metadata, we need to update it with the new data file doc id.
586
                    setMetadataDoc(metadataDocId);
587
                    
588
                    if (ClientFgdcHelper.isFGDC(getMetadataDoc())) {
589
                        clientViewBean.setContentStandard(ClientView.FEDERAL_GEOGRAPHIC_DATA_COMMITTEE);
590
                        fileInfo = parseFileInfo(fNm);
591
                        
592
                        xPathQuery = ClientFgdcHelper.FGDC_DATA_FILE_QUERY_XPATH.replaceFirst("%1s", lastDocId);
593
                        newDocId = nextVersion(lastDocId, xPathQuery);
594
                        ClientFgdcHelper.updateFileNameAndType(getMetadataDoc().getDocumentElement(), newDocId, fileInfo);
595
                        //*** Upload the data file to metacat.
596
                        getMetacatClient().upload(newDocId, fNm, inputStream, Integer.MAX_VALUE);
597
                        result = "Updated to new document (from " + lastDocId + " to " + newDocId + ")";
598
                        
599
                        //*** Upload the metadata file to metacat.
600
                        xPathQuery = ClientFgdcHelper.XPATH_QUERY_TEMPLATE.replaceFirst("%1s", metadataDocId);
601
                        newDocId = updateMetadataDoc(metadataDocId, xPathQuery, null);
602
                        
603
                        //*** Save the new meta Doc Id for re-query.
604
                        clientViewBean.setMetaFileDocId(newDocId);
605
                        clientViewBean.setAction("read"); //*** Set for re-query.
606
                        
607
                    } else {
608
                        //***TODO This is EML.
609
                        clientViewBean.setContentStandard(ClientView.ECOLOGICAL_METADATA_LANGUAGE);
610
                        
611
                        //*** Save the old meta Doc Id for re-query.
612
                        clientViewBean.setMetaFileDocId(metadataDocId);
613
                        clientViewBean.setAction("read"); //*** Set for re-query.
614
                        result = "Currently this functionality only supports FGDC metadata.";
615
                    }
616
                }
617
            } catch (java.io.IOException ex) {
618
                ex.printStackTrace();
619
            }
620
        } else {
621
            result = "Please enter the updated file path/name.";
622
        }
623
        clientViewBean.setMessage(ClientView.UPDATE_MESSAGE, result);
624
        return(result);
625
    }
626
    
627
    private String updateMetadataDoc(String lastDocId, String docIdPath, String origFileName) {
628
        String                      newDocId = null;
629
        Reader                      reader;
630
        
631
        //*** Update the metadata with the new Doc Id version.
632
        try {
633
            newDocId = nextVersion(lastDocId, docIdPath);
634
            if (origFileName != null) {
635
                if (clientViewBean.getContentStandard().equals(ClientView.FEDERAL_GEOGRAPHIC_DATA_COMMITTEE))
636
                    ClientFgdcHelper.updateMetadataFileName(getMetadataDoc().getDocumentElement(), newDocId, origFileName);
637
                else
638
                    ; //TODO EML, etc.
639
            }
640
            //*** Upload the metadata file to metacat.
641
            reader = XMLUtilities.getDOMTreeAsReader(getMetadataDoc().getDocumentElement(), false);
642
            getMetacatClient().update(newDocId, reader, null);
643
            reader.close();
644
        } catch (Exception ex) {
645
            ex.printStackTrace();
646
        }
647
        return(newDocId);
648
    }
649
    
650
    private InputStream getNextInputStream(MultipartParser multipartParser, StringBuffer fileName, HashMap paramsMap)
651
    throws IOException {
652
        InputStream                     result = null;
653
        Part                            part;
654
        String                          parmName = null, value = null, fnam;
655
        
656
        while ((part = multipartParser.readNextPart()) != null) {
657
            if (part.isParam()) {
658
                parmName = part.getName();
659
                value = ((ParamPart) part).getStringValue();
660
                paramsMap.put(parmName, value);
661
                
662
            } else if (part.isFile()) {
663
                fnam = ((FilePart) part).getFileName();
664
                if (fnam != null && !fnam.equals("")) {
665
                    //*** File name is passed back via StringBuffer fileName param.
666
                    fileName.append(fnam);
667
                    result = ((FilePart) part).getInputStream();
668
                    break;
669
                }
670
            }
671
        }
672
        return(result);
673
    }
674
    
675
    private void getRemainingParameters(MultipartParser multipartParser, HashMap paramsMap)
676
    throws IOException {
677
        InputStream                     result = null;
678
        Part                            part;
679
        String                          parmName = null, value = null, fnam;
680
        
681
        while ((part = multipartParser.readNextPart()) != null) {
682
            if (part.isParam()) {
683
                parmName = part.getName();
684
                value = ((ParamPart) part).getStringValue();
685
                paramsMap.put(parmName, value);
686
            }
687
        }
688
    }
689
    
690
    /**
691
     * Queries Metacat for document listings, and returns the results in a TreeMap,
692
     * where the key is the Doc Id, and the value is the Create Date.  If the document
693
     * contains the specified 'returnfield', an addtional entry will be created with
694
     * the value being a Vector of sub-DocId's.  The key of this entry will be the
695
     * original DocId with some addtional text added.
696
     * Reads bean properties 'pathExpr' (String[]), 'pathValue' (String)
697
     * and 'returnfield' (String).
698
     * @return TreeMap
699
     */
700
    public TreeMap getSelectQueryMap() {
701
        TreeMap                         result;
702
        Document                        doc;
703
        NodeList                        nodeLst, subNodeLst;
704
        Node                            node, subNode;
705
        String                          key, val, paramExpr, paramVal;
706
        String                          value, returnFld;
707
        String                          path;
708
        Vector                          optGroup;
709
        final String                    DOCID_EXPR = "./docid";
710
        final String                    DOCNAME_EXPR = "./createdate";
711
        final String                    PARAM_EXPR = "./param[@name='%1s']";
712
        
713
        path = clientViewBean.getPathExpr();
714
        returnFld = clientViewBean.getReturnfield();
715
        value = clientViewBean.getPathValue();
716
        
717
        result = new TreeMap();
718
        //paramExpr = String.format(PARAM_EXPR, returnFld);
719
        paramExpr = PARAM_EXPR.replaceFirst("%1s", returnFld);
720
        //*** Query the database ***
721
        doc = query(path, value, returnFld);
722
        //*** Build the TreeMap to return ***
723
        try {
724
            nodeLst = (NodeList) xpath.evaluate("/resultset/document", doc, XPathConstants.NODESET);
725
            for (int i = 0; i < nodeLst.getLength(); i++) {
726
                node = nodeLst.item(i);
727
                key = xpath.evaluate(DOCID_EXPR, node);
728
                val = xpath.evaluate(DOCNAME_EXPR, node);
729
                result.put(key, key + " (" + val + ")");
730
                
731
                //*** returnfield values ***
732
                subNodeLst = (NodeList) xpath.evaluate(paramExpr, node, XPathConstants.NODESET);
733
                if (subNodeLst.getLength() > 0) {
734
                    optGroup = new Vector();
735
                    for (int k = 0; k < subNodeLst.getLength(); k++) {
736
                        subNode =  subNodeLst.item(k);
737
                        paramVal = xpath.evaluate("text()", subNode);
738
                        optGroup.add(paramVal);
739
                    }
740
                    result.put(key + " Data Files", optGroup);
741
                }
742
                
743
            }
744
        } catch (XPathExpressionException ex) {
745
            ex.printStackTrace();
746
        }
747
        return(result);
748
    }
749
    
750
    /**
751
     * Query metacat for documents that 'CONTAINS' the value at the specified XPath
752
     * expression.  Additionally, returns another non-standard field value.
753
     * Standard info contains: DocId, DocName, DocType, CreateDate, and UpdateDate.
754
     * @param pathExpr String contianing an XPath expression.
755
     * @param pathValue String containing a comparison value at the XPath expression.
756
     * @param returnFld String containing an XPath expression to a field which will be returned
757
     * in addition to the standard info.
758
     * @return DOM Document containing the results.
759
     */
760
    public Document query(String pathExpr, String pathValue, String returnFld) {
761
        Document                        result = null;
762
        InputStream                     response;
763
        BufferedReader                  buffy;
764
        Properties                      prop;
765
        
766
        try {
767
            prop = new Properties();
768
            prop.put("action", "query");
769
            prop.put("qformat", "xml");
770
            prop.put(pathExpr, pathValue);
771
            if (returnFld != null) {
772
                prop.put("returnfield", returnFld);
773
            }
774
            
775
            response = metacatClient.sendParameters(prop);
776
            if (response != null) {
777
                buffy = new BufferedReader(new InputStreamReader(response));
778
                result = XMLUtilities.getXMLReaderAsDOMDocument(buffy);
779
            }
780
        } catch (IOException ex) {
781
            ex.printStackTrace();
782
        } catch (Exception ex) {
783
            ex.printStackTrace();
784
        }
785
        return(result);
786
    }
787
    
788
    public void setMetadataDoc(Document doc) {
789
        metadataDoc = doc;
790
    }
791
    
792
    public void setMetadataDoc(String docId) throws Exception {
793
        Document                        doc = null;
794
        BufferedReader                  buffy;
795
        InputStream                     response;
796

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