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

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