Project

General

Profile

« Previous | Next » 

Revision 5211

Added by Matt Jones about 14 years ago

Merging in REST interface implementation that was created by Serhan Akin. Main change is
a refactored MetaCatServlet.java class, in which all of the handle* methods were moved
into a separate MetacatHandler.java class. This allows both the standard MetaCatServlet
and the new RestServlet to both call the MetacatHandler.handle* methods as needed. This
is a basic port of Akin's work without any major changes to his design or architecture.
One major difference is that the ResourceHandler.query() method has been essentially
disabled because it relied on EcoGrid classes which would have generated a circular
dependency between EcoGrid and Metacat. See the comments in ResourceHandler describing
these issues. Until the circularities are resolved, the REST query() method will
be disabled.

View differences:

MetaCatServlet.java
26 26

  
27 27
package edu.ucsb.nceas.metacat;
28 28

  
29
import java.io.BufferedInputStream;
30
import java.io.File;
31
import java.io.FileInputStream;
32
import java.io.FileReader;
33 29
import java.io.IOException;
34
import java.io.OutputStreamWriter;
35 30
import java.io.PrintWriter;
36
import java.io.StringReader;
37
import java.io.Writer;
38
import java.net.MalformedURLException;
39
import java.net.URL;
40 31
import java.sql.PreparedStatement;
41 32
import java.sql.ResultSet;
42 33
import java.sql.SQLException;
43
import java.sql.Timestamp;
44
import java.text.ParseException;
45
import java.text.SimpleDateFormat;
46 34
import java.util.Enumeration;
47
import java.util.HashMap;
48 35
import java.util.Hashtable;
49
import java.util.Iterator;
50
import java.util.Map;
51 36
import java.util.Timer;
52 37
import java.util.Vector;
53
import java.util.zip.ZipEntry;
54
import java.util.zip.ZipOutputStream;
55 38

  
56 39
import javax.servlet.ServletConfig;
57 40
import javax.servlet.ServletContext;
......
64 47

  
65 48
import org.apache.log4j.Logger;
66 49
import org.apache.log4j.PropertyConfigurator;
67
import org.ecoinformatics.eml.EMLParser;
68 50

  
69
import au.com.bytecode.opencsv.CSVWriter;
70

  
71
import com.oreilly.servlet.multipart.FilePart;
72
import com.oreilly.servlet.multipart.MultipartParser;
73
import com.oreilly.servlet.multipart.ParamPart;
74
import com.oreilly.servlet.multipart.Part;
75

  
76
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlException;
77
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlForSingleFile;
78
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlInterface;
79
import edu.ucsb.nceas.metacat.cart.CartManager;
80 51
import edu.ucsb.nceas.metacat.database.DBConnection;
81 52
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
82 53
import edu.ucsb.nceas.metacat.database.DatabaseService;
83
import edu.ucsb.nceas.metacat.dataquery.DataQuery;
84 54
import edu.ucsb.nceas.metacat.properties.PropertyService;
85 55
import edu.ucsb.nceas.metacat.properties.SkinPropertyService;
86
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
87 56
import edu.ucsb.nceas.metacat.replication.ReplicationService;
88 57
import edu.ucsb.nceas.metacat.service.ServiceService;
89 58
import edu.ucsb.nceas.metacat.service.SessionService;
90 59
import edu.ucsb.nceas.metacat.service.XMLSchemaService;
91
import edu.ucsb.nceas.metacat.shared.ServiceException;
92 60
import edu.ucsb.nceas.metacat.shared.BaseException;
93 61
import edu.ucsb.nceas.metacat.shared.HandlerException;
94 62
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
63
import edu.ucsb.nceas.metacat.shared.ServiceException;
95 64
import edu.ucsb.nceas.metacat.spatial.SpatialFeatureSchema;
96 65
import edu.ucsb.nceas.metacat.spatial.SpatialHarvester;
97
import edu.ucsb.nceas.metacat.spatial.SpatialQuery;
98 66
import edu.ucsb.nceas.metacat.util.AuthUtil;
99 67
import edu.ucsb.nceas.metacat.util.ConfigurationUtil;
68
import edu.ucsb.nceas.metacat.util.DocumentUtil;
100 69
import edu.ucsb.nceas.metacat.util.ErrorSendingErrorException;
101
import edu.ucsb.nceas.metacat.util.DocumentUtil;
102
import edu.ucsb.nceas.metacat.util.MetacatUtil;
103 70
import edu.ucsb.nceas.metacat.util.RequestUtil;
104 71
import edu.ucsb.nceas.metacat.util.ResponseUtil;
72
import edu.ucsb.nceas.metacat.util.SessionData;
105 73
import edu.ucsb.nceas.metacat.util.SystemUtil;
106
import edu.ucsb.nceas.metacat.util.SessionData;
107 74
import edu.ucsb.nceas.metacat.workflow.WorkflowSchedulerClient;
108 75
import edu.ucsb.nceas.utilities.FileUtil;
109 76
import edu.ucsb.nceas.utilities.GeneralPropertyException;
110
import edu.ucsb.nceas.utilities.LSIDUtil;
111
import edu.ucsb.nceas.utilities.ParseLSIDException;
112 77
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
113 78
import edu.ucsb.nceas.utilities.UtilException;
114 79

  
......
285 250

  
286 251
	private static final long serialVersionUID = 1L;
287 252
	private Timer timer = null;
288
    private static boolean _sitemapScheduled;
289 253
    private static boolean _firstHalfInitialized = false;
290 254
    private static boolean _fullyInitialized = false;
255
    private MetacatHandler handler = null;
291 256
    
292 257
    // Constants -- these should be final in a servlet
293
    private static final String PROLOG = "<?xml version=\"1.0\"?>";
294
    private static final String SUCCESS = "<success>";
295
    private static final String SUCCESSCLOSE = "</success>";
296
    private static final String ERROR = "<error>";
297
    private static final String ERRORCLOSE = "</error>";
298 258
    public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
299 259
    public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
300 260
    public static final String EML2KEYWORD = ":eml";
......
415 375
			 * cache on restart, trigger the harvester regeneratation method
416 376
			 */
417 377
			if (PropertyService.getProperty("spatial.runSpatialOption").equals("true")) {
418
//					&& PropertyService.getProperty("spatial.regenerateCacheOnRestart").equals("true")) {
419

  
378
			//      && PropertyService.getProperty("spatial.regenerateCacheOnRestart").equals("true")) {
379
			        
420 380
				// Begin timer
421 381
				long before = System.currentTimeMillis();
422 382

  
423
				// if either the point or polygon shape files do not exist, then regenerate the entire spatial cache
424
				// this may be expensive with many documents
425
				if( FileUtil.getFileStatus(SpatialFeatureSchema.pointShpUri) == FileUtil.DOES_NOT_EXIST) {		
426
					SpatialHarvester sh = new SpatialHarvester();
427
					sh.regenerate();
428
					sh.destroy();
429
				}
383
                // if either the point or polygon shape files do not exist, then regenerate the entire spatial cache
384
                // this may be expensive with many documents
385
                if (FileUtil.getFileStatus(SpatialFeatureSchema.pointShpUri) == FileUtil.DOES_NOT_EXIST) {      
386
                    SpatialHarvester sh = new SpatialHarvester();
387
                    sh.regenerate();
388
                    sh.destroy();
389
                }
430 390

  
431 391
				// After running the first time, we want to to set
432 392
				// regenerateCacheOnRestart to false
......
460 420
			System.setProperty("replication.logfile.name", replicationLogPath);			
461 421
			PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
462 422
			
463
			_sitemapScheduled = false;
423
	         //Initialize Metacat Handler
424
            handler = new MetacatHandler(getServletContext(), timer);
464 425

  
426
			MetacatHandler.set_sitemapScheduled(false);
427

  
465 428
			_fullyInitialized = true;
466 429
			
467 430
			logMetacat.warn("MetaCatServlet.initSecondHalf - Metacat (" + MetacatVersion.getVersionID()
......
717 680

  
718 681
		try {
719 682
			String ctype = request.getContentType();
683
			
720 684
			if (ctype != null && ctype.startsWith("multipart/form-data")) {
721
				handleMultipartForm(request, response);
685
				handler.handleMultipartForm(request, response);
722 686
				return;
723 687
			} 
724 688

  
......
748 712
						skins[0] = skin;
749 713
						params.put("qformat", skins);
750 714
					}
751
					handleReadAction(params, request, response, "public", null, null);
715
					handler.handleReadAction(params, request, response, "public", null, null);
752 716
					return;
753 717
				}
754 718
			}
......
809 773
			// handle login action
810 774
			if (action.equals("login")) {
811 775
				PrintWriter out = response.getWriter();
812
				handleLoginAction(out, params, request, response);
776
				handler.handleLoginAction(out, params, request, response);
813 777
				out.close();
814 778

  
815 779
				// handle logout action
816 780
			} else if (action.equals("logout")) {
817 781
				PrintWriter out = response.getWriter();
818
				handleLogoutAction(out, params, request, response);
782
				handler.handleLogoutAction(out, params, request, response);
819 783
				out.close();
820 784

  
821 785
				// handle shrink DBConnection request
......
867 831
			if (action.equals("query")) {
868 832
				ServletOutputStream streamOut = response.getOutputStream();
869 833
				PrintWriter out = new PrintWriter(streamOut);
870
				handleQuery(out, params, response, userName, groupNames, sessionId);
834
				handler.handleQuery(out, params, response, userName, groupNames, sessionId);
871 835
				out.close();
872 836
			} else if (action.equals("squery")) {
873 837
				ServletOutputStream streamOut = response.getOutputStream();
874 838
				PrintWriter out = new PrintWriter(streamOut);
875 839
				if (params.containsKey("query")) {
876
					handleSQuery(out, params, response, userName, groupNames, sessionId);
840
					handler.handleSQuery(out, params, response, userName, groupNames, sessionId);
877 841
					out.close();
878 842
				} else {
879 843
					out.println("Illegal action squery without \"query\" parameter");
......
885 849
						.debug("MetaCatServlet.handleGetOrPost - ******************* SPATIAL QUERY ********************");
886 850
				ServletOutputStream streamOut = response.getOutputStream();
887 851
				PrintWriter out = new PrintWriter(streamOut);
888
				handleSpatialQuery(out, params, response, userName, groupNames, sessionId);
852
				handler.handleSpatialQuery(out, params, response, userName, groupNames, sessionId);
889 853
				out.close();
890 854

  
891 855
			} else if (action.trim().equals("dataquery")) {
892 856

  
893 857
				logMetacat.debug("MetaCatServlet.handleGetOrPost - ******************* DATA QUERY ********************");
894
				handleDataquery(params, response, sessionId);
858
				handler.handleDataquery(params, response, sessionId);
895 859
			} else if (action.trim().equals("editcart")) {
896 860
				logMetacat.debug("MetaCatServlet.handleGetOrPost - ******************* EDIT CART ********************");
897
				handleEditCart(params, response, sessionId);
861
				handler.handleEditCart(params, response, sessionId);
898 862
			} else if (action.equals("export")) {
899 863

  
900
				handleExportAction(params, response, userName, groupNames, password);
864
				handler.handleExportAction(params, response, userName, groupNames, password);
901 865
			} else if (action.equals("read")) {
902 866
				if (params.get("archiveEntryName") != null) {
903 867
					ArchiveHandler.getInstance().readArchiveEntry(params, request,
904 868
							response, userName, password, groupNames);
905 869
				} else {
906
					handleReadAction(params, request, response, userName, password,
870
					handler.handleReadAction(params, request, response, userName, password,
907 871
							groupNames);
908 872
				}
909 873
			} else if (action.equals("readinlinedata")) {
910
				handleReadInlineDataAction(params, request, response, userName, password,
874
				handler.handleReadInlineDataAction(params, request, response, userName, password,
911 875
						groupNames);
912 876
			} else if (action.equals("insert") || action.equals("update")) {
913 877
				PrintWriter out = response.getWriter();
914 878
				if ((userName != null) && !userName.equals("public")) {
915
					handleInsertOrUpdateAction(request, response, out, params, userName,
879
					handler.handleInsertOrUpdateAction(request, response, out, params, userName,
916 880
							groupNames);
917 881
				} else {
918 882
					response.setContentType("text/xml");
......
925 889
			} else if (action.equals("delete")) {
926 890
				PrintWriter out = response.getWriter();
927 891
				if ((userName != null) && !userName.equals("public")) {
928
					handleDeleteAction(out, params, request, response, userName,
892
					handler.handleDeleteAction(out, params, request, response, userName,
929 893
							groupNames);
930 894
				} else {
931 895
					response.setContentType("text/xml");
......
937 901
				out.close();
938 902
			} else if (action.equals("validate")) {
939 903
				PrintWriter out = response.getWriter();
940
				handleValidateAction(out, params);
904
				handler.handleValidateAction(out, params);
941 905
				out.close();
942 906
			} else if (action.equals("setaccess")) {
943 907
				PrintWriter out = response.getWriter();
944
				handleSetAccessAction(out, params, userName, request, response);
908
				handler.handleSetAccessAction(out, params, userName, request, response);
945 909
				out.close();
946 910
			} else if (action.equals("getaccesscontrol")) {
947 911
				PrintWriter out = response.getWriter();
948
				handleGetAccessControlAction(out, params, response, userName, groupNames);
912
				handler.handleGetAccessControlAction(out, params, response, userName, groupNames);
949 913
				out.close();
950 914
			} else if (action.equals("isauthorized")) {
951 915
				PrintWriter out = response.getWriter();
......
953 917
				out.close();
954 918
			} else if (action.equals("getprincipals")) {
955 919
				PrintWriter out = response.getWriter();
956
				handleGetPrincipalsAction(out, userName, password);
920
				handler.handleGetPrincipalsAction(out, userName, password);
957 921
				out.close();
958 922
			} else if (action.equals("getdoctypes")) {
959 923
				PrintWriter out = response.getWriter();
960
				handleGetDoctypesAction(out, params, response);
924
				handler.handleGetDoctypesAction(out, params, response);
961 925
				out.close();
962 926
			} else if (action.equals("getdtdschema")) {
963 927
				PrintWriter out = response.getWriter();
964
				handleGetDTDSchemaAction(out, params, response);
928
				handler.handleGetDTDSchemaAction(out, params, response);
965 929
				out.close();
966 930
			} else if (action.equals("getlastdocid")) {
967 931
				PrintWriter out = response.getWriter();
968
				handleGetMaxDocidAction(out, params, response);
932
				handler.handleGetMaxDocidAction(out, params, response);
969 933
				out.close();
970 934
			} else if (action.equals("getalldocids")) {
971 935
				PrintWriter out = response.getWriter();
972
				handleGetAllDocidsAction(out, params, response);
936
				handler.handleGetAllDocidsAction(out, params, response);
973 937
				out.close();
974 938
			} else if (action.equals("isregistered")) {
975 939
				PrintWriter out = response.getWriter();
976
				handleIdIsRegisteredAction(out, params, response);
940
				handler.handleIdIsRegisteredAction(out, params, response);
977 941
				out.close();
978 942
			} else if (action.equals("getrevisionanddoctype")) {
979 943
				PrintWriter out = response.getWriter();
980
				handleGetRevisionAndDocTypeAction(out, params);
944
				handler.handleGetRevisionAndDocTypeAction(out, params);
981 945
				out.close();
982 946
			} else if (action.equals("getversion")) {
983 947
				response.setContentType("text/xml");
......
985 949
				out.println(MetacatVersion.getVersionAsXml());
986 950
				out.close();
987 951
			} else if (action.equals("getlog")) {
988
				handleGetLogAction(params, request, response, userName, groupNames);
952
				handler.handleGetLogAction(params, request, response, userName, groupNames);
989 953
			} else if (action.equals("getloggedinuserinfo")) {
990 954
				PrintWriter out = response.getWriter();
991 955
				response.setContentType("text/xml");
......
1008 972
				out.println("\n</user>\n");
1009 973
				out.close();
1010 974
			} else if (action.equals("buildindex")) {
1011
				handleBuildIndexAction(params, request, response, userName, groupNames);
975
				handler.handleBuildIndexAction(params, request, response, userName, groupNames);
1012 976
			} else if (action.equals("login") || action.equals("logout")) {
1013 977
				/*
1014 978
				 * } else if (action.equals("protocoltest")) { String testURL =
......
1106 1070
			}
1107 1071

  
1108 1072
			// Schedule the sitemap generator to run periodically
1109
			scheduleSitemapGeneration(request);
1073
			handler.scheduleSitemapGeneration(request);
1110 1074

  
1111 1075

  
1112 1076
		} catch (PropertyNotFoundException pnfe) {
......
1135 1099
		} 
1136 1100
	}
1137 1101
    
1138
	
1139
	private void handleDataquery(
1140
			Hashtable<String, String[]> params,
1141
            HttpServletResponse response,
1142
            String sessionId) throws PropertyNotFoundException, IOException {
1143
		
1144
		DataQuery dq = null;
1145
		if (sessionId != null) {
1146
			dq = new DataQuery(sessionId);
1147
		}
1148
		else {
1149
			dq = new DataQuery();
1150
		}
1151
		
1152
    	String dataqueryXML = (params.get("dataquery"))[0];
1153

  
1154
    	ResultSet rs = null;
1155
		try {
1156
			rs = dq.executeQuery(dataqueryXML);
1157
		} catch (Exception e) {
1158
			//probably need to do something here
1159
			e.printStackTrace();
1160
			return;
1161
		}
1162
    	
1163
		//process the result set
1164
		String qformat = "csv";
1165
		String[] temp = params.get("qformat");
1166
		if (temp != null && temp.length > 0) {
1167
			qformat = temp[0];
1168
		}
1169
		String fileName = "query-results." + qformat;
1170
		
1171
		//get the results as csv file
1172
		if (qformat != null && qformat.equalsIgnoreCase("csv")) {
1173
			response.setContentType("text/csv");
1174
			//response.setContentType("application/csv");
1175
	        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
1176
	        
1177
			Writer writer = new OutputStreamWriter(response.getOutputStream());
1178
			CSVWriter csv = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
1179
			try {
1180
				
1181
				csv.writeAll(rs, true);
1182
				
1183
				csv.flush();
1184
				response.flushBuffer();
1185
				
1186
				rs.close();
1187
				
1188
			} catch (SQLException e) {
1189
				e.printStackTrace();
1190
			}
1191
			
1192
			return;
1193
		}
1194
		
1195
	}
1196
	
1197
	private void handleEditCart(
1198
			Hashtable<String, String[]> params,
1199
            HttpServletResponse response,
1200
            String sessionId) throws PropertyNotFoundException, IOException {
1201
		
1202
		CartManager cm = null;
1203
		if (sessionId != null) {
1204
			cm = new CartManager(sessionId);
1205
		}
1206
		else {
1207
			cm = new CartManager();
1208
		}
1209
		
1210
    	String editOperation = (params.get("operation"))[0];
1211
    	
1212
    	String[] docids = params.get("docid");
1213
    	String[] field = params.get("field");
1214
    	String[] path = params.get("path");
1215
    	
1216
    	Map<String,String> fields = null;
1217
    	if (field != null && path != null) {
1218
    		fields = new HashMap<String,String>();
1219
    		fields.put(field[0], path[0]);
1220
    	}
1221
    	
1222
    	//TODO handle attribute map (metadata fields)
1223
    	cm.editCart(editOperation, docids, fields);
1224
    	
1225
	}
1226
	
1227
    // ///////////////////////////// METACAT SPATIAL ///////////////////////////
1228
    
1229 1102
    /**
1230
	 * handles all spatial queries -- these queries may include any of the
1231
	 * queries supported by the WFS / WMS standards
1232
	 * 
1233
	 * handleSQuery(out, params, response, username, groupnames, sess_id);
1234
	 */
1235
    private void handleSpatialQuery(PrintWriter out, Hashtable<String, String[]> params,
1236
            HttpServletResponse response,
1237
            String username, String[] groupnames,
1238
            String sess_id) throws PropertyNotFoundException {
1239
        
1240
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1241
        
1242
        if ( !PropertyService.getProperty("spatial.runSpatialOption").equals("true") ) {
1243
            response.setContentType("text/html");
1244
            out.println("<html> Metacat Spatial Option is turned off </html>");
1245
            out.close();
1246
            return ;
1247
        }
1248
        
1249
        /*
1250
		 * Perform spatial query against spatial cache
1251
		 */
1252
        float _xmax = Float.valueOf( (params.get("xmax"))[0] ).floatValue();
1253
        float _ymax = Float.valueOf( (params.get("ymax"))[0] ).floatValue();
1254
        float _xmin = Float.valueOf( (params.get("xmin"))[0] ).floatValue();
1255
        float _ymin = Float.valueOf( (params.get("ymin"))[0] ).floatValue();
1256
        SpatialQuery sq = new SpatialQuery();
1257
        Vector<String> docids = sq.filterByBbox( _xmin, _ymin, _xmax, _ymax );
1258
        // logMetacat.info(" --- Spatial Query completed. Passing on the SQuery
1259
		// handler");
1260
        // logMetacat.warn("\n\n ******* after spatial query, we've got " +
1261
		// docids.size() + " docids \n\n");
1262
        
1263
        /*
1264
		 * Create an array matching docids
1265
		 */
1266
        String [] docidArray = new String[docids.size()];
1267
        docids.toArray(docidArray);
1268
        
1269
        /*
1270
		 * Create squery string
1271
		 */
1272
        String squery = DocumentIdQuery.createDocidQuery( docidArray );
1273
        // logMetacat.info("-----------\n" + squery + "\n------------------");
1274
        String[] queryArray = new String[1];
1275
        queryArray[0] = squery;
1276
        params.put("query", queryArray);
1277
        
1278
        /*
1279
		 * Determine qformat
1280
		 */
1281
        String[] qformatArray = new String[1];
1282
        try {
1283
            String _skin = (params.get("skin"))[0];
1284
            qformatArray[0] = _skin;
1285
        } catch (java.lang.NullPointerException e) {
1286
            // should be "default" but keep this for backwards compatibility
1287
			// with knp site
1288
            logMetacat.warn("MetaCatServlet.handleSpatialQuery - No SKIN specified for metacat actions=spatial_query... defaulting to 'knp' skin !\n");
1289
            qformatArray[0] = "knp";
1290
        }
1291
        params.put("qformat", qformatArray);
1292
        
1293
        // change the action
1294
        String[] actionArray = new String[1];
1295
        actionArray[0] = "squery";
1296
        params.put("action", actionArray);
1297
        
1298
        /*
1299
		 * Pass the docids to the DBQuery contructor
1300
		 */
1301
        // This is a hack to get the empty result set to show...
1302
        // Otherwise dbquery sees no docidOverrides and does a full % percent
1303
		// query
1304
        if (docids.size() == 0)
1305
            docids.add("");
1306
        
1307
        DBQuery queryobj = new DBQuery(docids);
1308
        queryobj.findDocuments(response, out, params, username, groupnames, sess_id);
1309
        
1310
    }
1311
    
1312
    // LOGIN & LOGOUT SECTION
1313
    /**
1314
	 * Handle the login request. Create a new session object. Do user
1315
	 * authentication through the session.
1316
	 */
1317
    private void handleLoginAction(PrintWriter out, Hashtable<String, String[]> params,
1318
            HttpServletRequest request, HttpServletResponse response) {
1319
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1320
        AuthSession sess = null;
1321
        
1322
        if(params.get("username") == null){
1323
            response.setContentType("text/xml");
1324
            out.println("<?xml version=\"1.0\"?>");
1325
            out.println("<error>");
1326
            out.println("Username not specified");
1327
            out.println("</error>");
1328
            return;
1329
        }
1330
        
1331
        // }
1332
        
1333
        if(params.get("password") == null){
1334
            response.setContentType("text/xml");
1335
            out.println("<?xml version=\"1.0\"?>");
1336
            out.println("<error>");
1337
            out.println("Password not specified");
1338
            out.println("</error>");
1339
            return;
1340
        }
1341
        
1342
        String un = (params.get("username"))[0];
1343
        logMetacat.info("MetaCatServlet.handleLoginAction - user " + un + " is trying to login");
1344
        String pw = (params.get("password"))[0];
1345
        
1346
        String qformat = "xml";
1347
        if (params.get("qformat") != null) {
1348
            qformat = (params.get("qformat"))[0];
1349
        }
1350
        
1351
        try {
1352
            sess = new AuthSession();
1353
        } catch (Exception e) {
1354
        	String errorMsg = "MetacatServlet.handleLoginAction - Problem in MetacatServlet.handleLoginAction() authenicating session: "
1355
                + e.getMessage();
1356
            logMetacat.error(errorMsg);
1357
            out.println(errorMsg);
1358
            return;
1359
        }
1360
        boolean isValid = sess.authenticate(request, un, pw);
1361
        
1362
        //if it is authernticate is true, store the session
1363
        if (isValid) {
1364
            HttpSession session = sess.getSessions();
1365
            String id = session.getId();
1366
            
1367
            logMetacat.debug("MetaCatServlet.handleLoginAction - Store session id " + id
1368
                    + " which has username" + session.getAttribute("username")
1369
                    + " into hash in login method");
1370
            try {
1371
				SessionService.registerSession(id, 
1372
						(String) session.getAttribute("username"), 
1373
						(String[]) session.getAttribute("groupnames"), 
1374
						(String) session.getAttribute("password"), 
1375
						(String) session.getAttribute("name"));
1376
			} catch (ServiceException se) {
1377
				String errorMsg = "MetacatServlet.handleLoginAction - service problem registering session: "
1378
						+ se.getMessage();
1379
				logMetacat.error("MetaCatServlet.handleLoginAction - " + errorMsg);
1380
				out.println(errorMsg);
1381
				return;
1382
			} 			
1383
        }
1384
                
1385
        // format and transform the output
1386
        if (qformat.equals("xml")) {
1387
            response.setContentType("text/xml");
1388
            out.println(sess.getMessage());
1389
        } else {
1390
            try {
1391
                DBTransform trans = new DBTransform();
1392
                response.setContentType("text/html");
1393
                trans.transformXMLDocument(sess.getMessage(),
1394
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
1395
                        out, null, null);
1396
            } catch (Exception e) {               
1397
                logMetacat.error("MetaCatServlet.handleLoginAction - General error"
1398
                        + e.getMessage());
1399
            }
1400
        }
1401
    }
1402
    
1403
    /**
1404
     * Handle the logout request. Close the connection.
1405
     */
1406
    private void handleLogoutAction(PrintWriter out, Hashtable<String, String[]> params,
1407
            HttpServletRequest request, HttpServletResponse response) {
1408
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1409
        String qformat = "xml";
1410
        if(params.get("qformat") != null){
1411
            qformat = params.get("qformat")[0];
1412
        }
1413
        
1414
        // close the connection
1415
        HttpSession sess = request.getSession(false);
1416
        logMetacat.info("MetaCatServlet.handleLogoutAction - After get session in logout request");
1417
        if (sess != null) {
1418
            logMetacat.info("MetaCatServlet.handleLogoutAction - The session id " + sess.getId()
1419
            + " will be invalidate in logout action");
1420
            logMetacat.info("MetaCatServlet.handleLogoutAction - The session contains user "
1421
                    + sess.getAttribute("username")
1422
                    + " will be invalidate in logout action");
1423
            sess.invalidate();
1424
            SessionService.unRegisterSession(sess.getId());
1425
        }
1426
        
1427
        // produce output
1428
        StringBuffer output = new StringBuffer();
1429
        output.append("<?xml version=\"1.0\"?>");
1430
        output.append("<logout>");
1431
        output.append("User logged out");
1432
        output.append("</logout>");
1433
        
1434
        //format and transform the output
1435
        if (qformat.equals("xml")) {
1436
            response.setContentType("text/xml");
1437
            out.println(output.toString());
1438
        } else {
1439
            try {
1440
                DBTransform trans = new DBTransform();
1441
                response.setContentType("text/html");
1442
                trans.transformXMLDocument(output.toString(),
1443
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
1444
                        out, null, null);
1445
            } catch (Exception e) {
1446
                logMetacat.error(
1447
                        "MetaCatServlet.handleLogoutAction - General error: "
1448
                        + e.getMessage());
1449
            }
1450
        }
1451
    }
1452
    
1453
    // END OF LOGIN & LOGOUT SECTION
1454
    
1455
    // SQUERY & QUERY SECTION
1456
    /**
1457
     * Retreive the squery xml, execute it and display it
1458
     *
1459
     * @param out the output stream to the client
1460
     * @param params the Hashtable of parameters that should be included in the
1461
     *            squery.
1462
     * @param response the response object linked to the client
1463
     * @param conn the database connection
1464
     */
1465
    private void handleSQuery(PrintWriter out, Hashtable<String, String[]> params,
1466
            HttpServletResponse response, String user, String[] groups,
1467
            String sessionid) throws PropertyNotFoundException {
1468
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1469
        long squeryWarnLimit = Long.parseLong(PropertyService.getProperty("database.squeryTimeWarnLimit"));
1470
    	
1471
        long startTime = System.currentTimeMillis();
1472
        DBQuery queryobj = new DBQuery();
1473
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
1474
        long outPutTime = System.currentTimeMillis();
1475
        long runTime = outPutTime - startTime;
1476

  
1477
        if (runTime > squeryWarnLimit) {
1478
        	logMetacat.warn("MetaCatServlet.handleSQuery - Long running squery.  Total time: " + runTime + 
1479
        			" ms, squery: " + ((String[])params.get("query"))[0]);
1480
        }
1481
        logMetacat.debug("MetaCatServlet.handleSQuery - squery: " + ((String[])params.get("query"))[0] + 
1482
        		" ran in " + runTime + " ms");
1483
    }
1484
    
1485
    /**
1486
     * Create the xml query, execute it and display the results.
1487
     *
1488
     * @param out the output stream to the client
1489
     * @param params the Hashtable of parameters that should be included in the
1490
     *            squery.
1491
     * @param response the response object linked to the client
1492
     */
1493
    private void handleQuery(PrintWriter out, Hashtable<String, String[]> params,
1494
            HttpServletResponse response, String user, String[] groups,
1495
            String sessionid) throws PropertyNotFoundException {
1496
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1497
        long queryWarnLimit = Long.parseLong(PropertyService.getProperty("database.queryTimeWarnLimit"));
1498
    	
1499
        //create the query and run it
1500
        String xmlquery = DBQuery.createSQuery(params);
1501
        String[] queryArray = new String[1];
1502
        queryArray[0] = xmlquery;
1503
        params.put("query", queryArray);
1504
        long startTime = System.currentTimeMillis();
1505
        DBQuery queryobj = new DBQuery();
1506
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
1507
        long outPutTime = System.currentTimeMillis();
1508
        long runTime = outPutTime -startTime;
1509

  
1510
        if (runTime > queryWarnLimit) {
1511
        	logMetacat.warn("MetaCatServlet.handleQuery - Long running squery.  Total time: " + runTime + 
1512
        			" ms, squery: " + ((String[])params.get("query"))[0]);
1513
        }
1514
        logMetacat.debug("MetaCatServlet.handleQuery - query: " + ((String[])params.get("query"))[0] + 
1515
        		" ran in " + runTime + " ms");
1516
    }
1517
    
1518
    // END OF SQUERY & QUERY SECTION
1519
    
1520
    //Exoport section
1521
    /**
1522
     * Handle the "export" request of data package from Metacat in zip format
1523
     *
1524
     * @param params the Hashtable of HTTP request parameters
1525
     * @param response the HTTP response object linked to the client
1526
     * @param user the username sent the request
1527
     * @param groups the user's groupnames
1528
     */
1529
    private void handleExportAction(Hashtable<String, String[]> params,
1530
            HttpServletResponse response,
1531
            String user, String[] groups, String passWord) {
1532
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1533
        // Output stream
1534
        ServletOutputStream out = null;
1535
        // Zip output stream
1536
        ZipOutputStream zOut = null;
1537
        DBQuery queryObj = null;
1538
        
1539
        String[] docs = new String[10];
1540
        String docId = "";
1541
        
1542
        try {
1543
            // read the params
1544
            if (params.containsKey("docid")) {
1545
                docs = params.get("docid");
1546
            }
1547
            // Create a DBuery to handle export
1548
            queryObj = new DBQuery();
1549
            // Get the docid
1550
            docId = docs[0];
1551
            // Make sure the client specify docid
1552
            if (docId == null || docId.equals("")) {
1553
                response.setContentType("text/xml"); //MIME type
1554
                // Get a printwriter
1555
                PrintWriter pw = response.getWriter();
1556
                // Send back message
1557
                pw.println("<?xml version=\"1.0\"?>");
1558
                pw.println("<error>");
1559
                pw.println("You didn't specify requested docid");
1560
                pw.println("</error>");
1561
                // Close printwriter
1562
                pw.close();
1563
                return;
1564
            }
1565
            // Get output stream
1566
            out = response.getOutputStream();
1567
            response.setContentType("application/zip"); //MIME type
1568
            response.setHeader("Content-Disposition",
1569
                    "attachment; filename="
1570
                    + docId + ".zip"); // Set the name of the zip file
1571
            
1572
            zOut = new ZipOutputStream(out);
1573
            zOut = queryObj
1574
                    .getZippedPackage(docId, out, user, groups, passWord);
1575
            zOut.finish(); //terminate the zip file
1576
            zOut.close(); //close the zip stream
1577
            
1578
        } catch (Exception e) {
1579
            try {
1580
                response.setContentType("text/xml"); //MIME type
1581
                // Send error message back
1582
                if (out != null) {
1583
                    PrintWriter pw = new PrintWriter(out);
1584
                    pw.println("<?xml version=\"1.0\"?>");
1585
                    pw.println("<error>");
1586
                    pw.println(e.getMessage());
1587
                    pw.println("</error>");
1588
                    // Close printwriter
1589
                    pw.close();
1590
                    // Close output stream
1591
                    out.close();
1592
                }
1593
                // Close zip output stream
1594
                if (zOut != null) {
1595
                    zOut.close();
1596
                }
1597
            } catch (IOException ioe) {
1598
                logMetacat.error("MetaCatServlet.handleExportAction - Problem with the servlet output: "
1599
                        + ioe.getMessage());
1600
            }
1601
            
1602
            logMetacat.error("MetaCatServlet.handleExportAction - General error: "
1603
                    + e.getMessage());
1604
            e.printStackTrace(System.out);
1605
            
1606
        }
1607
        
1608
    }
1609
    
1610
    /**
1611
     * In eml2 document, the xml can have inline data and data was stripped off
1612
     * and store in file system. This action can be used to read inline data
1613
     * only
1614
     *
1615
     * @param params the Hashtable of HTTP request parameters
1616
     * @param response the HTTP response object linked to the client
1617
     * @param user the username sent the request
1618
     * @param groups the user's groupnames
1619
     */
1620
    private void handleReadInlineDataAction(Hashtable<String, String[]> params,
1621
            HttpServletRequest request, HttpServletResponse response,
1622
            String user, String passWord, String[] groups) {
1623
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1624
        String[] docs = new String[10];
1625
        String inlineDataId = null;
1626
        String docId = "";
1627
        ServletOutputStream out = null;
1628
        
1629
        try {
1630
            // read the params
1631
            if (params.containsKey("inlinedataid")) {
1632
                docs = params.get("inlinedataid");
1633
            }
1634
            // Get the docid
1635
            inlineDataId = docs[0];
1636
            // Make sure the client specify docid
1637
            if (inlineDataId == null || inlineDataId.equals("")) {
1638
                throw new Exception("You didn't specify requested inlinedataid"); }
1639
            
1640
            // check for permission
1641
            docId = 
1642
            	DocumentUtil.getDocIdWithoutRevFromInlineDataID(inlineDataId);
1643
            PermissionController controller = new PermissionController(docId);
1644
            // check top level read permission
1645
            if (!controller.hasPermission(user, groups,
1646
                    AccessControlInterface.READSTRING)) {
1647
                throw new Exception("User " + user
1648
                        + " doesn't have permission " + " to read document "
1649
                        + docId);
1650
            } else {
1651
                //check data access level
1652
                try {
1653
                    Hashtable<String,String> unReadableInlineDataList =
1654
                            PermissionController.getUnReadableInlineDataIdList(docId,
1655
                            user, groups, false);
1656
                    String inlineDataIdWithoutRev = DocumentUtil.getInlineDataIdWithoutRev(inlineDataId);
1657
                    if (unReadableInlineDataList.containsValue(inlineDataIdWithoutRev)) {
1658
                        throw new Exception("User " + user
1659
                                + " doesn't have permission " + " to read inlinedata "
1660
                                + inlineDataId);
1661
                        
1662
                    }//if
1663
                }//try
1664
                catch (Exception e) {
1665
                    throw e;
1666
                }//catch
1667
            }//else
1668
            
1669
            // Get output stream
1670
            out = response.getOutputStream();
1671
            // read the inline data from the file
1672
            String inlinePath = PropertyService.getProperty("application.inlinedatafilepath");
1673
            File lineData = new File(inlinePath, inlineDataId);
1674
            FileInputStream input = new FileInputStream(lineData);
1675
            byte[] buffer = new byte[4 * 1024];
1676
            int bytes = input.read(buffer);
1677
            while (bytes != -1) {
1678
                out.write(buffer, 0, bytes);
1679
                bytes = input.read(buffer);
1680
            }
1681
            out.close();
1682
            
1683
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1684
                    inlineDataId, "readinlinedata");
1685
        } catch (Exception e) {
1686
            try {
1687
                PrintWriter pw = null;
1688
                // Send error message back
1689
                if (out != null) {
1690
                    pw = new PrintWriter(out);
1691
                } else {
1692
                    pw = response.getWriter();
1693
                }
1694
                pw.println("<?xml version=\"1.0\"?>");
1695
                pw.println("<error>");
1696
                pw.println(e.getMessage());
1697
                pw.println("</error>");
1698
                // Close printwriter
1699
                pw.close();
1700
                // Close output stream if out is not null
1701
                if (out != null) {
1702
                    out.close();
1703
                }
1704
            } catch (IOException ioe) {
1705
                logMetacat.error("MetaCatServlet.handleReadInlineDataAction - Problem with the servlet output: "
1706
                        + ioe.getMessage());
1707
            }
1708
            logMetacat.error("MetaCatServlet.handleReadInlineDataAction - General error: "
1709
                    + e.getMessage());
1710
        }
1711
    }
1712
    
1713
    /**
1714
     * Handle the "read" request of metadata/data files from Metacat or any
1715
     * files from Internet; transformed metadata XML document into HTML
1716
     * presentation if requested; zip files when more than one were requested.
1717
     *
1718
     * @param params the Hashtable of HTTP request parameters
1719
     * @param request the HTTP request object linked to the client
1720
     * @param response the HTTP response object linked to the client
1721
     * @param user the username sent the request
1722
     * @param groups the user's groupnames
1723
     */
1724
    private void handleReadAction(Hashtable<String, String[]> params, HttpServletRequest request,
1725
            HttpServletResponse response, String user, String passWord,
1726
            String[] groups) {
1727
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1728
        ServletOutputStream out = null;
1729
        ZipOutputStream zout = null;
1730
        PrintWriter pw = null;
1731
        boolean zip = false;
1732
        boolean withInlineData = true;
1733
        
1734
        try {
1735
            String[] docs = new String[0];
1736
            String docid = "";
1737
            String qformat = "";
1738
            String abstrpath = null;
1739
            
1740
            // read the params
1741
            if (params.containsKey("docid")) {
1742
                docs = params.get("docid");
1743
            }
1744
            if (params.containsKey("qformat")) {
1745
                qformat = params.get("qformat")[0];
1746
            }
1747
            // the param for only metadata (eml)
1748
            // we don't support read a eml document without inline data now.
1749
            /*if (params.containsKey("inlinedata")) {
1750
             
1751
                String inlineData = ((String[]) params.get("inlinedata"))[0];
1752
                if (inlineData.equalsIgnoreCase("false")) {
1753
                    withInlineData = false;
1754
                }
1755
            }*/
1756
            if ((docs.length > 1) || qformat.equals("zip")) {
1757
                zip = true;
1758
                out = response.getOutputStream();
1759
                response.setContentType("application/zip"); //MIME type
1760
                zout = new ZipOutputStream(out);
1761
            }
1762
            // go through the list of docs to read
1763
            for (int i = 0; i < docs.length; i++) {
1764
            	String providedFileName = null;
1765
            	if (params.containsKey(docs[i])) {
1766
                    providedFileName = params.get(docs[i])[0];
1767
                }
1768
                try {
1769
                    
1770
                    URL murl = new URL(docs[i]);
1771
                    Hashtable<String,String> murlQueryStr = MetacatUtil.parseQuery(
1772
                            murl.getQuery());
1773
                    // case docid="http://.../?docid=aaa"
1774
                    // or docid="metacat://.../?docid=bbb"
1775
                    if (murlQueryStr.containsKey("docid")) {
1776
                        // get only docid, eliminate the rest
1777
                        docid = murlQueryStr.get("docid");
1778
                        if (zip) {
1779
                            addDocToZip(request, docid, providedFileName, zout, user, groups);
1780
                        } else {
1781
                            readFromMetacat(request, response, docid, qformat,
1782
                                    abstrpath, user, groups, zip, zout,
1783
                                    withInlineData, params);
1784
                        }
1785
                        
1786
                        // case docid="http://.../filename"
1787
                    } else {
1788
                        docid = docs[i];
1789
                        if (zip) {
1790
                            addDocToZip(request, docid, providedFileName, zout, user, groups);
1791
                        } else {
1792
                            readFromURLConnection(response, docid);
1793
                        }
1794
                    }
1795
                    
1796
                } catch (MalformedURLException mue) {
1797
                    docid = docs[i];
1798
                    if (zip) {
1799
                        addDocToZip(request, docid, providedFileName, zout, user, groups);
1800
                    } else {
1801
                        readFromMetacat(request, response, docid, qformat,
1802
                                abstrpath, user, groups, zip, zout,
1803
                                withInlineData, params);
1804
                    }
1805
                }
1806
            }
1807
            
1808
            if (zip) {
1809
                zout.finish(); //terminate the zip file
1810
                zout.close(); //close the zip stream
1811
            }
1812
            
1813
        } catch (McdbDocNotFoundException notFoundE) {
1814
            // To handle doc not found exception
1815
            // the docid which didn't be found
1816
            String notFoundDocId = notFoundE.getUnfoundDocId();
1817
            String notFoundRevision = notFoundE.getUnfoundRevision();
1818
            logMetacat.warn("MetaCatServlet.handleReadAction - Missed id: " + notFoundDocId);
1819
            logMetacat.warn("MetaCatServlet.handleReadAction - Missed rev: " + notFoundRevision);
1820
            try {
1821
                // read docid from remote server
1822
                readFromRemoteMetaCat(response, notFoundDocId,
1823
                        notFoundRevision, user, passWord, out, zip, zout);
1824
                // Close zout outputstream
1825
                if (zout != null) {
1826
                    zout.close();
1827
                }
1828
                // close output stream
1829
                if (out != null) {
1830
                    out.close();
1831
                }
1832
                
1833
            } catch (Exception exc) {
1834
                logMetacat.error("MetaCatServlet.handleReadAction - General error: "
1835
                        + exc.getMessage());
1836
                try {
1837
                    if (out != null) {
1838
                        response.setContentType("text/xml");
1839
                        // Send back error message by printWriter
1840
                        pw = new PrintWriter(out);
1841
                        pw.println("<?xml version=\"1.0\"?>");
1842
                        pw.println("<error>");
1843
                        pw.println(notFoundE.getMessage());
1844
                        pw.println("</error>");
1845
                        pw.close();
1846
                        out.close();
1847
                        
1848
                    } else {
1849
                        response.setContentType("text/xml"); //MIME type
1850
                        // Send back error message if out = null
1851
                        if (pw == null) {
1852
                            // If pw is null, open the respnose
1853
                            pw = response.getWriter();
1854
                        }
1855
                        pw.println("<?xml version=\"1.0\"?>");
1856
                        pw.println("<error>");
1857
                        pw.println(notFoundE.getMessage());
1858
                        pw.println("</error>");
1859
                        pw.close();
1860
                    }
1861
                    // close zout
1862
                    if (zout != null) {
1863
                        zout.close();
1864
                    }
1865
                } catch (IOException ie) {
1866
                    logMetacat.error("MetaCatServlet.handleReadAction - Problem with the servlet output: "
1867
                            + ie.getMessage());
1868
                }
1869
            }
1870
        } catch (Exception e) {
1871
            try {
1872
                
1873
                if (out != null) {
1874
                    response.setContentType("text/xml"); //MIME type
1875
                    pw = new PrintWriter(out);
1876
                    pw.println("<?xml version=\"1.0\"?>");
1877
                    pw.println("<error>");
1878
                    pw.println(e.getMessage());
1879
                    pw.println("</error>");
1880
                    pw.close();
1881
                    out.close();
1882
                } else {
1883
                    response.setContentType("text/xml"); //MIME type
1884
                    // Send back error message if out = null
1885
                    if (pw == null) {
1886
                        pw = response.getWriter();
1887
                    }
1888
                    pw.println("<?xml version=\"1.0\"?>");
1889
                    pw.println("<error>");
1890
                    pw.println(e.getMessage());
1891
                    pw.println("</error>");
1892
                    pw.close();
1893
                    
1894
                }
1895
                // Close zip output stream
1896
                if (zout != null) {
1897
                    zout.close();
1898
                }
1899
                
1900
            } catch (Exception e2) {
1901
                logMetacat.error("MetaCatServlet.handleReadAction - Problem with the servlet output: "
1902
                        + e2.getMessage());
1903
                e2.printStackTrace(System.out);
1904
                
1905
            }
1906
            
1907
            logMetacat.error("MetaCatServlet.handleReadAction - General error: "
1908
                    + e.getMessage());
1909
            //e.printStackTrace(System.out);
1910
        }
1911
    }
1912
    
1913
    /** read metadata or data from Metacat
1914
     */
1915
    private void readFromMetacat(HttpServletRequest request,
1916
            HttpServletResponse response, String docid, String qformat,
1917
            String abstrpath, String user, String[] groups, boolean zip,
1918
            ZipOutputStream zout, boolean withInlineData, Hashtable<String, String[]> params)
1919
            throws ClassNotFoundException, IOException, SQLException,
1920
            McdbException, Exception {
1921
    	
1922
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1923
        try {
1924
        	
1925
            if (docid.startsWith("urn:")) {
1926
            	docid = LSIDUtil.getDocId(docid, true);               	
1927
            }
1928
            
1929
            // here is hack for handle docid=john.10(in order to tell mike.jim.10.1
1930
            // mike.jim.10, we require to provide entire docid with rev). But
1931
            // some old client they only provide docid without rev, so we need
1932
            // to handle this suituation. First we will check how many
1933
            // seperator here, if only one, we will append the rev in xml_documents
1934
            // to the id.
1935
            docid = appendRev(docid);
1936
            
1937
            DocumentImpl doc = new DocumentImpl(docid);
1938
            
1939
            //check the permission for read
1940
            if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1941
                Exception e = new Exception("User " + user
1942
                        + " does not have permission"
1943
                        + " to read the document with the docid " + docid);
1944
                
1945
                throw e;
1946
            }
1947
            
1948
            if (doc.getRootNodeID() == 0) {
1949
                // this is data file
1950
                String filepath = PropertyService.getProperty("application.datafilepath");
1951
                if (!filepath.endsWith("/")) {
1952
                    filepath += "/";
1953
                }
1954
                String filename = filepath + docid;
1955
                FileInputStream fin = null;
1956
                fin = new FileInputStream(filename);
1957
                
1958
                //MIME type
1959
                String contentType = getServletContext().getMimeType(filename);
1960
                if (contentType == null) {
1961
                    ContentTypeProvider provider = new ContentTypeProvider(
1962
                            docid);
1963
                    contentType = provider.getContentType();
1964
                    logMetacat.info("MetaCatServlet.readFromMetacat - Final contenttype is: "
1965
                            + contentType);
1966
                }
1967
                
1968
                response.setContentType(contentType);
1969
                // if we decide to use "application/octet-stream" for all data
1970
                // returns
1971
                // response.setContentType("application/octet-stream");
1972

  
1973
                // check for the existence of a metadatadocid parameter,
1974
                // if this is sent, then send a filename which contains both
1975
                // the metadata docid and the data docid, so the link with
1976
                // metadata is explicitly encoded in the filename.
1977
                String metadatadocid = null;
1978
                Vector<String> nameparts = new Vector<String>();
1979

  
1980
                if(params.containsKey("metadatadocid")) {
1981
                    metadatadocid = params.get("metadatadocid")[0];
1982
                }
1983
                if (metadatadocid != null && !metadatadocid.equals("")) {
1984
                    nameparts.add(metadatadocid);
1985
                }
1986
                // we'll always have the docid, include it in the name
1987
                String doctype = doc.getDoctype();
1988
								// TODO: fix this to lookup the associated FGDC metadata document,
1989
								// and grab the doctype tag for it.  These should be set to something 
1990
								// consistent, not 'metadata' as it stands...
1991
                //if (!doctype.equals("metadata")) {
1992
                //    nameparts.add(docid);
1993
                //} 
1994
								nameparts.add(docid);
1995
                // Set the name of the data file to the entity name plus docid,
1996
                // or if that is unavailable, use the docid alone
1997
                String docname = doc.getDocname();
1998
                if (docname != null && !docname.equals("")) {
1999
                    nameparts.add(docname); 
2000
                }
2001
                // combine the name elements with a dash, using a 'join' equivalent
2002
                String outputname = null;
2003
                String delimiter = "-";
2004
                Iterator<String> iter = nameparts.iterator();
2005
                StringBuffer buffer = new StringBuffer(iter.next());
2006
                while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
2007
                outputname = buffer.toString();    
2008
                
2009
                response.setHeader("Content-Disposition",
2010
                        "attachment; filename=\"" + outputname + "\"");
2011
                
2012
                try {
2013
                    ServletOutputStream out = response.getOutputStream();
2014
                    byte[] buf = new byte[4 * 1024]; // 4K buffer
2015
                    int b = fin.read(buf);
2016
                    while (b != -1) {
2017
                        out.write(buf, 0, b);
2018
                        b = fin.read(buf);
2019
                    }
2020
                } finally {
2021
                    if (fin != null) fin.close();
2022
                }
2023
                
2024
            } else {
2025
                // this is metadata doc
2026
            	ServletOutputStream streamOut = response.getOutputStream();
2027
                if (qformat.equals("xml") || qformat.equals("")) {
2028
                    // if equals "", that means no qformat is specified. hence
2029
                    // by default the document should be returned in xml format
2030
                    // set content type first
2031
                    response.setContentType("text/xml"); //MIME type
2032
                    response.setHeader("Content-Disposition",
2033
                            "attachment; filename=" + docid + ".xml");
2034
                    
2035
                    // Try to get the metadata file from disk. If it isn't
2036
					// found, create it from the db and write it to disk then.
2037
					try {
2038
						PrintWriter out = new PrintWriter(streamOut);
2039
						doc.toXml(out, user, groups, withInlineData);				
2040
					} catch (Exception e) {
2041
						// any exceptions in reading the xml from disc, and we go back to the
2042
						// old way of creating the xml directly.
2043
						logMetacat.error("MetaCatServlet.readFromMetacat - could not read from document file " + docid 
2044
								+ ": " + e.getMessage());
2045
						PrintWriter out = new PrintWriter(streamOut);
2046
						doc.toXmlFromDb(out, user, groups, withInlineData);
2047
					}
2048
                } else {
2049
                	// TODO MCD, this should read from disk as well?
2050
                    //*** This is a metadata doc, to be returned in a skin/custom format.
2051
                    //*** Add param to indicate if public has read access or not.
2052
                    if (!user.equals("public")) {
2053
                        if (DocumentImpl.hasReadPermission("public", null, docid))
2054
                            params.put("publicRead", new String[] {"true"});
2055
                        else
2056
                            params.put("publicRead", new String[] {"false"});
2057
                    }
2058
                    
2059
                    response.setContentType("text/html"); //MIME type
2060
                    PrintWriter out = new PrintWriter(streamOut);
2061
                    
2062
                    // Look up the document type
2063
                    String doctype = doc.getDoctype();
2064
                    // Transform the document to the new doctype
2065
                    DBTransform dbt = new DBTransform();
2066
                    dbt.transformXMLDocument(doc.toString(user, groups,
2067
                            withInlineData), doctype, "-//W3C//HTML//EN",
2068
                            qformat, out, params, null);
2069
                }
2070
                
2071
            }
2072
            EventLog.getInstance().log(request.getRemoteAddr(), user,
2073
                    docid, "read");
2074
        } catch (Exception except) {
2075
            throw except;
2076
        }
2077
    }
2078
    
2079
    /**
2080
     * read data from URLConnection
2081
     */
2082
    private void readFromURLConnection(HttpServletResponse response,
2083
            String docid) throws IOException, MalformedURLException {
2084
        ServletOutputStream out = response.getOutputStream();
2085
        String contentType = getServletContext().getMimeType(docid); //MIME
2086
        // type
2087
        if (contentType == null) {
2088
            if (docid.endsWith(".xml")) {
2089
                contentType = "text/xml";
2090
            } else if (docid.endsWith(".css")) {
2091
                contentType = "text/css";
2092
            } else if (docid.endsWith(".dtd")) {
2093
                contentType = "text/plain";
2094
            } else if (docid.endsWith(".xsd")) {
2095
                contentType = "text/xml";
2096
            } else if (docid.endsWith("/")) {
2097
                contentType = "text/html";
2098
            } else {
2099
                File f = new File(docid);
2100
                if (f.isDirectory()) {
2101
                    contentType = "text/html";
2102
                } else {
2103
                    contentType = "application/octet-stream";
2104
                }
2105
            }
2106
        }
2107
        response.setContentType(contentType);
2108
        // if we decide to use "application/octet-stream" for all data returns
2109
        // response.setContentType("application/octet-stream");
2110
        
2111
        // this is http url
2112
        URL url = new URL(docid);
2113
        BufferedInputStream bis = null;
2114
        try {
2115
            bis = new BufferedInputStream(url.openStream());
2116
            byte[] buf = new byte[4 * 1024]; // 4K buffer
2117
            int b = bis.read(buf);
2118
            while (b != -1) {
2119
                out.write(buf, 0, b);
2120
                b = bis.read(buf);
2121
            }
2122
        } finally {
2123
            if (bis != null) bis.close();
2124
        }
2125
        
2126
    }
2127
    
2128
    /**
2129
     * read file/doc and write to ZipOutputStream
2130
     *
2131
     * @param docid
2132
     * @param zout
2133
     * @param user
2134
     * @param groups
2135
     * @throws ClassNotFoundException
2136
     * @throws IOException
2137
     * @throws SQLException
2138
     * @throws McdbException
2139
     * @throws Exception
2140
     */
2141
    private void addDocToZip(HttpServletRequest request, String docid, String providedFileName,
2142
            ZipOutputStream zout, String user, String[] groups) throws
2143
            ClassNotFoundException, IOException, SQLException, McdbException,
2144
            Exception {
2145
        byte[] bytestring = null;
2146
        ZipEntry zentry = null;
2147
        
2148
        try {
2149
            URL url = new URL(docid);
2150
            
2151
            // this http url; read from URLConnection; add to zip
2152
            //use provided file name if we have one
2153
            if (providedFileName != null && providedFileName.length() > 1) {
2154
            	zentry = new ZipEntry(providedFileName);
2155
            }
2156
            else {
2157
            	zentry = new ZipEntry(docid);
2158
            }
2159
            zout.putNextEntry(zentry);
2160
            BufferedInputStream bis = null;
2161
            try {
2162
                bis = new BufferedInputStream(url.openStream());
2163
                byte[] buf = new byte[4 * 1024]; // 4K buffer
2164
                int b = bis.read(buf);
2165
                while (b != -1) {
2166
                    zout.write(buf, 0, b);
2167
                    b = bis.read(buf);
2168
                }
2169
            } finally {
2170
                if (bis != null) bis.close();
2171
            }
2172
            zout.closeEntry();
2173
            
2174
        } catch (MalformedURLException mue) {
2175
            
2176
            // this is metacat doc (data file or metadata doc)
2177
            try {
2178
                DocumentImpl doc = new DocumentImpl(docid);
2179
                
2180
                //check the permission for read
2181
                if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
2182
                    Exception e = new Exception("User " + user
2183
                            + " does not have "
2184
                            + "permission to read the document with the docid "
2185
                            + docid);
2186
                    throw e;
2187
                }
2188
                
2189
                if (doc.getRootNodeID() == 0) {
2190
                    // this is data file; add file to zip
2191
                    String filepath = PropertyService.getProperty("application.datafilepath");
2192
                    if (!filepath.endsWith("/")) {
2193
                        filepath += "/";
2194
                    }
2195
                    String filename = filepath + docid;
2196
                    FileInputStream fin = null;
2197
                    fin = new FileInputStream(filename);
2198
                    try {
2199
                    	//use provided file name if we have one
2200
                        if (providedFileName != null && providedFileName.length() > 1) {
2201
                        	zentry = new ZipEntry(providedFileName);
2202
                        }
2203
                        else {
2204
                        	zentry = new ZipEntry(docid);
2205
                        }
2206
                        zout.putNextEntry(zentry);
2207
                        byte[] buf = new byte[4 * 1024]; // 4K buffer
2208
                        int b = fin.read(buf);
2209
                        while (b != -1) {
2210
                            zout.write(buf, 0, b);
2211
                            b = fin.read(buf);
2212
                        }
2213
                    } finally {
2214
                        if (fin != null) fin.close();
2215
                    }
2216
                    zout.closeEntry();
2217
                    
2218
                } else {
2219
                    // this is metadata doc; add doc to zip
2220
                    bytestring = doc.toString().getBytes();
2221
                    //use provided file name if given
2222
                    if (providedFileName != null && providedFileName.length() > 1) {
2223
                    	zentry = new ZipEntry(providedFileName);
2224
                    }
2225
                    else {
2226
                    	zentry = new ZipEntry(docid + ".xml");
2227
                    }
2228
                    zentry.setSize(bytestring.length);
2229
                    zout.putNextEntry(zentry);
2230
                    zout.write(bytestring, 0, bytestring.length);
2231
                    zout.closeEntry();
2232
                }
2233
                EventLog.getInstance().log(request.getRemoteAddr(), user,
2234
                        docid, "read");
2235
            } catch (Exception except) {
2236
                throw except;
2237
            }
2238
        }
2239
    }
2240
    
2241
    /**
2242
     * If metacat couldn't find a data file or document locally, it will read
2243
     * this docid from its home server. This is for the replication feature
2244
     */
2245
    private void readFromRemoteMetaCat(HttpServletResponse response,
2246
            String docid, String rev, String user, String password,
2247
            ServletOutputStream out, boolean zip, ZipOutputStream zout)
2248
            throws Exception {
2249
        // Create a object of RemoteDocument, "" is for zipEntryPath
2250
        RemoteDocument remoteDoc = new RemoteDocument(docid, rev, user,
2251
                password, "");
2252
        String docType = remoteDoc.getDocType();
2253
        // Only read data file
2254
        if (docType.equals("BIN")) {
2255
            // If it is zip format
2256
            if (zip) {
2257
                remoteDoc.readDocumentFromRemoteServerByZip(zout);
2258
            } else {
2259
                if (out == null) {
2260
                    out = response.getOutputStream();
2261
                }
2262
                response.setContentType("application/octet-stream");
2263
                remoteDoc.readDocumentFromRemoteServer(out);
2264
            }
2265
        } else {
2266
            throw new Exception("Docid: " + docid + "." + rev
2267
                    + " couldn't find");
2268
        }
2269
    }
2270
    
2271
    /**
2272
     * Handle the database putdocument request and write an XML document to the
2273
     * database connection
2274
     */
2275
    private void handleInsertOrUpdateAction(HttpServletRequest request,
2276
            HttpServletResponse response, PrintWriter out, Hashtable<String, String[]> params,
2277
            String user, String[] groups) {
2278
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2279
        DBConnection dbConn = null;
2280
        int serialNumber = -1;
2281
        String output = "";
2282
        String qformat = null;
2283
        if(params.containsKey("qformat"))
2284
        {
2285
          qformat = params.get("qformat")[0];
2286
        }
2287
        
2288
        if(params.get("docid") == null){
2289
            out.println("<?xml version=\"1.0\"?>");
2290
            out.println("<error>");
2291
            out.println("Docid not specified");
2292
            out.println("</error>");
2293
            logMetacat.error("MetaCatServlet.handleInsertOrUpdateAction - Docid not specified");
2294
            return;
2295
        }
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff