Project

General

Profile

« Previous | Next » 

Revision 2819

Added by Matt Jones over 18 years ago

Reformatted LSID code for consistency.

View differences:

src/edu/ucsb/nceas/metacat/lsid/LSIDDataLookup.java
36 36
import com.ibm.lsid.LSID;
37 37
import com.ibm.lsid.server.LSIDServerException;
38 38

  
39
public class LSIDDataLookup {
39
public class LSIDDataLookup
40
{
41
    public static final int UNKNOWN = 1;
42
    public static final int ABSTRACT = 2;
43
    public static final int CONCRETE = 4;
40 44

  
41
//	private static Connection lsidLookup = null;
45
    private static Log logger = LogFactory
46
                    .getLog("edu.ucsb.nceas.metacat.lsid");
42 47

  
43
	public static final int UNKNOWN = 1;
44
	public static final int ABSTRACT = 2;
45
	public static final int CONCRETE = 4;
46
    
47
    private static Log logger = LogFactory.getLog( "edu.ucsb.nceas.metacat.lsid" );
48

  
49
	public LSIDDataLookup() throws LSIDServerException {
48
    public LSIDDataLookup() throws LSIDServerException
49
    {
50 50
        logger.info("Creating LSIDDataLookup (Metacat).");
51
  	}
51
    }
52 52

  
53
    public int lsidType(LSID lsid) throws LSIDServerException
54
    {
53 55

  
54
	public int lsidType(LSID lsid) throws LSIDServerException {
56
        int result = CONCRETE;
57
        return result;
58
    }
55 59

  
56
		int result = CONCRETE;
57
		return result;
58
	}
60
    public InputStream lsidData(LSID lsid) throws LSIDServerException
61
    {
62
        String ns = lsid.getNamespace();
63
        String id = lsid.getObject();
64
        String ver = lsid.getRevision();
65
        InputStream docStream = null;
59 66

  
60
	public InputStream lsidData(LSID lsid) throws LSIDServerException {
61
		String ns = lsid.getNamespace();
62
		String id = lsid.getObject();
63
		String ver = lsid.getRevision();
64
		InputStream docStream = null;
65
		
67
        // example metacat query
68
        // http://metacat.nceas.ucsb.edu/knb/metacat?action=read&qformat=xml&docid=knb-lter-gce.109.6
69
        //
66 70

  
67
		// example metacat query
68
		// http://metacat.nceas.ucsb.edu/knb/metacat?action=read&qformat=xml&docid=knb-lter-gce.109.6
69
		//
70
		
71
		ResourceBundle rb = ResourceBundle.getBundle("metacat-lsid");
72
		String theServer = rb.getString("metacatserver");
73
		logger.debug("the server is " + theServer);
71
        ResourceBundle rb = ResourceBundle.getBundle("metacat-lsid");
72
        String theServer = rb.getString("metacatserver");
73
        logger.debug("the server is " + theServer);
74 74

  
75
		String url = theServer + "?action=read&qformat=xml&docid=";
76
		url = url + ns + "." + id + "." + ver;
77
		try {
78
			URL theDoc = new URL(url);
79
			docStream  = theDoc.openStream();
80
		} catch (MalformedURLException mue) {
81
         		logger.error("MalformedURLException in LSIDDataLookup: " + mue);
82
         		mue.printStackTrace();
83
   		} catch (IOException ioe) {
84
         		logger.error("IOException in LSIDDataLookup: " + ioe);
85
         		ioe.printStackTrace();
86
		}
87

  
88

  
89
		return docStream;
90
	}
91

  
75
        String url = theServer + "?action=read&qformat=xml&docid=";
76
        url = url + ns + "." + id + "." + ver;
77
        try {
78
            URL theDoc = new URL(url);
79
            docStream = theDoc.openStream();
80
        } catch (MalformedURLException mue) {
81
            logger.error("MalformedURLException in LSIDDataLookup: " + mue);
82
            mue.printStackTrace();
83
        } catch (IOException ioe) {
84
            logger.error("IOException in LSIDDataLookup: " + ioe);
85
            ioe.printStackTrace();
86
        }
87
        return docStream;
88
    }
92 89
}
src/edu/ucsb/nceas/metacat/lsid/LSIDAuthorityMetaData.java
55 55
import edu.ucsb.nceas.metacat.client.MetacatFactory;
56 56
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
57 57

  
58
public class LSIDAuthorityMetaData implements LSIDMetadataService {
58
public class LSIDAuthorityMetaData implements LSIDMetadataService
59
{
60
    private LSIDDataLookup lookup = null;
61
    private static Hashtable currentLSIDs = new Hashtable();
62
    private static Log logger = LogFactory
63
                    .getLog("edu.ucsb.nceas.metacat.lsid");
59 64

  
60
	private LSIDDataLookup lookup = null;
61
	private static Hashtable currentLSIDs = new Hashtable();
62
    private static Log logger = LogFactory.getLog( "edu.ucsb.nceas.metacat.lsid" );
63
    
64
	public void initService(LSIDServiceConfig cf) throws LSIDServerException {
65
    public void initService(LSIDServiceConfig cf) throws LSIDServerException
66
    {
65 67
        logger.info("Starting LSIDAuthorityMetadata.");
66
		lookup = new LSIDDataLookup();
67
	}
68
        lookup = new LSIDDataLookup();
69
    }
68 70

  
69
	private static final String RDF_NS =
70
		"http://www.w3.org/1999/02/22-rdf-syntax-ns#";
71
	private static final String DC_NS = "http://purl.org/dc/elements/1.1/";
72
	private static final String I3CP_NS = "urn:lsid:i3c.org:predicates:";
73
	private static final String I3C_CONTENT = "urn:lsid:i3c.org:types:content";
71
    private static final String RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
72
    private static final String DC_NS = "http://purl.org/dc/elements/1.1/";
73
    private static final String I3CP_NS = "urn:lsid:i3c.org:predicates:";
74
    private static final String I3C_CONTENT = "urn:lsid:i3c.org:types:content";
74 75

  
75
	public MetadataResponse getMetadata(
76
		LSIDRequestContext req,
77
		String[] formats)
78
		throws LSIDServerException {
79
		LSID lsid = req.getLsid();
80
		ByteArrayInputStream theMetadata = doMetadataRequest(lsid);
81
		return new MetadataResponse(
82
			theMetadata,
83
			null,
84
			MetadataResponse.RDF_FORMAT);
85
	}
76
    public MetadataResponse getMetadata(LSIDRequestContext req, String[] formats)
77
                    throws LSIDServerException
78
    {
79
        LSID lsid = req.getLsid();
80
        ByteArrayInputStream theMetadata = doMetadataRequest(lsid);
81
        return new MetadataResponse(theMetadata, null,
82
                                    MetadataResponse.RDF_FORMAT);
83
    }
86 84

  
87
	private ByteArrayInputStream doMetadataRequest(LSID lsid)
88
		throws LSIDServerException {
89
		logger.debug("getting metadata for lsid " + lsid.getLsid());
90
		try {
85
    private ByteArrayInputStream doMetadataRequest(LSID lsid)
86
                    throws LSIDServerException
87
    {
88
        logger.debug("getting metadata for lsid " + lsid.getLsid());
89
        try {
91 90

  
92
			String styleSheetName = null;
93
			styleSheetName = "metacat.xslt";
94
			LSIDDataLookup myLookup = new LSIDDataLookup();
95
			InputStream content = myLookup.lsidData(lsid);
96
			InputStream content2 = myLookup.lsidData(lsid);
97
			if (!isEML(content2)) {
98
				content = getEML(lsid);
99
			}
100
			content2.close();
101
			setCurrentLSID(lsid);
102
			InputStream styleSheet =
103
				getClass().getResourceAsStream(styleSheetName);
104
			TransformerFactory factory = TransformerFactory.newInstance();
105
			Transformer transformer =
106
				factory.newTransformer(new StreamSource(styleSheet));
107
			ByteArrayOutputStream out = new ByteArrayOutputStream();
108
			transformer.transform(
109
				new StreamSource(content),
110
				new StreamResult(out));
111
			content.close();
112
			clearState();
113
			return new ByteArrayInputStream(out.toByteArray());
114
		} catch (Exception e) {
115
			throw new LSIDServerException(
116
				e,
117
				"Error transforming XML for: " + lsid);
118
		}
119
	}
91
            String styleSheetName = null;
92
            styleSheetName = "metacat.xslt";
93
            LSIDDataLookup myLookup = new LSIDDataLookup();
94
            InputStream content = myLookup.lsidData(lsid);
95
            InputStream content2 = myLookup.lsidData(lsid);
96
            if (!isEML(content2)) {
97
                content = getEML(lsid);
98
            }
99
            content2.close();
100
            setCurrentLSID(lsid);
101
            InputStream styleSheet = getClass()
102
                            .getResourceAsStream(styleSheetName);
103
            TransformerFactory factory = TransformerFactory.newInstance();
104
            Transformer transformer = factory
105
                            .newTransformer(new StreamSource(styleSheet));
106
            ByteArrayOutputStream out = new ByteArrayOutputStream();
107
            transformer.transform(new StreamSource(content),
108
                                  new StreamResult(out));
109
            content.close();
110
            clearState();
111
            return new ByteArrayInputStream(out.toByteArray());
112
        } catch (Exception e) {
113
            throw new LSIDServerException(e, "Error transforming XML for: "
114
                                             + lsid);
115
        }
116
    }
120 117

  
121
	private String getStringFromInputStream(InputStream input) {
122
		StringBuffer result = new StringBuffer();
123
		BufferedReader in = new BufferedReader(new InputStreamReader(input));
124
		String line;
125
		try {
126
			while ((line = in.readLine()) != null) {
127
				result.append(line);
128
			}
129
		} catch (IOException e) {
130
			logger.error("IOexception " + e);
131
		}
118
    private String getStringFromInputStream(InputStream input)
119
    {
120
        StringBuffer result = new StringBuffer();
121
        BufferedReader in = new BufferedReader(new InputStreamReader(input));
122
        String line;
123
        try {
124
            while ((line = in.readLine()) != null) {
125
                result.append(line);
126
            }
127
        } catch (IOException e) {
128
            logger.error("IOexception " + e);
129
        }
132 130

  
133
		return result.toString();
131
        return result.toString();
134 132

  
135
	}
133
    }
136 134

  
137
	/**
138
	 * figure out is this inputstream is an eml document or not
139
		 */
135
    /**
136
     * figure out is this inputstream is an eml document or not
137
     * TODO: need a better way to figure out if this is an eml document 
138
     */
139
    private boolean isEML(InputStream input)
140
    {
140 141

  
141
	/* TODO: need a better way to figure out if this is an eml document */
142
	private boolean isEML(InputStream input) {
142
        if (input == null) { return false; }
143 143

  
144
		if (input == null) {
145
			return false;
146
		}
144
        int loop = 0;
145
        boolean itIsEML = false;
146
        String line = "";
147
        try {
148
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
149
            while ((loop < 20) && (line != null) && (!itIsEML)) {
150
                line = in.readLine();
151
                line = line.toLowerCase();
152
                if (line.indexOf("eml:eml") != -1) {
153
                    itIsEML = true;
154
                }
155
                loop++;
156
            }
157
        } catch (IOException e) {
158
            logger.error("ioerror in LSIDAuthorityMetadata: " + e);
159
        }
160
        return itIsEML;
161
    }
147 162

  
148
		int loop = 0;
149
		boolean itIsEML = false;
150
		String line = "";
151
		try {
152
			BufferedReader in =
153
				new BufferedReader(new InputStreamReader(input));
154
			while ((loop < 20) && (line != null) && (!itIsEML)) {
155
				line = in.readLine();
156
				line = line.toLowerCase();
157
				if (line.indexOf("eml:eml") != -1) {
158
					itIsEML = true;
159
				}
160
				loop++;
161
			}
162
		} catch (IOException e) {
163
			logger.error("ioerror in LSIDAuthorityMetadata: " + e);
164
		}
165
		return itIsEML;
166
	}
163
    /**
164
     * this lsid points to a data object - get the metadata objects which refer
165
     * to this document
166
     */
167
    private InputStream getEML(LSID theLSID)
168
    {
167 169

  
168
	/**
169
	 *  this lsid points to a data object - get the
170
	     *  metadata objects which refer to this document
171
	     */
170
        InputStream response = null;
172 171

  
173
	private InputStream getEML(LSID theLSID) {
172
        // need to find things with this object in any of the elements
173
        // using the metacat api
174
        // get back dataset/docid and dataset/title
174 175

  
175
		InputStream response = null;
176
        // create the query
177
        String theQuery = getMetaCatQuery(theLSID);
176 178

  
177
		// need to find things with this object in any of the elements
178
		// using the metacat api
179
		// get back dataset/docid and dataset/title
179
        // get the metacat record
180
        Reader metaCatResponse = getMetaCatResponse(theQuery);
180 181

  
181
		// create the query
182
		String theQuery = getMetaCatQuery(theLSID);
182
        // parse the metadata to get the applicable rdf information
183
        response = parseMetaCatResponse(metaCatResponse, theLSID);
183 184

  
184
		// get the metacat record
185
		Reader metaCatResponse = getMetaCatResponse(theQuery);
185
        return response;
186 186

  
187
		// parse the metadata to get the applicable rdf information
188
		response = parseMetaCatResponse(metaCatResponse, theLSID);
187
    }
189 188

  
190
		return response;
191

  
192
	}
193

  
194
	/** 
195
	 * given an LSID return a metacat query which will return docs mentioning this LSID
196
	 */
197

  
198
	private String getMetaCatQuery(LSID lsid) {
189
    /**
190
     * given an LSID return a metacat query which will return docs mentioning
191
     * this LSID
192
     */
193
    private String getMetaCatQuery(LSID lsid)
194
    {
199 195
        logger.debug("getting Metacat Query for: " + lsid.toString());
200
		String ns = lsid.getNamespace();
201
		String id = lsid.getObject();
202
		String ver = lsid.getRevision();
203
		String theName = ns + "." + id + "." + ver;
196
        String ns = lsid.getNamespace();
197
        String id = lsid.getObject();
198
        String ver = lsid.getRevision();
199
        String theName = ns + "." + id + "." + ver;
204 200

  
205
		String theQuery = null;
206
		theQuery =
207
			"<?xml version=\"1.0\"?>\n"
208
				+ "<pathquery version=\"1.2\">\n"
209
				+ "  <querytitle>"
210
				+ theName
211
				+ " search</querytitle>\n"
212
				+ "  <returnfield>dataset/docid</returnfield>\n"
213
				+ "  <returnfield>dataset/title</returnfield>\n"
214
				+ "  <querygroup operator=\"UNION\">\n"
215
				+ "    <queryterm searchmode=\"contains\" casesensitive=\"false\">\n"
216
				+ "      <value>"
217
				+ theName
218
				+ "</value>\n"
219
				+ "      <pathexpr>anyfield</pathexpr>\n"
220
				+ "    </queryterm>\n"
221
				+ "  </querygroup>\n"
222
				+ "<pathquery>\n";
201
        String theQuery = null;
202
        theQuery = "<?xml version=\"1.0\"?>\n"
203
                   + "<pathquery version=\"1.2\">\n"
204
                   + "  <querytitle>"
205
                   + theName
206
                   + " search</querytitle>\n"
207
                   + "  <returnfield>dataset/docid</returnfield>\n"
208
                   + "  <returnfield>dataset/title</returnfield>\n"
209
                   + "  <querygroup operator=\"UNION\">\n"
210
                   + "    <queryterm searchmode=\"contains\" casesensitive=\"false\">\n"
211
                   + "      <value>" + theName + "</value>\n"
212
                   + "      <pathexpr>anyfield</pathexpr>\n"
213
                   + "    </queryterm>\n" + "  </querygroup>\n"
214
                   + "<pathquery>\n";
223 215

  
224
		return theQuery;
216
        return theQuery;
225 217

  
226
	}
218
    }
227 219

  
228
	/* 
229
	 * given a query string, query MetaCat and return the response
230
	 */
231
	private Reader getMetaCatResponse(String query) {
220
    /**
221
     * given a query string, query MetaCat and return the response
222
     */
223
    private Reader getMetaCatResponse(String query)
224
    {
232 225
        logger.debug("Querying the metacat server.");
233
		//  get the metacat server from the configuration file
234
		//
235
		ResourceBundle rb = ResourceBundle.getBundle("metacat-lsid");
236
		String url = rb.getString("metacatserver");
237
		Reader r = null;
238
		try {
226
        // get the metacat server from the configuration file
227
        //
228
        ResourceBundle rb = ResourceBundle.getBundle("metacat-lsid");
229
        String url = rb.getString("metacatserver");
230
        Reader r = null;
231
        try {
239 232

  
240
			Metacat m = MetacatFactory.createMetacatConnection(url);
241
			r = m.query(new StringReader(query));
233
            Metacat m = MetacatFactory.createMetacatConnection(url);
234
            r = m.query(new StringReader(query));
242 235

  
243
		} catch (MetacatInaccessibleException mie) {
236
        } catch (MetacatInaccessibleException mie) {
244 237
            logger.error("Metacat Inaccessible:\n" + mie.getMessage());
245
		} catch (Exception e) {
246
			logger.error("General exception:\n" + e.getMessage());
247
		}
248
		return r;
249
	}
238
        } catch (Exception e) {
239
            logger.error("General exception:\n" + e.getMessage());
240
        }
241
        return r;
242
    }
250 243

  
251
	/**
252
	 * Given a reader which is a metacat response, parse it and return the appropriate rdf
253
	 */
254
	private InputStream parseMetaCatResponse(Reader reader, LSID theLSID) {
255
		InputStream response = null;
244
    /**
245
     * Given a reader which is a metacat response, parse it and return the
246
     * appropriate rdf
247
     */
248
    private InputStream parseMetaCatResponse(Reader reader, LSID theLSID)
249
    {
250
        InputStream response = null;
256 251
        logger.debug("Parsing the metacat response.");
257
		// if there's more than one document, then return rdf listing the documents
258
		// otherwise get the document and return rdf  based on it
252
        // if there's more than one document, then return rdf listing the
253
        // documents
254
        // otherwise get the document and return rdf based on it
259 255

  
260
		String contents = getStringFromReader(reader);
261
		if (numberDocuments(contents) < 1) {
262
			response = noMetaDataResponse(theLSID);
263
		} else if (numberDocuments(contents) > 1) {
264
			response = metaDataList(contents, theLSID);
265
		} else {
266
			response = getMetaData(contents, theLSID);
267
		}
268
		return response;
269
	}
256
        String contents = getStringFromReader(reader);
257
        if (numberDocuments(contents) < 1) {
258
            response = noMetaDataResponse(theLSID);
259
        } else if (numberDocuments(contents) > 1) {
260
            response = metaDataList(contents, theLSID);
261
        } else {
262
            response = getMetaData(contents, theLSID);
263
        }
264
        return response;
265
    }
270 266

  
271
	/**
272
	 *  There's no metadata for this document 
273
	*/
267
    /**
268
     * There's no metadata for this document
269
     */
270
    private ByteArrayInputStream noMetaDataResponse(LSID theLSID)
271
    {
272
        ResourceBundle rb = ResourceBundle.getBundle("metacat-lsid");
273
        String metadataLabels = rb.getString("metadatalabels");
274 274

  
275
	private ByteArrayInputStream noMetaDataResponse(LSID theLSID) {
276
		ResourceBundle rb = ResourceBundle.getBundle("metacat-lsid");
277
		String metadataLabels = rb.getString("metadatalabels");
275
        String result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
276
                        + "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" \n"
277
                        + "	xmlns:dc=\"http://purl.org/dc/elements/1.1/\" \n"
278
                        + "	xmlns:pred=\"urn:lsid:i3c.org:predicates:\" xmlns=\"urn:lsid:"
279
                        + metadataLabels
280
                        + ":predicates:\"> \n"
281
                        + "<rdf:Description rdf:about=\""
282
                        + theLSID.getLsid()
283
                        + "\"> \n"
284
                        + "	<pred:title xmlns:pred=\"http://purl.org/dc/elements/1.1/\">There is no metadata for this LSID.</pred:title>\n"
285
                        + "</rdf:Description>\n" + "</rdf:RDF>\n";
278 286

  
279
		String result =
280
			"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
281
				+ "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" \n"
282
				+ "	xmlns:dc=\"http://purl.org/dc/elements/1.1/\" \n"
283
				+ "	xmlns:pred=\"urn:lsid:i3c.org:predicates:\" xmlns=\"urn:lsid:" 
284
				+ metadataLabels + ":predicates:\"> \n"
285
				+ "<rdf:Description rdf:about=\""
286
				+ theLSID.getLsid()
287
				+ "\"> \n"
288
				+ "	<pred:title xmlns:pred=\"http://purl.org/dc/elements/1.1/\">There is no metadata for this LSID.</pred:title>\n"
289
				+ "</rdf:Description>\n"
290
				+ "</rdf:RDF>\n";
291
			
287
        return new ByteArrayInputStream(result.getBytes());
288
    }
292 289

  
293
		return new ByteArrayInputStream(result.getBytes());
294
	}
290
    /**
291
     * There's more than one metdata document
292
     */
293
    private ByteArrayInputStream metaDataList(String contents, LSID theLSID)
294
    {
295
        ResourceBundle rb = ResourceBundle.getBundle("metacat");
296
        String metadataLabels = rb.getString("metadatalabels");
295 297

  
296
	/**
297
	 *  There's more than one metdata document
298
	     */
298
        String result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
299
                        + "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" \n"
300
                        + "	xmlns:dc=\"http://purl.org/dc/elements/1.1/\" \n"
301
                        + "	xmlns:pred=\"urn:lsid:i3c.org:predicates:\" xmlns=\"urn:lsid:"
302
                        + metadataLabels
303
                        + ":predicates:\"> \n"
304
                        + "<rdf:Description rdf:about=\""
305
                        + theLSID.getLsid()
306
                        + "\"> \n"
307
                        + "	<pred:title xmlns:pred=\"http://purl.org/dc/elements/1.1/\">There is more than one metadata document for this LSID - which confuses me right now.  Try again soon and I'll be less confused.</pred:title>\n"
308
                        + "</rdf:Description>\n" + "</rdf:RDF>\n";
299 309

  
300
	private ByteArrayInputStream metaDataList(String contents, LSID theLSID) {
301
		ResourceBundle rb = ResourceBundle.getBundle("metacat");
302
		String metadataLabels = rb.getString("metadatalabels");
310
        return new ByteArrayInputStream(result.getBytes());
311
    }
303 312

  
304
		String result =
305
			"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
306
				+ "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" \n"
307
				+ "	xmlns:dc=\"http://purl.org/dc/elements/1.1/\" \n"
308
				+ "	xmlns:pred=\"urn:lsid:i3c.org:predicates:\" xmlns=\"urn:lsid:"
309
				+ metadataLabels + ":predicates:\"> \n"
310
				+ "<rdf:Description rdf:about=\""
311
				+ theLSID.getLsid()
312
				+ "\"> \n"
313
				+ "	<pred:title xmlns:pred=\"http://purl.org/dc/elements/1.1/\">There is more than one metadata document for this LSID - which confuses me right now.  Try again soon and I'll be less confused.</pred:title>\n"
314
				+ "</rdf:Description>\n"
315
				+ "</rdf:RDF>\n";
313
    /**
314
     * There's just one metadata document
315
     */
316
    private ByteArrayInputStream getMetaData(String contents, LSID theLSID)
317
    {
318
        String paramString = "<param name=\"dataset/title\">";
319
        ByteArrayInputStream result = null;
316 320

  
317
		return new ByteArrayInputStream(result.getBytes());
318
	}
321
        if (contents.indexOf(paramString) == -1) {
322
            return noMetaDataResponse(theLSID);
323
        } else {
324
            String parts[] = contents.split(paramString);
325
            String parts2[] = parts[1].split("</param>");
326
            try {
327
                LSID newLSID = new LSID(parts2[0]);
328
                result = doMetadataRequest(newLSID);
319 329

  
320
	/**
321
	 *  There's just one metadata document 
322
	     */
323

  
324
	private ByteArrayInputStream getMetaData(String contents, LSID theLSID) {
325
		String paramString = "<param name=\"dataset/title\">";
326
		ByteArrayInputStream result = null;
327

  
328
		if (contents.indexOf(paramString) == -1) {
329
			return noMetaDataResponse(theLSID);
330
		} else {
331
			String parts[] = contents.split(paramString);
332
			String parts2[] = parts[1].split("</param>");
333
			try {
334
				LSID newLSID = new LSID(parts2[0]);
335
				result = doMetadataRequest(newLSID);
336

  
337
			} catch (MalformedLSIDException e) {
330
            } catch (MalformedLSIDException e) {
338 331
                logger.error("problem generating LSID: " + e);
339
				e.printStackTrace();
340
			} catch (LSIDServerException e) {
332
                e.printStackTrace();
333
            } catch (LSIDServerException e) {
341 334
                logger.error("problem generating LSID: " + e);
342
				e.printStackTrace();
343
			}
344
		}
345
		return result;
346
	}
335
                e.printStackTrace();
336
            }
337
        }
338
        return result;
339
    }
347 340

  
348
	/**
349
	 *  Find out how many contents are in this metacat response
350
	 *  I'm just using string stuff for this - sort of lame, but does the trick
351
	 *  more cool would be to use xml stuff
352
	 */
353
	private int numberDocuments(String contents) {
341
    /**
342
     * Find out how many contents are in this metacat response I'm just using
343
     * string stuff for this - sort of lame, but does the trick more cool would
344
     * be to use xml stuff
345
     */
346
    private int numberDocuments(String contents)
347
    {
354 348

  
355
		String[] docSplit = contents.split("<document>");
356
		return (docSplit.length - 1);
357
	}
349
        String[] docSplit = contents.split("<document>");
350
        return (docSplit.length - 1);
351
    }
358 352

  
359
	/**
360
	 * Given a reader, return a string
361
	 */
362
	private String getStringFromReader(Reader reader) {
363
		StringBuffer response = new StringBuffer();
353
    /**
354
     * Given a reader, return a string
355
     */
356
    private String getStringFromReader(Reader reader)
357
    {
358
        StringBuffer response = new StringBuffer();
364 359

  
365
		try {
366
			BufferedReader bufReader = new BufferedReader(reader);
360
        try {
361
            BufferedReader bufReader = new BufferedReader(reader);
367 362

  
368
			String line = null;
369
			while ((line = bufReader.readLine()) != null) {
370
				response.append(line);
371
			}
372
			bufReader.close();
363
            String line = null;
364
            while ((line = bufReader.readLine()) != null) {
365
                response.append(line);
366
            }
367
            bufReader.close();
373 368

  
374
		} catch (IOException e) {
375
			logger.error("error getting string from reader " + e);
376
		}
377
		return response.toString();
378
	}
369
        } catch (IOException e) {
370
            logger.error("error getting string from reader " + e);
371
        }
372
        return response.toString();
373
    }
379 374

  
380
	/**
381
	 * set the LSID for the current thread
382
	 */
383
	static void setCurrentLSID(LSID lsid) {
384
		currentLSIDs.put(Thread.currentThread(), lsid);
385
	}
375
    /**
376
     * set the LSID for the current thread
377
     */
378
    static void setCurrentLSID(LSID lsid)
379
    {
380
        currentLSIDs.put(Thread.currentThread(), lsid);
381
    }
386 382

  
387
	static void clearState() {
388
		currentLSIDs.remove(Thread.currentThread());
389
	}
383
    static void clearState()
384
    {
385
        currentLSIDs.remove(Thread.currentThread());
386
    }
390 387

  
391
	/**
392
	 * get the current LSID for the given thread, for use in XSLT so return a string
393
	 */
394
	//	public static String getLSID() throws MalformedLSIDException {
395
	//		return ((LSID)currentLSIDs.get(Thread.currentThread())).toString();
396
	//	}
388
    /**
389
     * get the current LSID for the given thread, for use in XSLT so return a
390
     * string
391
     */
392
    public static String getLSID(
393
                         org.apache.xalan.extensions.XSLProcessorContext foo,
394
                         org.apache.xalan.templates.ElemExtensionCall bar)
395
                    throws MalformedLSIDException
396
    {
397
        return ((LSID) currentLSIDs.get(Thread.currentThread())).toString();
398
    }
397 399

  
398
	public static String getLSID(
399
		org.apache.xalan.extensions.XSLProcessorContext foo,
400
		org.apache.xalan.templates.ElemExtensionCall bar)
401
		throws MalformedLSIDException {
402
		return ((LSID) currentLSIDs.get(Thread.currentThread())).toString();
403
	}
404

  
405
	public static String getLSID() throws MalformedLSIDException {
406
		return ((LSID) currentLSIDs.get(Thread.currentThread())).toString();
407
	}
400
    public static String getLSID() throws MalformedLSIDException
401
    {
402
        return ((LSID) currentLSIDs.get(Thread.currentThread())).toString();
403
    }
408 404
}
src/edu/ucsb/nceas/metacat/lsid/LSIDAuthorityMain.java
40 40
import com.ibm.lsid.wsdl.LSIDMetadataPort;
41 41
import com.ibm.lsid.wsdl.SOAPLocation;
42 42

  
43
public class LSIDAuthorityMain extends SimpleAuthority {
43
public class LSIDAuthorityMain extends SimpleAuthority
44
{
44 45

  
45
	private LSIDDataLookup lookup = null;
46
    private static Log logger = LogFactory.getLog( "edu.ucsb.nceas.metacat.lsid" );
47
    
48
	public void initService(LSIDServiceConfig cf) throws LSIDServerException {
46
    private LSIDDataLookup lookup = null;
47
    private static Log logger = LogFactory
48
                    .getLog("edu.ucsb.nceas.metacat.lsid");
49

  
50
    public void initService(LSIDServiceConfig cf) throws LSIDServerException
51
    {
49 52
        logger.info("Starting LSIDAuthorityMain.");
50
		lookup = new LSIDDataLookup();
51
	}
53
        lookup = new LSIDDataLookup();
54
    }
52 55

  
53
	public ExpiringResponse getKnownURIs() throws LSIDServerException {
56
    public ExpiringResponse getKnownURIs() throws LSIDServerException
57
    {
54 58
        logger.debug("In LSIDAuthorityMain.getKnownURIs()");
55
		return null;
56
	}
59
        return null;
60
    }
57 61

  
58
	public LSIDMetadataPort[] getMetadataLocations(LSID lsid, String url) {
62
    public LSIDMetadataPort[] getMetadataLocations(LSID lsid, String url)
63
    {
59 64
        logger.debug("In LSIDAuthorityMain.getMetadataLocations()");
60 65
        if (lookup == null)
61
			return null;
66
            return null;
62 67

  
63
		int lsType;
64
		try {
65
			lsType = lookup.lsidType(lsid);
66
		}
67
		catch (LSIDServerException ex) {
68
			ex.printStackTrace();
69
			lsType = LSIDDataLookup.UNKNOWN;
70
		}
71
		if (lsType == LSIDDataLookup.UNKNOWN)
72
			return null;
68
        int lsType;
69
        try {
70
            lsType = lookup.lsidType(lsid);
71
        } catch (LSIDServerException ex) {
72
            ex.printStackTrace();
73
            lsType = LSIDDataLookup.UNKNOWN;
74
        }
75
        if (lsType == LSIDDataLookup.UNKNOWN)
76
            return null;
73 77

  
74
		HostDescriptor hd = new HostDescriptor(url);
75
		return new LSIDMetadataPort[] {
76
		// thau added http metadata port here
77
			new HTTPLocation(
78
				hd.host, hd.port,
79
				hd.pathPrefix + "/authority/metadata" 
80
			),
81
		new SOAPLocation(
82
				hd.baseURL + "metadata"
83
			)
84
		};
85
	}
78
        HostDescriptor hd = new HostDescriptor(url);
79
        return new LSIDMetadataPort[] {
80
                        // thau added http metadata port here
81
                        new HTTPLocation(hd.host, hd.port,
82
                                         hd.pathPrefix + "/authority/metadata"),
83
                        new SOAPLocation(hd.baseURL + "metadata")};
84
    }
86 85

  
87
	public LSIDDataPort[] getDataLocations(LSID lsid, String url) {
86
    public LSIDDataPort[] getDataLocations(LSID lsid, String url)
87
    {
88 88
        logger.debug("In LSIDAuthorityMain.getDataLocations()");
89
		if (lookup == null)
90
			return null;
89
        if (lookup == null)
90
            return null;
91 91

  
92
		int lsType;
93
		try {
94
			lsType = lookup.lsidType(lsid);
95
		}
96
		catch (LSIDServerException ex) {
97
			ex.printStackTrace();
98
			lsType = LSIDDataLookup.UNKNOWN;
99
		}
100
		if (lsType == LSIDDataLookup.UNKNOWN)
101
			return null;
102
		if (lsType == LSIDDataLookup.ABSTRACT)
103
			return new LSIDDataPort[0];
104
		
105
		HostDescriptor hd = new HostDescriptor(url);
106
		return new LSIDDataPort[] {
107
			new HTTPLocation(
108
				hd.host, hd.port,
109
				hd.pathPrefix + "/authority/data"
110
			),
111
			new SOAPLocation(
112
				hd.baseURL + "data"
113
			)
114
		};
115
	}
92
        int lsType;
93
        try {
94
            lsType = lookup.lsidType(lsid);
95
        } catch (LSIDServerException ex) {
96
            ex.printStackTrace();
97
            lsType = LSIDDataLookup.UNKNOWN;
98
        }
99
        if (lsType == LSIDDataLookup.UNKNOWN)
100
            return null;
101
        if (lsType == LSIDDataLookup.ABSTRACT)
102
            return new LSIDDataPort[0];
116 103

  
117
	private static final Pattern HOST_PTN = Pattern.compile(
118
		"https?://([^/:]+)(?::(\\d+))?(.*)/authority(.*)"
119
	);
120
	
121
	/* Q&D implementation */
122
	private class HostDescriptor {
123
		public String host;
124
		public int port;
125
		public String pathPrefix;
126
		public String baseURL;
127
		
128
		public HostDescriptor(String url) {
104
        HostDescriptor hd = new HostDescriptor(url);
105
        return new LSIDDataPort[] {
106
                        new HTTPLocation(hd.host, hd.port, hd.pathPrefix
107
                                                           + "/authority/data"),
108
                        new SOAPLocation(hd.baseURL + "data")};
109
    }
110

  
111
    private static final Pattern HOST_PTN = Pattern
112
                    .compile("https?://([^/:]+)(?::(\\d+))?(.*)/authority(.*)");
113

  
114
    /* Q&D implementation */
115
    private class HostDescriptor
116
    {
117
        public String host;
118
        public int port;
119
        public String pathPrefix;
120
        public String baseURL;
121

  
122
        public HostDescriptor(String url)
123
        {
129 124
            logger.debug("Creating a HostDescriptor for: " + url);
130
            //Thread.dumpStack();
131
			host = "localhost";
132
			port = -1;
133
			pathPrefix = "";
134
			if (url != null || url.length() > 0) {
125
            // Thread.dumpStack();
126
            host = "localhost";
127
            port = -1;
128
            pathPrefix = "";
129
            if (url != null || url.length() > 0) {
135 130
                logger.debug("HostDescriptor: url is > 0 length");
136
				Matcher m = HOST_PTN.matcher(url);
137
				if (m.lookingAt()) {
138
					host = m.group(1);
131
                Matcher m = HOST_PTN.matcher(url);
132
                if (m.lookingAt()) {
133
                    host = m.group(1);
139 134
                    logger.debug("HostDescriptor.host: " + host);
140
					if ((m.group(2) != null) && (m.group(2).length() > 0)) {
141
						port = Integer.parseInt(m.group(2));
135
                    if ((m.group(2) != null) && (m.group(2).length() > 0)) {
136
                        port = Integer.parseInt(m.group(2));
142 137
                    }
143 138
                    logger.debug("HostDescriptor.port: " + port);
144
					pathPrefix = m.group(3);
139
                    pathPrefix = m.group(3);
145 140
                    logger.debug("HostDescriptor.pathPrefix: " + pathPrefix);
146
				}
147
			}
148
			if (port > 0) {
149
				baseURL = "http://" + host + ":" + port +
150
					pathPrefix + "/authority/";
141
                }
142
            }
143
            if (port > 0) {
144
                baseURL = "http://" + host + ":" + port + pathPrefix
145
                          + "/authority/";
151 146
            } else {
152
				baseURL = "http://" + host + pathPrefix + "/authority/";
147
                baseURL = "http://" + host + pathPrefix + "/authority/";
153 148
            }
154 149
            logger.debug("HostDescriptor.baseURL: " + baseURL);
155
		}
156
	}
150
        }
151
    }
157 152
}
src/edu/ucsb/nceas/metacat/lsid/LSIDAuthorityData.java
34 34
import com.ibm.lsid.server.LSIDServerException;
35 35
import com.ibm.lsid.server.LSIDServiceConfig;
36 36

  
37
public class LSIDAuthorityData implements LSIDDataService {
37
public class LSIDAuthorityData implements LSIDDataService
38
{
39
    private LSIDDataLookup lookup = null;
40
    private static Log logger = LogFactory
41
                    .getLog("edu.ucsb.nceas.metacat.lsid");
38 42

  
39
	private LSIDDataLookup lookup = null;
40
    private static Log logger = LogFactory.getLog( "edu.ucsb.nceas.metacat.lsid" );
41
    
42
	public InputStream getData(LSIDRequestContext lsid) throws LSIDServerException {
43
    public InputStream getData(LSIDRequestContext lsid)
44
                    throws LSIDServerException
45
    {
43 46
        logger.debug("Getting data (Metacat): " + lsid.getLsid().toString());
44
		if (lookup == null)
45
			throw new LSIDServerException(500, "Cannot query database");
46
		return lookup.lsidData(lsid.getLsid());
47
	}
47
        if (lookup == null)
48
            throw new LSIDServerException(500, "Cannot query database");
49
        return lookup.lsidData(lsid.getLsid());
50
    }
48 51

  
49
	public InputStream getDataByRange(LSIDRequestContext lsid, int start, int end) throws LSIDServerException {
50
		if (lookup == null)
51
			throw new LSIDServerException(500, "Cannot query database");
52
		return lookup.lsidData(lsid.getLsid());
53
	}
52
    public InputStream getDataByRange(LSIDRequestContext lsid, int start,
53
                                      int end) throws LSIDServerException
54
    {
55
        if (lookup == null)
56
            throw new LSIDServerException(500, "Cannot query database");
57
        return lookup.lsidData(lsid.getLsid());
58
    }
54 59

  
55
	public void initService(LSIDServiceConfig cf) throws LSIDServerException {
60
    public void initService(LSIDServiceConfig cf) throws LSIDServerException
61
    {
56 62
        logger.info("Starting LSIDAuthorityData (Metacat).");
57
		lookup = new LSIDDataLookup();
58
	}
63
        lookup = new LSIDDataLookup();
64
    }
59 65
}

Also available in: Unified diff