-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathMultiRemoteDSpaceRepositoryHandlePlugin.java
More file actions
749 lines (679 loc) · 22.3 KB
/
MultiRemoteDSpaceRepositoryHandlePlugin.java
File metadata and controls
749 lines (679 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.handle;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import net.handle.hdllib.Encoder;
import net.handle.hdllib.HandleException;
import net.handle.hdllib.HandleStorage;
import net.handle.hdllib.HandleValue;
import net.handle.hdllib.ScanCallback;
import net.handle.hdllib.Util;
import net.cnri.util.StreamTable;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
/**
* Extension to the CNRI Handle Server that translates requests to resolve
* handles into remote calls to the mini-DSpace Handle resolver JSON API. This
* only provides some of the functionality (namely, the resolving of handles to
* URLs) of the CNRI HandleStorage interface.
*
* <p>
* This class is intended to be embedded in the CNRI Handle Server. It conforms
* to the HandleStorage interface that was delivered with Handle Server version
* 9.3.0.
* </p>
*
* @author Andrea Bollini
*/
public class MultiRemoteDSpaceRepositoryHandlePlugin implements HandleStorage
{
/**
* Name of configuration file. This can be overwritten by setting a path
* to the configuration file to use in the system property
* <code>dspace.handle.plugin.configuration</code>.
*/
private static final String CONFIG_FILE_NAME = "handle-dspace-plugin.cfg";
/**
* Every Property starting with this key will be used as DSpace endpoint
* while resolving handles, f.e. http://localhost:8080/xmlui/handleresolver.
*/
private static final String PROPERTY_KEY = "dspace.handle.endpoint";
/** log4j category */
private static final Logger log = Logger
.getLogger(MultiRemoteDSpaceRepositoryHandlePlugin.class);
// maps prefixes to URLs from DSpace instances
private Map<String, String> prefixes;
/**
* Constructor
*/
public MultiRemoteDSpaceRepositoryHandlePlugin()
{
}
// //////////////////////////////////////
// Non-Resolving methods -- unimplemented
// //////////////////////////////////////
/**
* HandleStorage interface method - not implemented.
*/
@Override
public void init(StreamTable st) throws Exception
{
// Not implemented
if (log.isInfoEnabled())
{
log.info("Called init");
}
// initalize our prefix map
this.prefixes = new HashMap<>();
// try to find our configuration
Properties properties = loadProperties(CONFIG_FILE_NAME);
// find urls of all configured dspace instances
for (Enumeration e = properties.propertyNames(); e.hasMoreElements();)
{
String propertyName = (String) e.nextElement();
if (propertyName.startsWith(PROPERTY_KEY))
{
// load the prefixes of this instance
loadPrefixes(properties.getProperty(propertyName));
}
}
// did we found any prefixes?
if (this.prefixes.isEmpty())
{
throw new HandleException(HandleException.INTERNAL_ERROR,
"Unable to find configuration or to reach any DSpace instance.");
}
if (log.isInfoEnabled())
{
for (Iterator<String> it = this.prefixes.keySet().iterator(); it.hasNext() ;)
{
String prefix = it.next();
log.info("Loaded Prefix " + prefix + " from " + this.prefixes.get(prefix));
}
}
}
/**
* HandleStorage interface method - not implemented.
*/
@Override
public void setHaveNA(byte[] theHandle, boolean haveit)
throws HandleException
{
// Not implemented
if (log.isInfoEnabled())
{
log.info("Called setHaveNA (not implemented)");
}
}
/**
* HandleStorage interface method - not implemented.
*/
@Override
public void createHandle(byte[] theHandle, HandleValue[] values)
throws HandleException
{
// Not implemented
if (log.isInfoEnabled())
{
log.info("Called createHandle (not implemented)");
}
}
/**
* HandleStorage interface method - not implemented.
*/
@Override
public boolean deleteHandle(byte[] theHandle) throws HandleException
{
// Not implemented
if (log.isInfoEnabled())
{
log.info("Called deleteHandle (not implemented)");
}
return false;
}
/**
* HandleStorage interface method - not implemented.
*/
@Override
public void updateValue(byte[] theHandle, HandleValue[] values)
throws HandleException
{
// Not implemented
if (log.isInfoEnabled())
{
log.info("Called updateValue (not implemented)");
}
}
/**
* HandleStorage interface method - not implemented.
*/
@Override
public void deleteAllRecords() throws HandleException
{
// Not implemented
if (log.isInfoEnabled())
{
log.info("Called deleteAllRecords (not implemented)");
}
}
/**
* HandleStorage interface method - not implemented.
*/
@Override
public void checkpointDatabase() throws HandleException
{
// Not implemented
if (log.isInfoEnabled())
{
log.info("Called checkpointDatabase (not implemented)");
}
}
/**
* HandleStorage interface method - not implemented.
*/
@Override
public void shutdown()
{
// Not implemented
if (log.isInfoEnabled())
{
log.info("Called shutdown (not implemented)");
}
}
/**
* HandleStorage interface method - not implemented.
*/
@Override
public void scanHandles(ScanCallback callback) throws HandleException
{
// Not implemented
if (log.isInfoEnabled())
{
log.info("Called scanHandles (not implemented)");
}
}
/**
* HandleStorage interface method - not implemented.
*/
@Override
public void scanNAs(ScanCallback callback) throws HandleException
{
// Not implemented
if (log.isInfoEnabled())
{
log.info("Called scanNAs (not implemented)");
}
}
// //////////////////////////////////////
// Resolving methods
// //////////////////////////////////////
/**
* Return the raw values for this handle. This implementation returns a
* single URL value.
*
* @param theHandle
* byte array representation of handle
* @param indexList
* ignored
* @param typeList
* ignored
* @return A byte array with the raw data for this handle. Currently, this
* consists of a single URL value.
* @exception HandleException
* If an error occurs while calling the Handle API.
*/
@Override
public byte[][] getRawHandleValues(byte[] theHandle, int[] indexList,
byte[][] typeList) throws HandleException
{
if (log.isInfoEnabled())
{
log.info("Called getRawHandleValues");
}
if (theHandle == null)
{
throw new HandleException(HandleException.INTERNAL_ERROR);
}
String handle = Util.decodeString(theHandle);
String url = getRemoteDSpaceURL(handle);
HandleValue value = new HandleValue();
value.setIndex(100);
value.setType(Util.encodeString("URL"));
value.setData(Util.encodeString(url));
value.setTTLType((byte) 0);
value.setTTL(100);
value.setTimestamp(100);
value.setReferences(null);
value.setAdminCanRead(true);
value.setAdminCanWrite(false);
value.setAnyoneCanRead(true);
value.setAnyoneCanWrite(false);
List<HandleValue> values = new LinkedList<>();
values.add(value);
byte[][] rawValues = new byte[values.size()][];
for (int i = 0; i < values.size(); i++)
{
HandleValue hvalue = values.get(i);
rawValues[i] = new byte[Encoder.calcStorageSize(hvalue)];
Encoder.encodeHandleValue(rawValues[i], 0, hvalue);
}
return rawValues;
}
private String getRemoteDSpaceURL(String handle) throws HandleException
{
if (log.isInfoEnabled())
{
log.info("Called getRemoteDSpaceURL("+handle+").");
}
InputStreamReader jsonStreamReader = null;
String url = null;
try
{
String prefix = handle.split("/")[0];
String endpoint = this.prefixes.get(prefix);
if (endpoint == null)
{
if (log.isDebugEnabled())
{
log.debug("Cannot find endpoint for prefix " + prefix + ", throw HANDLE_DOES_NOT_EXIST.");
}
throw new HandleException(HandleException.HANDLE_DOES_NOT_EXIST);
}
String jsonurl = endpoint + "/resolve/" + handle;
jsonStreamReader = new InputStreamReader(
new URL(jsonurl).openStream(), "UTF-8");
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(jsonStreamReader);
if (jsonElement == null || jsonElement.isJsonNull()
|| jsonElement.getAsJsonArray().size() == 0
|| jsonElement.getAsJsonArray().get(0).isJsonNull())
{
if (log.isDebugEnabled())
{
log.debug("Throw HandleException: HANDLE_DOES_NOT_EXIST.");
}
throw new HandleException(HandleException.HANDLE_DOES_NOT_EXIST);
}
url = jsonElement.getAsJsonArray().get(0).getAsString();
}
catch (HandleException | IOException | JsonIOException | JsonSyntaxException e)
{
if (log.isDebugEnabled())
{
log.debug("Exception in getRawHandleValues", e);
}
// Stack loss as exception does not support cause
throw new HandleException(HandleException.INTERNAL_ERROR);
}
finally
{
if (jsonStreamReader != null)
{
try
{
jsonStreamReader.close();
}
catch (IOException e)
{
log.error(e.getMessage(), e);
}
}
}
if (log.isDebugEnabled())
{
log.debug(("getRemoteDspaceURL returns " + url));
}
return url;
}
/**
* Return true if we have this handle in storage.
*
* @param theHandle
* byte array representation of handle
* @return True if we have this handle in storage
* @exception HandleException
* If an error occurs while calling the Handle API.
*/
@Override
public boolean haveNA(byte[] theHandle) throws HandleException
{
if (log.isInfoEnabled())
{
log.info("Called haveNA");
}
/*
* Naming authority Handles are in the form: 0.NA/1721.1234
*
* 0.NA is basically the naming authority for naming authorities. For
* this simple implementation, we will just check if the requestes
* prefix is one that DSpace returns when we call
* handleresolver/listprefixes.
*/
// Which authority does the request pertain to? Remove the heading "0.NA/".
String received = Util.decodeString(theHandle).substring("0.NA/".length());
return this.prefixes.containsKey(received);
}
/**
* Return all handles in local storage which start with the naming authority
* handle.
*
* @param theNAHandle
* byte array representation of naming authority handle
* @return All handles in local storage which start with the naming
* authority handle.
* @exception HandleException
* If an error occurs while calling the Handle API.
*/
@Override
public Enumeration getHandlesForNA(byte[] theNAHandle)
throws HandleException
{
String naHandle = Util.decodeString(theNAHandle);
if (log.isInfoEnabled())
{
log.info("Called getHandlesForNA for NA " + naHandle);
}
List<String> handles = getRemoteDSpaceHandles(naHandle);
List<byte[]> results = new LinkedList<>();
for (String handle : handles)
{
// Transforms to byte array
results.add(Util.encodeString(handle));
}
return Collections.enumeration(results);
}
private List<String> getRemoteDSpaceHandles(String naHandle)
throws HandleException
{
List<String> handles = new ArrayList<>();
String endpoint = this.prefixes.get(naHandle);
if (null == endpoint)
{
// We don't know anything about this prefix, return an empty list.
return handles;
}
InputStreamReader jsonStreamReader = null;
try
{
String jsonurl = endpoint + "/listhandles/" + naHandle;
jsonStreamReader = new InputStreamReader(
new URL(jsonurl).openStream(), "UTF-8");
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(jsonStreamReader);
if (jsonElement != null && jsonElement.getAsJsonArray().size() != 0)
{
for (int i = 0; i < jsonElement.getAsJsonArray().size(); i++)
{
handles.add(jsonElement.getAsJsonArray().get(i)
.getAsString());
}
}
}
catch (IOException | JsonIOException | JsonSyntaxException e)
{
if (log.isDebugEnabled())
{
log.debug("Exception in getHandlesForNA", e);
}
// Stack loss as exception does not support cause
throw new HandleException(HandleException.INTERNAL_ERROR);
}
finally
{
if (jsonStreamReader != null)
{
try
{
jsonStreamReader.close();
}
catch (IOException e)
{
log.error(e.getMessage(), e);
}
}
}
return handles;
}
private Properties loadProperties(String filename) throws IOException
{
InputStream is = findConfigFile(filename);
Properties props = new Properties();
InputStreamReader ir = null;
// load the configuration
try {
ir = new InputStreamReader(is, "UTF-8");
props.load(ir);
} catch (UnsupportedEncodingException ex) {
if (log.isInfoEnabled())
{
log.info("Caught an UnsupportedEncodingException while loading configuration: " + ex.getMessage());
}
throw new RuntimeException(ex);
}
catch (IOException ex)
{
if (log.isInfoEnabled())
{
log.info("Caught an IOException while loading configuration: " + ex.getMessage());
}
throw ex;
}
finally
{
if (ir != null)
{
try
{
ir.close();
}
catch (IOException ex)
{
// nothing to do.
}
}
if (is != null)
{
try
{
is.close();
}
catch (IOException ex)
{
// nothing to do.
}
}
}
return props;
}
private InputStream findConfigFile(String filename)
{
InputStream is = null;
// try to load config file as defined in system property:
try
{
String configProperty = System.getProperty("dspace.handle.plugin.configuration");
if (null != configProperty)
{
is = new FileInputStream(configProperty);
}
}
catch (SecurityException se)
{
// A security manager may stop us from accessing the system properties.
// This isn't really a fatal error though, so catch and ignore
log.warn("Unable to access system properties, ignoring.", se);
}
catch (FileNotFoundException fne)
{
log.warn("Unable to find config file as defined by system property: "
+ fne.getMessage());
}
if (null == is)
{
// try some default locations
URL url = MultiRemoteDSpaceRepositoryHandlePlugin.class.getResource(
"/" + filename);
if (null == url)
{
if (log.isInfoEnabled())
{
log.info("Cannot find configuration by using getResource().");
}
} else {
try
{
is = new FileInputStream(url.getPath());
log.warn("Falling back to default locations, "
+ "found configuration at: " + url.getPath());
}
catch (FileNotFoundException e)
{
if (log.isInfoEnabled())
{
// didn't found fallback config, nothing to do about it.
log.info("Unable to open fallback configuration: " + e.getMessage());
}
}
}
}
if (null == is)
{
// try to find configuration in the current working directory
// where the user started the handle server.
try
{
is = new FileInputStream("./" + filename);
if (log.isInfoEnabled())
{
log.info("Loaded configuration from your current working "
+ "directory where you started the handle server.");
}
}
catch (FileNotFoundException ex)
{
if (log.isInfoEnabled())
{
log.info("Can't load config file: " + ex.getMessage());
}
}
}
if (is == null)
{
throw new IllegalStateException("Cannot find configuration.");
}
return is;
}
private void loadPrefixes(String endpoint)
{
URL url = null;
try {
url = new URL(endpoint + "/listprefixes");
} catch (MalformedURLException ex) {
log.error(endpoint + "is not a correct URL, will ignore this "
+ "DSpace instance.", ex);
}
String[] prefixes;
try {
InputStreamReader jsonStreamReader = new InputStreamReader(url.openStream(), "UTF-8");
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(jsonStreamReader);
if (jsonElement != null && jsonElement.getAsJsonArray().size() != 0)
{
for (int i = 0; i < jsonElement.getAsJsonArray().size(); i++)
{
String prefix = jsonElement.getAsJsonArray().get(i).getAsString();
this.prefixes.put(prefix, endpoint);
if (log.isInfoEnabled())
{
log.info("Mapping " + prefix + " to instance at " + endpoint);
}
}
} else {
log.warn("DSpace instance running at " + url + " returns empty prefix list.");
}
}
catch (IOException | JsonIOException | JsonSyntaxException ex)
{
log.warn("Error while loading prefixes from " + endpoint + ", ignoring.", ex);
}
}
public static void main(String[] args) throws Exception
{
MultiRemoteDSpaceRepositoryHandlePlugin multi = new MultiRemoteDSpaceRepositoryHandlePlugin();
try
{
System.out.println(StringUtils.join(
multi.getRemoteDSpaceHandles("123456789"), ","));
}
catch (HandleException e)
{
e.printStackTrace();
}
try
{
System.out.println(StringUtils.join(
multi.getRemoteDSpaceHandles("123456780"), ","));
}
catch (HandleException e)
{
e.printStackTrace();
}
try
{
System.out.println(multi.getRemoteDSpaceURL("123456789/1"));
}
catch (HandleException e)
{
e.printStackTrace();
}
try
{
System.out.println(multi.getRemoteDSpaceURL("123456789/1111111"));
}
catch (HandleException e)
{
e.printStackTrace();
}
try
{
System.out.println(multi.getRemoteDSpaceURL("123456780/1"));
}
catch (HandleException e)
{
e.printStackTrace();
}
try
{
System.out.println(multi.getRemoteDSpaceURL("123456780/1111111"));
}
catch (HandleException e)
{
e.printStackTrace();
}
}
}