Project

General

Profile

« Previous | Next » 

Revision 3530

Added by barteau about 17 years ago

Seperated web API code, from plain java code, by creating seperate constructors and handling Http stuff in just two methods: "clientRequest" and "handleDownloadResponse".
Results in using HttpServlet code in an isolated/thin layer, making it easier to test and reuse all other methods.

View differences:

src/edu/ucsb/nceas/metacat/clientview/ClientViewHelper.java
27 27
import java.io.InputStreamReader;
28 28
import java.io.Reader;
29 29
import java.io.StringReader;
30
import java.util.Collection;
31 30
import java.util.HashMap;
32 31
import java.util.Iterator;
33 32
import java.util.Properties;
......
68 67
    public static final String                          PERMISSION_TYPE_DISALLOW = "deny";
69 68
    
70 69
    /**
71
     * Creates a new instance of ClientViewHelper
70
     * Creates a new instance of ClientViewHelper, using info in an HttpServletRequest
71
     * for initializing.
72
     * @param request HttpServletRequest, sent from the client browser.
73
     * @throws edu.ucsb.nceas.metacat.client.MetacatInaccessibleException Thrown
72 74
     */
73 75
    public ClientViewHelper(HttpServletRequest request) throws MetacatInaccessibleException {
74
        String                              metacatPath = "http://%1s%2s/metacat";
75
        String                              host, context, button, tmp;
76
        String                              host, context;
76 77
        
77 78
        clientSession = request.getSession();
78
        
79 79
        host = request.getHeader("host");
80 80
        context = request.getContextPath();
81
        init(host, context);
82
    }
83
    
84
    /**
85
     * Creates a new instance of ClientViewHelper, using parameter values
86
     * for initializing.  This constructor is plain java code so it's the portal of
87
     * choice for JUnit testing.
88
     * @param host The host with port (if needed), such as "localhost:8084".
89
     * @param context The application root context.
90
     * @param bean ClientView instance, with pre-populated values.
91
     * @throws edu.ucsb.nceas.metacat.client.MetacatInaccessibleException thrown
92
     */
93
    public ClientViewHelper(String host, String context, ClientView bean) throws MetacatInaccessibleException {
94
        clientViewBean = bean;
95
        init(host, context);
96
    }
97
    
98
    private void init(String host, String context) throws MetacatInaccessibleException {
99
        String                              metacatPath = "http://%1s%2s/metacat";
100
        String                              tmp;
101
        
81 102
        tmp = metacatPath.replaceFirst("%1s", host);
82 103
        metacatPath = tmp.replaceFirst("%2s", context);
83 104
        metacatClient = (MetacatClient) MetacatFactory.createMetacatConnection(metacatPath);
84 105
        sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit"))).intValue();
85 106
    }
86 107
    
108
    /**
109
     * Main web API method for handling various actions.
110
     * @param request HttpServletRequest
111
     * @param response HttpServletResponse
112
     * @return String message
113
     */
87 114
    public String clientRequest(HttpServletRequest request, HttpServletResponse response)  {
88
        String                              result = null, action, message, serverResponse;
89
        String                              button, contentType, posted_ldapUserName, tmp;
115
        String                              result = null, action, contentType;
90 116
        MultipartParser                     multipartParser;
91
        int                                 fileIdx;
117
        HashMap                             responseMap;
92 118
        
93 119
        if (clientViewBean == null)
94 120
            clientViewBean = (ClientView) clientSession.getAttribute(ClientView.CLIENT_VIEW_BEAN);
......
96 122
        if (clientViewBean != null) {
97 123
            action = clientViewBean.getAction();
98 124
            contentType = request.getContentType();
99
        
125
            
100 126
            //*** BEGIN: manual bind params to bean (if we arrived here via the ClientViewHelper.jspx).
101 127
            if (action == null || action.equals("")) {
102 128
                if (contentType != null && contentType.contains("multipart/form-data")) {
103 129
                    action = "Upload";
104 130
                } else {
105 131
                    action = request.getParameter("action");
106
                    clientViewBean.setAction(action);
107 132
                    clientViewBean.setDocId(request.getParameter("docid"));
108 133
                    clientViewBean.setMetaFileDocId(request.getParameter("metadataDocId"));
109 134
                    clientViewBean.setQformat(request.getParameter("qformat"));
110 135
                    clientViewBean.setPublicAccess(request.getParameter("publicAccess") != null);
111 136
                    clientViewBean.setContentStandard(request.getParameter("contentStandard"));
112 137
                }
138
                clientViewBean.setAction(action);
113 139
            }
114 140
            //*** END: manual bind params to bean.
115 141
            
116 142
            if (action != null) {
143
                if (action.equals("Login")) {
144
                    responseMap = handleClientRequest(null);
145
                    //*** Now that the action has been processed, clear it.
146
                    clientViewBean.setAction("");
147
                } else if (action.equals("Logout")) {
148
                    responseMap = handleClientRequest(null);
149
                    clientViewBean.setAction("");
150
                } else if (action.equals("Upload")) {
151
                    try {
152
                        //*** Init the MultipartParser.
153
                        multipartParser = new MultipartParser(request, sizeLimit * 1024 * 1024);
154
                        responseMap = handleClientRequest(multipartParser);
155
                    } catch (IOException ex) {
156
                        responseMap = new HashMap();
157
                        responseMap.put("message", ex.getMessage());
158
                    }
159
                    clientViewBean.setAction("");
160
                } else if (action.equals("Download")) {
161
                    responseMap = handleClientRequest(null);
162
                    try {
163
                        handleDownloadResponse(responseMap, response);
164
                    } catch (IOException ex) {
165
                        responseMap = new HashMap();
166
                        responseMap.put("message", ex.getMessage());
167
                    }
168
                    
169
                } else if (action.equals("Set Access")) {
170
                    responseMap = handleClientRequest(null);
171
                    clientViewBean.setAction("");
172
                } else {
173
                    responseMap = handleClientRequest(null);
174
                }
175
                result = (String) responseMap.get("message");
176
            }
177
        } else {
178
            result = "ClientViewHelper.clientRequest: ClientView bean is not instantiated.";
179
        }
180
        return(result);
181
    }
182
    
183
    /**
184
     * Main method for handling various actions.
185
     *
186
     * Note: This is mostly plain java code so it is JUnit friendly
187
     * (pass null as the MulipartParser).
188
     *
189
     * @param multipartParser Only needed if the action is "Upload".
190
     * @return HashMap containing "message", and possibly several other values.  If
191
     * the action is Download, than this will contain all needed values
192
     * to pass to handleDownloadResponse.
193
     */
194
    public HashMap handleClientRequest(MultipartParser multipartParser)  {
195
        String                              result = "", serverResponse;
196
        String                              button, posted_ldapUserName, tmp, action;
197
        HashMap                             responseMap = new HashMap();
198
        int                                 fileIdx;
199
        
200
        
201
        if (clientViewBean != null) {
202
            action = clientViewBean.getAction();
203
            if (action != null) {
117 204
                try {
118 205
                    if (action.equals("Login")) {
119
                        //posted_ldapUserName = String.format(LDAP_TEMPLATE, clientViewBean.getUsername(), clientViewBean.getOrganization());
120 206
                        tmp = LDAP_TEMPLATE.replaceFirst("%1s", clientViewBean.getUsername());
121 207
                        posted_ldapUserName = tmp.replaceFirst("%2s", clientViewBean.getOrganization());
122 208
                        
123 209
                        serverResponse = metacatClient.login(posted_ldapUserName, clientViewBean.getPassword());
124 210
                        setLoggedIn(serverResponse);
125
                        message = parseXml("message", serverResponse);
211
                        result = parseXml("message", serverResponse);
126 212
                        contactName = parseXml("name", serverResponse);
127
                        clientViewBean.setMessage(ClientView.LOGIN_MESSAGE, message);
213
                        clientViewBean.setMessage(ClientView.LOGIN_MESSAGE, result);
128 214
                        clientViewBean.setMessage(ClientView.UPLOAD_MESSAGE, "");
129 215
                        if (isLoggedIn()) {
130 216
                            clientViewBean.setSessionid(metacatClient.getSessionId());
131 217
                        }
132
                        //*** Now that the action has been processed, clear it.
133
                        clientViewBean.setAction("");
134 218
                    } else if (action.equals("Logout")) {
135
                        message = metacatClient.logout();
136
                        setLoggedIn(message);
137
                        message = parseXml("message", message);
138
                        clientViewBean.setMessage(ClientView.LOGIN_MESSAGE, message);
219
                        result = metacatClient.logout();
220
                        setLoggedIn(result);
221
                        result = parseXml("message", result);
222
                        clientViewBean.setMessage(ClientView.LOGIN_MESSAGE, result);
139 223
                        clientViewBean.setMessage(ClientView.UPLOAD_MESSAGE, "");
140 224
                        if (!isLoggedIn()) {
141 225
                            clientViewBean.setUsername("");
......
143 227
                            clientViewBean.setOrganization("");
144 228
                            clientViewBean.setSessionid(null);
145 229
                        }
146
                        //*** Now that the action has been processed, clear it.
147
                        clientViewBean.setAction("");
148
                        
149 230
                    } else if (action.equals("Delete")) {
150
                        
151 231
                        ClientFgdcHelper.clientDeleteRequest(clientViewBean, this);
152 232
                        clientViewBean.setAction("read"); //*** Set for re-query.
153 233
                        //*** Note: the clientViewBean will already have the updated Meta Doc Id.
234
                        
154 235
                    } else if (action.equals("Upload")) {
155
                        message = "";
156
                        //*** Only process request if a file upload.
236
                        //*** Only process request if logged in.
157 237
                        if (isLoggedIn()) {
158
                            //*** Init the MultipartParser.
159
                            multipartParser = new MultipartParser(request, sizeLimit * 1024 * 1024);
160
                            message = handlePackageUpload(clientViewBean, multipartParser);
238
                            if (multipartParser == null)
239
                                result = "ClientViewHelper.handleClientRequest: MultipartParser is not instantiated.";
240
                            else
241
                                result = handlePackageUpload(clientViewBean, multipartParser);
242
                        } else {
243
                            result = "You must be logged in to perform an upload.";
161 244
                        }
162
                        clientViewBean.setMessage(ClientView.UPLOAD_MESSAGE, message);
163
                        //*** Now that the action has been processed, clear it.
164
                        clientViewBean.setAction("");
165
                        
245
                        clientViewBean.setMessage(ClientView.UPLOAD_MESSAGE, result);
166 246
                    } else if (action.equals("Update")) {
167
                        System.out.println("This is not implemented here.  Call ClientViewHelper.jspx");
247
                        result = "This is not implemented here.  Call ClientViewHelper.jspx";
168 248
                    } else if (action.equals("Scope")) {
169
                        message = handleDocIdSelect();
170
                        clientViewBean.setMessage(ClientView.SELECT_MESSAGE, message);
249
                        result = handleDocIdSelect();
250
                        clientViewBean.setMessage(ClientView.SELECT_MESSAGE, result);
171 251
                    } else if (action.equals("Download")) {
172
                        download(clientViewBean, response);
252
                        responseMap = download(clientViewBean);
173 253
                    } else if (action.equals("Set Access")) {
174
                        result = handleChangeAccess(clientViewBean.getMetaFileDocId(), 
254
                        result = handleChangeAccess(clientViewBean.getMetaFileDocId(),
175 255
                                (clientViewBean.isPublicAccess()? PERMISSION_TYPE_ALLOW: PERMISSION_TYPE_DISALLOW));
176
                        clientViewBean.setAction("");
177 256
                        clientViewBean.setMessage(ClientView.UPDATE_MESSAGE, result);
257
                    } else {
258
                        result = action + " action not recognized.";
178 259
                    }
179
                    
180 260
                } catch (Exception ex) {
181
                    message = ex.getMessage();
182
                    clientViewBean.setMessage(ClientView.ERROR_MESSAGE, message);
261
                    result = ex.getMessage();
262
                    clientViewBean.setMessage(ClientView.ERROR_MESSAGE, result);
183 263
                    ex.printStackTrace();
184 264
                }
185 265
            }
186 266
        } else {
187
            System.out.println("ClientViewHelper.clientRequest: ClientView bean is not instantiated.");
267
            result = "ClientViewHelper.clientRequest: ClientView bean is not instantiated.";
188 268
        }
189
        return(result);
269
        responseMap.put("message", result);
270
        return(responseMap);
190 271
    }
191 272
    
192 273
    /**
......
877 958
        return(result);
878 959
    }
879 960
    
880
    private void download(ClientView bean, HttpServletResponse response) {
961
    private HashMap download(ClientView bean) {
881 962
        Properties                      args;
882 963
        InputStream                     inStream;
883 964
        String                          docId, metaId, fNm = null, pth, txtLst[];
......
885 966
        Node                            branchRoot, metaRoot;
886 967
        ByteArrayOutputStream           outStream;
887 968
        int                             intMe;
969
        HashMap                         responseMap = new HashMap();
888 970
        
889 971
        docId = bean.getDocId();
890 972
        metaId = bean.getMetaFileDocId();
......
904 986
                        branchRoot = getNode(xpath, pth, getMetadataDoc());
905 987
                        fNm = getNodeText(xpath, ClientFgdcHelper.FGDC_FILE_NAME_XPATH, branchRoot);
906 988
                        fNm = toZipFileName(fNm);
907
                        response.setContentType("application/zip");
989
                        responseMap.put("contentType", "application/zip");
908 990
                        //*** Get the list of docId's for the entire package.
909 991
                        args.put(metaId, "docid");
910 992
                        txtLst = getNodeTextList(xpath, ClientFgdcHelper.FGDC_DATA_FILE_NODES_XPATH, branchRoot);
......
916 998
                        pth = pth.replaceFirst("%2s", "digform");
917 999
                        branchRoot = getNode(xpath, pth, getMetadataDoc());
918 1000
                        fNm = getNodeText(xpath, ClientFgdcHelper.FGDC_DATA_FILE_NAME_XPATH, branchRoot);
919
                        response.setContentType("application/octet-stream");
1001
                        responseMap.put("contentType", "application/octet-stream");
920 1002
                        args.put(docId, "docid");
921 1003
                        args.put("xml", "qformat");
922 1004
                    }
......
927 1009
                        txtLst = new String[] {docId};
928 1010
                        args.put(txtLst[0], "docid");
929 1011
                        args.put("zip", "qformat");
930
                        response.setContentType("application/zip");
1012
                        responseMap.put("contentType", "application/zip");
931 1013
                    } else {
932 1014
                        fNm = "emlData.dat";
933 1015
                        args.put("xml", "qformat");
934 1016
                        args.put(docId, "docid");
935
                        response.setContentType("application/octet-stream");
1017
                        responseMap.put("contentType", "application/octet-stream");
936 1018
                    }
937 1019
                }
938 1020
                
939 1021
                //*** Set the filename in the response.
940
                response.setHeader("Content-Disposition", "attachment; filename=" + fNm);
1022
                responseMap.put("Content-Disposition", "attachment; filename=" + fNm);
941 1023
                
942 1024
                //*** Next, read the file from metacat.
943 1025
                inStream = metacatClient.sendParameters(args);
......
949 1031
                }
950 1032
                
951 1033
                //*** Now, write the output stream to the response.
952
                response.setContentLength(outStream.size());
953
                outStream.writeTo(response.getOutputStream());
954
                response.flushBuffer();
1034
                responseMap.put("outputStream", outStream);
955 1035
                
956 1036
                //*** Finally, set the message for the user interface to display.
957 1037
                msg = msg.replaceFirst("~", fNm);
......
962 1042
                bean.setMessage(ClientView.SELECT_MESSAGE, ex.getMessage());
963 1043
            }
964 1044
        }
1045
        return(responseMap);
965 1046
    }
966 1047
    
1048
    private void handleDownloadResponse(HashMap responseMap, HttpServletResponse response) throws IOException {
1049
        ByteArrayOutputStream                       outStream;
1050
        String                                      contentDisposition, contentType;
1051
        
1052
        contentType = (String) responseMap.get("contentType");
1053
        contentDisposition = (String) responseMap.get("Content-Disposition");
1054
        outStream = (ByteArrayOutputStream) responseMap.get("outputStream");
1055
        
1056
        response.setContentType(contentType);
1057
        response.setHeader("Content-Disposition", contentDisposition);
1058
        response.setContentLength(outStream.size());
1059
        outStream.writeTo(response.getOutputStream());
1060
        response.flushBuffer();
1061
    }
1062
    
967 1063
    public static String toZipFileName(String fileName) {
968 1064
        String                      result = "metacat";
969 1065
        int                         idx;
......
978 1074
        result += ".zip";
979 1075
        return(result);
980 1076
    }
1077
    
981 1078
}

Also available in: Unified diff