Project

General

Profile

1
/**
2
 *  Copyright: 2013 Regents of the University of California and the
3
 *             National Center for Ecological Analysis and Synthesis
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 2 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 */
19
package edu.ucsb.nceas.metacat.index;
20

    
21
import java.io.ByteArrayInputStream;
22
import java.io.FileInputStream;
23
import java.io.FileNotFoundException;
24
import java.io.IOException;
25
import java.io.InputStream;
26
import java.net.MalformedURLException;
27
import java.util.ArrayList;
28
import java.util.Calendar;
29
import java.util.Date;
30
import java.util.HashMap;
31
import java.util.Iterator;
32
import java.util.List;
33
import java.util.Map;
34
import java.util.Set;
35

    
36
import javax.xml.parsers.DocumentBuilder;
37
import javax.xml.parsers.DocumentBuilderFactory;
38
import javax.xml.parsers.ParserConfigurationException;
39
import javax.xml.xpath.XPath;
40
import javax.xml.xpath.XPathExpressionException;
41
import javax.xml.xpath.XPathFactory;
42

    
43
import org.apache.commons.codec.EncoderException;
44
import org.apache.commons.io.output.ByteArrayOutputStream;
45
import org.apache.commons.lang.StringUtils;
46
import org.apache.commons.logging.Log;
47
import org.apache.commons.logging.LogFactory;
48
import org.apache.solr.client.solrj.SolrQuery;
49
import org.apache.solr.client.solrj.SolrServer;
50
import org.apache.solr.client.solrj.SolrServerException;
51
import org.apache.solr.client.solrj.response.QueryResponse;
52
import org.apache.solr.client.solrj.response.UpdateResponse;
53
import org.apache.solr.common.SolrDocument;
54
import org.apache.solr.common.SolrDocumentList;
55
import org.apache.solr.common.SolrInputDocument;
56
import org.apache.solr.schema.IndexSchema;
57
import org.dataone.cn.indexer.XMLNamespaceConfig;
58
import org.dataone.cn.indexer.convert.SolrDateConverter;
59
import org.dataone.cn.indexer.parser.IDocumentSubprocessor;
60
import org.dataone.cn.indexer.parser.SolrField;
61
import org.dataone.cn.indexer.resourcemap.ResourceEntry;
62
import org.dataone.cn.indexer.resourcemap.ResourceMap;
63
import org.dataone.cn.indexer.resourcemap.ResourceMapFactory;
64
import org.dataone.cn.indexer.solrhttp.SolrDoc;
65
import org.dataone.cn.indexer.solrhttp.SolrElementField;
66
import org.dataone.service.exceptions.NotFound;
67
import org.dataone.service.exceptions.NotImplemented;
68
import org.dataone.service.exceptions.ServiceFailure;
69
import org.dataone.service.exceptions.UnsupportedType;
70
import org.dataone.service.types.v1.Event;
71
import org.dataone.service.types.v1.Identifier;
72
import org.dataone.service.types.v1.SystemMetadata;
73
import org.dataone.service.util.DateTimeMarshaller;
74
import org.dataone.service.util.TypeMarshaller;
75
import org.dspace.foresite.OREParserException;
76
import org.jibx.runtime.JiBXException;
77
import org.w3c.dom.Document;
78
import org.xml.sax.SAXException;
79

    
80
import edu.ucsb.nceas.metacat.common.index.event.IndexEvent;
81
import edu.ucsb.nceas.metacat.common.query.SolrQueryServiceController;
82
import edu.ucsb.nceas.metacat.index.event.EventlogFactory;
83
import edu.ucsb.nceas.metacat.index.resourcemap.ResourceMapSubprocessor;
84

    
85
/**
86
 * A class does insert, update and remove indexes to a SOLR server
87
 * @author tao
88
 *
89
 */
90
public class SolrIndex {
91
            
92
    public static final String ID = "id";
93
    private static final String IDQUERY = ID+":*";
94
    private List<IDocumentSubprocessor> subprocessors = null;
95
    private SolrServer solrServer = null;
96
    private XMLNamespaceConfig xmlNamespaceConfig = null;
97
    private List<SolrField> sysmetaSolrFields = null;
98

    
99
    private static DocumentBuilderFactory documentBuilderFactory = null;
100
    private static DocumentBuilder builder = null;
101

    
102
    private static XPathFactory xpathFactory = null;
103
    private static XPath xpath = null;
104
    Log log = LogFactory.getLog(SolrIndex.class);
105
    
106
    static {
107
        documentBuilderFactory = DocumentBuilderFactory.newInstance();
108
        documentBuilderFactory.setNamespaceAware(true);
109
        try {
110
            builder = documentBuilderFactory.newDocumentBuilder();
111
        } catch (ParserConfigurationException e) {
112
            e.printStackTrace();
113
        }
114
        xpathFactory = XPathFactory.newInstance();
115
        xpath = xpathFactory.newXPath();
116
    }
117
    
118
    /**
119
     * Constructor
120
     * @throws SAXException 
121
     * @throws IOException 
122
     */
123
    public SolrIndex(XMLNamespaceConfig xmlNamespaceConfig, List<SolrField> sysmetaSolrFields)
124
                    throws XPathExpressionException, ParserConfigurationException, IOException, SAXException {
125
         this.xmlNamespaceConfig = xmlNamespaceConfig;
126
         this.sysmetaSolrFields = sysmetaSolrFields;
127
         init();
128
    }
129
    
130
    private void init() throws ParserConfigurationException, XPathExpressionException {
131
        xpath.setNamespaceContext(xmlNamespaceConfig);
132
        initExpressions();
133
    }
134

    
135
    private void initExpressions() throws XPathExpressionException {
136
        for (SolrField field : sysmetaSolrFields) {
137
            field.initExpression(xpath);
138
        }
139

    
140
    }
141
    
142
    
143
    /**
144
     * Get the list of the Subprocessors in this index.
145
     * @return the list of the Subprocessors.
146
     */
147
    public List<IDocumentSubprocessor> getSubprocessors() {
148
        return subprocessors;
149
    }
150

    
151
    /**
152
     * Set the list of Subprocessors.
153
     * @param subprocessorList  the list will be set.
154
     */
155
    public void setSubprocessors(List<IDocumentSubprocessor> subprocessorList) {
156
        for (IDocumentSubprocessor subprocessor : subprocessorList) {
157
            subprocessor.initExpression(xpath);
158
        }
159
        this.subprocessors = subprocessorList;
160
    }
161
    
162
    /**
163
     * Generate the index for the given information
164
     * @param id
165
     * @param systemMetadata
166
     * @param dataStream
167
     * @return
168
     * @throws IOException
169
     * @throws SAXException
170
     * @throws ParserConfigurationException
171
     * @throws XPathExpressionException
172
     * @throws JiBXException 
173
     * @throws SolrServerException 
174
     * @throws EncoderException
175
     * @throws UnsupportedType 
176
     * @throws NotFound 
177
     * @throws NotImplemented 
178
     */
179
    private Map<String, SolrDoc> process(String id, SystemMetadata systemMetadata, InputStream dataStream)
180
                    throws IOException, SAXException, ParserConfigurationException,
181
                    XPathExpressionException, JiBXException, EncoderException, SolrServerException, NotImplemented, NotFound, UnsupportedType{
182

    
183
        // Load the System Metadata document
184
        ByteArrayOutputStream systemMetadataOutputStream = new ByteArrayOutputStream();
185
        TypeMarshaller.marshalTypeToOutputStream(systemMetadata, systemMetadataOutputStream);
186
        ByteArrayInputStream systemMetadataStream = new ByteArrayInputStream(systemMetadataOutputStream.toByteArray());
187
        Document sysMetaDoc = generateXmlDocument(systemMetadataStream);
188
        if (sysMetaDoc == null) {
189
            log.error("Could not load System metadata for ID: " + id);
190
            return null;
191
        }
192

    
193
        // Extract the field values from the System Metadata
194
        List<SolrElementField> sysSolrFields = processSysmetaFields(sysMetaDoc, id);
195
        SolrDoc indexDocument = new SolrDoc(sysSolrFields);
196
        Map<String, SolrDoc> docs = new HashMap<String, SolrDoc>();
197
        docs.put(id, indexDocument);
198

    
199
        // Determine if subprocessors are available for this ID
200
        if (subprocessors != null) {
201
                    // for each subprocessor loaded from the spring config
202
                    for (IDocumentSubprocessor subprocessor : subprocessors) {
203
                        // Does this subprocessor apply?
204
                        if (subprocessor.canProcess(sysMetaDoc)) {
205
                            // if so, then extract the additional information from the
206
                            // document.
207
                            try {
208
                                // docObject = the resource map document or science
209
                                // metadata document.
210
                                // note that resource map processing touches all objects
211
                                // referenced by the resource map.
212
                                Document docObject = generateXmlDocument(dataStream);
213
                                if (docObject == null) {
214
                                    throw new Exception("Could not load OBJECT for ID " + id );
215
                                } else {
216
                                    docs = subprocessor.processDocument(id, docs, docObject);
217
                                }
218
                            } catch (Exception e) {
219
                                log.error(e.getStackTrace().toString());
220
                                throw new SolrServerException(e.getMessage());
221
                            }
222
                        }
223
                    }
224
       }
225

    
226
       // TODO: in the XPathDocumentParser class in d1_cn_index_process module,
227
       // merge is only for resource map. We need more work here.
228
       for (SolrDoc mergeDoc : docs.values()) {
229
           if (!mergeDoc.isMerged()) {
230
                 mergeWithIndexedDocument(mergeDoc);
231
           }
232
       }
233

    
234
       //SolrElementAdd addCommand = getAddCommand(new ArrayList<SolrDoc>(docs.values()));
235
               
236
       return docs;
237
    }
238
    
239
    /**
240
     * Merge updates with existing solr documents
241
     * 
242
     * This method appears to re-set the data package field data into the
243
     * document about to be updated in the solr index. Since packaging
244
     * information is derived from the package document (resource map), this
245
     * information is not present when processing a document contained in a data
246
     * package. This method replaces those values from the existing solr index
247
     * record for the document being processed. -- sroseboo, 1-18-12
248
     * 
249
     * @param indexDocument
250
     * @return
251
     * @throws IOException
252
     * @throws EncoderException
253
     * @throws XPathExpressionException
254
     * @throws SAXException 
255
     * @throws ParserConfigurationException 
256
     * @throws SolrServerException 
257
     * @throws UnsupportedType 
258
     * @throws NotFound 
259
     * @throws NotImplemented 
260
     */
261
    // TODO:combine merge function with resourcemap merge function
262

    
263
    private SolrDoc mergeWithIndexedDocument(SolrDoc indexDocument) throws IOException,
264
            EncoderException, XPathExpressionException, SolrServerException, ParserConfigurationException, SAXException, NotImplemented, NotFound, UnsupportedType {
265
        List<String> ids = new ArrayList<String>();
266
        ids.add(indexDocument.getIdentifier());
267
        List<SolrDoc> indexedDocuments = ResourceMapSubprocessor.getSolrDocs(ids);
268
        SolrDoc indexedDocument = indexedDocuments == null || indexedDocuments.size() <= 0 ? null
269
                : indexedDocuments.get(0);
270
        
271
        IndexSchema indexSchema = SolrQueryServiceController.getInstance().getSchema();
272

    
273
        if (indexedDocument == null || indexedDocument.getFieldList().size() <= 0) {
274
            return indexDocument;
275
        } else {
276
            for (SolrElementField field : indexedDocument.getFieldList()) {
277
                if ((field.getName().equals(SolrElementField.FIELD_ISDOCUMENTEDBY)
278
                        || field.getName().equals(SolrElementField.FIELD_DOCUMENTS) || field
279
                        .getName().equals(SolrElementField.FIELD_RESOURCEMAP))
280
                        && !indexDocument.hasFieldWithValue(field.getName(), field.getValue())) {
281
                    indexDocument.addField(field);
282
                } else if (!indexSchema.isCopyFieldTarget(indexSchema.getField(field.getName())) && !indexDocument.hasField(field.getName())) {
283
                    indexDocument.addField(field);
284
                }
285
            }
286

    
287
            indexDocument.setMerged(true);
288
            return indexDocument;
289
        }
290
    }
291
    
292
    /*
293
     * Generate a Document from the InputStream
294
     */
295
    private Document generateXmlDocument(InputStream smdStream) throws SAXException {
296
        Document doc = null;
297

    
298
        try {
299
            doc = builder.parse(smdStream);
300
        } catch (IOException e) {
301
            log.error(e.getMessage(), e);
302
        }
303

    
304
        return doc;
305
    }
306
    
307
    /*
308
     * Index the fields of the system metadata
309
     */
310
    private List<SolrElementField> processSysmetaFields(Document doc, String identifier) {
311

    
312
        List<SolrElementField> fieldList = new ArrayList<SolrElementField>();
313
        // solrFields is the list of fields defined in the application context
314
       
315
        for (SolrField field : sysmetaSolrFields) {
316
            try {
317
                // the field.getFields method can return a single value or
318
                // multiple values for multi-valued fields
319
                // or can return multiple SOLR document fields.
320
                fieldList.addAll(field.getFields(doc, identifier));
321
            } catch (Exception e) {
322
                e.printStackTrace();
323
            }
324
        }
325
        return fieldList;
326

    
327
    }
328
    
329
    /**
330
     * Check the parameters of the insert or update methods.
331
     * @param pid
332
     * @param systemMetadata
333
     * @param data
334
     * @throws SolrServerException
335
     */
336
    private void checkParams(Identifier pid, SystemMetadata systemMetadata, InputStream data) throws SolrServerException {
337
        if(pid == null || pid.getValue() == null || pid.getValue().trim().equals("")) {
338
            throw new SolrServerException("The identifier of the indexed document should not be null or blank.");
339
        }
340
        if(systemMetadata == null) {
341
            throw new SolrServerException("The system metadata of the indexed document "+pid.getValue()+ " should not be null.");
342
        }
343
        if(data == null) {
344
            throw new SolrServerException("The indexed document itself for pid "+pid.getValue()+" should not be null.");
345
        }
346
    }
347
    
348
    /**
349
     * Insert the indexes for a document.
350
     * @param pid  the id of this document
351
     * @param systemMetadata  the system metadata associated with the data object
352
     * @param data  the data object itself
353
     * @throws SolrServerException 
354
     * @throws JiBXException 
355
     * @throws EncoderException 
356
     * @throws UnsupportedType 
357
     * @throws NotFound 
358
     * @throws NotImplemented 
359
     */
360
    private synchronized void insert(Identifier pid, SystemMetadata systemMetadata, InputStream data) 
361
                    throws IOException, SAXException, ParserConfigurationException,
362
                    XPathExpressionException, SolrServerException, JiBXException, EncoderException, NotImplemented, NotFound, UnsupportedType {
363
        checkParams(pid, systemMetadata, data);
364
        Map<String, SolrDoc> docs = process(pid.getValue(), systemMetadata, data);
365
        
366
        //transform the Map to the SolrInputDocument which can be used by the solr server
367
        if(docs != null) {
368
            Set<String> ids = docs.keySet();
369
            for(String id : ids) {
370
                if(id != null) {
371
                    SolrDoc doc = docs.get(id);
372
                    insertToIndex(doc);
373
                }
374
                
375
            }
376
        }
377
    }
378
    
379
    /**
380
     * Adds the given fields to the solr index for the given pid, preserving the index values
381
     * that previously existed
382
     * @param pid
383
     * @param fields
384
     */
385
    public void insertFields(Identifier pid, Map<String, List<Object>> fields) {
386
    	
387
    	try {
388
			// copy the original values already indexed for this document	
389
	    	SolrQuery query = new SolrQuery("id:\"" + pid.getValue() + "\"");
390
	    	QueryResponse res = solrServer.query(query);
391
	    	SolrDocument orig = res.getResults().get(0);
392
	    	SolrDoc doc = new SolrDoc();
393
	        IndexSchema indexSchema = SolrQueryServiceController.getInstance().getSchema();
394
	    	for (String fieldName: orig.getFieldNames()) {
395
	        	//  don't transfer the copyTo fields, otherwise there are errors
396
	        	if (indexSchema.isCopyFieldTarget(indexSchema.getField(fieldName))) {
397
	        		continue;
398
	        	}
399
	        	for (Object value: orig.getFieldValues(fieldName)) {
400
	        		String stringValue = value.toString();
401
	        		// special handling for dates in ISO 8601
402
	        		if (value instanceof Date) {
403
	        			stringValue = DateTimeMarshaller.serializeDateToUTC((Date)value);
404
	        			SolrDateConverter converter = new SolrDateConverter();
405
	        			stringValue = converter.convert(stringValue);
406
	        		}
407
					SolrElementField field = new SolrElementField(fieldName, stringValue);
408
					log.debug("Adding field: " + fieldName);
409
					doc.addField(field);
410
	        	}
411
	        }
412
	    	
413
	        // add the additional fields we are trying to include in the index
414
	        for (String fieldName: fields.keySet()) {
415
	    		List<Object> values = fields.get(fieldName);
416
	    		for (Object value: values) {
417
	    	    	doc.updateOrAddField(fieldName, value.toString());
418
	    		}
419
	    	}
420
	        
421
	        // insert the whole thing
422
	        insertToIndex(doc);
423
    	} catch (Exception e) {
424
    		String error = "SolrIndex.insetFields - could not update the solr index: " + e.getMessage();
425
            writeEventLog(null, pid, error);
426
            log.error(error, e);
427
    	}
428

    
429
    }
430
    
431
    /*
432
     * Insert a SolrDoc to the solr server.
433
     */
434
    private synchronized void insertToIndex(SolrDoc doc) throws SolrServerException, IOException {
435
        if(doc != null ) {
436
            SolrInputDocument solrDoc = new SolrInputDocument();
437
            List<SolrElementField> list = doc.getFieldList();
438
            if(list != null) {
439
                //solrDoc.addField(METACATPIDFIELD, pid);
440
                Iterator<SolrElementField> iterator = list.iterator();
441
                while (iterator.hasNext()) {
442
                    SolrElementField field = iterator.next();
443
                    if(field != null) {
444
                        String value = field.getValue();
445
                        String name = field.getName();
446
                        //System.out.println("add name/value pair - "+name+"/"+value);
447
                        solrDoc.addField(name, value);
448
                    }
449
                }
450
            }
451
            if(!solrDoc.isEmpty()) {
452
                /*IndexEvent event = new IndexEvent();
453
                event.setDate(Calendar.getInstance().getTime());
454
                Identifier pid = new Identifier();
455
                pid.setValue(doc.getIdentifier());
456
                event.setIdentifier(pid);*/
457
                try {
458
                    UpdateResponse response = solrServer.add(solrDoc);
459
                    solrServer.commit();
460
                    /*event.setType(IndexEvent.SUCCESSINSERT);
461
                    event.setDescription("Successfully insert the solr index for the id "+pid.getValue());
462
                    try {
463
                        EventlogFactory.createIndexEventLog().write(event);
464
                    } catch (Exception e) {
465
                        log.error("SolrIndex.insertToIndex - IndexEventLog can't log the index inserting event :"+e.getMessage());
466
                    }*/
467
                } catch (SolrServerException e) {
468
                    /*event.setAction(Event.CREATE);
469
                    event.setDescription("Failed to insert the solr index for the id "+pid.getValue()+" since "+e.getMessage());
470
                    try {
471
                        EventlogFactory.createIndexEventLog().write(event);
472
                    } catch (Exception ee) {
473
                        log.error("SolrIndex.insertToIndex - IndexEventLog can't log the index inserting event :"+ee.getMessage());
474
                    }*/
475
                    throw e;
476
                } catch (IOException e) {
477
                    /*event.setAction(Event.CREATE);
478
                    event.setDescription("Failed to insert the solr index for the id "+pid.getValue()+" since "+e.getMessage());
479
                    try {
480
                        EventlogFactory.createIndexEventLog().write(event);
481
                    } catch (Exception ee) {
482
                        log.error("SolrIndex.insertToIndex - IndexEventLog can't log the index inserting event :"+ee.getMessage());
483
                    }*/
484
                    throw e;
485
                    
486
                }
487
                //System.out.println("=================the response is:\n"+response.toString());
488
            }
489
        }
490
    }
491
    
492
    /**
493
     * Update the solr index. This method handles the three scenarios:
494
     * 1. Remove an existing doc - if the the system metadata shows the value of the archive is true,
495
     *    remove the index for the previous version(s) and generate new index for the doc.
496
     * 2. Add a new doc - if the system metadata shows the value of the archive is false, generate the
497
     *    index for the doc.
498
     */
499
    public void update(Identifier pid, SystemMetadata systemMetadata) {
500
        String objectPath = null;
501
        InputStream data = null;
502
        try {
503
            objectPath = DistributedMapsFactory.getObjectPathMap().get(pid);
504
            data = new FileInputStream(objectPath);
505
            update(pid, systemMetadata, data);
506
            EventlogFactory.createIndexEventLog().remove(pid);
507
        } catch (Exception e) {
508
            String error = "SolrIndex.update - could not update the solr index since " + e.getMessage();
509
            writeEventLog(systemMetadata, pid, error);
510
            log.error(error, e);
511
        }
512
    }
513
    
514
    
515
    /**
516
     * Update the solr index. This method handles the three scenarios:
517
     * 1. Remove an existing doc - if the the system metadata shows the value of the archive is true,
518
     *    remove the index for the previous version(s) and generate new index for the doc.
519
     * 2. Add a new doc - if the system metadata shows the value of the archive is false, generate the
520
     *    index for the doc.
521
     * @param pid
522
     * @param systemMetadata
523
     * @param data
524
     * @throws SolrServerException
525
     * @throws ServiceFailure
526
     * @throws XPathExpressionException
527
     * @throws NotImplemented
528
     * @throws NotFound
529
     * @throws UnsupportedType
530
     * @throws IOException
531
     * @throws SAXException
532
     * @throws ParserConfigurationException
533
     * @throws OREParserException
534
     * @throws JiBXException
535
     * @throws EncoderException
536
     */
537
    void update(Identifier pid, SystemMetadata systemMetadata, InputStream data) throws SolrServerException, 
538
                                ServiceFailure, XPathExpressionException, NotImplemented, NotFound, UnsupportedType, 
539
                                IOException, SAXException, ParserConfigurationException, OREParserException, JiBXException, EncoderException {
540
        checkParams(pid, systemMetadata, data);
541
        boolean isArchive = systemMetadata.getArchived();
542
        if(isArchive ) {
543
            //delete the index for the archived objects
544
            remove(pid.getValue(), systemMetadata);
545
            log.info("SolrIndex.update============================= archive the idex for the identifier "+pid);
546
        } else {
547
            //generate index for either add or update.
548
            insert(pid, systemMetadata, data);
549
            log.info("SolrIndex.update============================= insert index for the identifier "+pid);
550
        }
551
    }
552
    
553
   
554

    
555
    /*
556
     * Is the pid a resource map
557
     */
558
    private boolean isDataPackage(String pid, SystemMetadata sysmeta) throws FileNotFoundException, ServiceFailure {
559
        boolean isDataPackage = false;
560
        //SystemMetadata sysmeta = DistributedMapsFactory.getSystemMetadata(pid);
561
        if(sysmeta != null) {
562
            isDataPackage = IndexGeneratorTimerTask.isResourceMap(sysmeta.getFormatId());
563
        }
564
        return isDataPackage;
565
    }
566

    
567
    private boolean isPartOfDataPackage(String pid) throws XPathExpressionException, NotImplemented, NotFound, UnsupportedType, SolrServerException, IOException, ParserConfigurationException, SAXException {
568
        SolrDoc dataPackageIndexDoc = ResourceMapSubprocessor.getSolrDoc(pid);
569
        if (dataPackageIndexDoc != null) {
570
            String resourceMapId = dataPackageIndexDoc
571
                    .getFirstFieldValue(SolrElementField.FIELD_RESOURCEMAP);
572
            return StringUtils.isNotEmpty(resourceMapId);
573
        } else {
574
            return false;
575
        }
576
    }
577
    /**
578
     * Remove the indexed associated with specified pid.
579
     * @param pid  the pid which the indexes are associated with
580
     * @throws IOException
581
     * @throws SolrServerException
582
     * @throws ParserConfigurationException 
583
     * @throws SAXException 
584
     * @throws UnsupportedType 
585
     * @throws NotFound 
586
     * @throws NotImplemented 
587
     * @throws XPathExpressionException 
588
     * @throws ServiceFailure 
589
     * @throws OREParserException 
590
     */
591
    private void remove(String pid, SystemMetadata sysmeta) throws IOException, SolrServerException, ServiceFailure, XPathExpressionException, NotImplemented, NotFound, UnsupportedType, SAXException, ParserConfigurationException, OREParserException {
592
        if (isDataPackage(pid, sysmeta)) {
593
            removeDataPackage(pid);
594
        } else if (isPartOfDataPackage(pid)) {
595
            removeFromDataPackage(pid);
596
        } else {
597
            removeFromIndex(pid);
598
        }
599
    }
600
    
601
    /*
602
     * Remove a resource map pid
603
     */
604
    private void removeDataPackage(String pid) throws ServiceFailure, SAXException, XPathExpressionException, NotImplemented, NotFound, UnsupportedType, SolrServerException, IOException, ParserConfigurationException, OREParserException  {
605
        Document resourceMapDoc = generateXmlDocument(DistributedMapsFactory.getDataObject(pid));
606
        //ResourceMap resourceMap = new ResourceMap(resourceMapDoc);
607
        ResourceMap resourceMap = ResourceMapFactory.buildResourceMap(resourceMapDoc);
608
        List<String> documentIds = resourceMap.getAllDocumentIDs();
609
        List<SolrDoc> indexDocuments =ResourceMapSubprocessor.getSolrDocs(documentIds);
610
        removeFromIndex(pid);
611
        //List<SolrDoc> docsToUpdate = new ArrayList<SolrDoc>();
612
        // for each document in data package:
613
        for (SolrDoc indexDoc : indexDocuments) {
614

    
615
            if (indexDoc.getIdentifier().equals(pid)) {
616
                continue; // skipping the resource map, no need update
617
                          // it.
618
                          // will
619
                          // be removed.
620
            }
621

    
622
            // Remove resourceMap reference
623
            indexDoc.removeFieldsWithValue(SolrElementField.FIELD_RESOURCEMAP,
624
                    resourceMap.getIdentifier());
625

    
626
            // // Remove documents/documentedby values for this resource
627
            // map
628
            for (ResourceEntry entry : resourceMap.getMappedReferences()) {
629
                if (indexDoc.getIdentifier().equals(entry.getIdentifier())) {
630
                    for (String documentedBy : entry.getDocumentedBy()) {
631
                        // Using removeOneFieldWithValue in-case same
632
                        // documents
633
                        // are in more than one data package. just
634
                        // remove
635
                        // one
636
                        // instance of data package info.
637
                        indexDoc.removeOneFieldWithValue(SolrElementField.FIELD_ISDOCUMENTEDBY,
638
                                documentedBy);
639
                    }
640
                    for (String documents : entry.getDocuments()) {
641
                        indexDoc.removeOneFieldWithValue(SolrElementField.FIELD_DOCUMENTS,
642
                                documents);
643
                    }
644
                    break;
645
                }
646
            }
647
            removeFromIndex(indexDoc.getIdentifier());
648
            insertToIndex(indexDoc);
649
            //docsToUpdate.add(indexDoc);
650
        }
651
        //SolrElementAdd addCommand = new SolrElementAdd(docsToUpdate);
652
        //httpService.sendUpdate(solrIndexUri, addCommand);
653
    }
654

    
655
    /*
656
     * Remove a pid which is part of resource map.
657
     */
658
    private void removeFromDataPackage(String pid) throws XPathExpressionException, NotImplemented, NotFound, UnsupportedType, SolrServerException, IOException, ParserConfigurationException, SAXException  {
659
        SolrDoc indexedDoc = ResourceMapSubprocessor.getSolrDoc(pid);
660
        removeFromIndex(pid);
661
        List<SolrDoc> docsToUpdate = new ArrayList<SolrDoc>();
662

    
663
        List<String> documents = indexedDoc.getAllFieldValues(SolrElementField.FIELD_DOCUMENTS);
664
        for (String documentsValue : documents) {
665
            SolrDoc solrDoc = ResourceMapSubprocessor.getSolrDoc(documentsValue);
666
            solrDoc.removeFieldsWithValue(SolrElementField.FIELD_ISDOCUMENTEDBY, pid);
667
            removeFromIndex(documentsValue);
668
            insertToIndex(solrDoc);
669
        }
670

    
671
        List<String> documentedBy = indexedDoc
672
                .getAllFieldValues(SolrElementField.FIELD_ISDOCUMENTEDBY);
673
        for (String documentedByValue : documentedBy) {
674
            SolrDoc solrDoc = ResourceMapSubprocessor.getSolrDoc(documentedByValue);
675
            solrDoc.removeFieldsWithValue(SolrElementField.FIELD_DOCUMENTS, pid);
676
            //docsToUpdate.add(solrDoc);
677
            removeFromIndex(documentedByValue);
678
            insertToIndex(solrDoc);
679
        }
680

    
681
        //SolrElementAdd addCommand = new SolrElementAdd(docsToUpdate);
682
        //httpService.sendUpdate(solrIndexUri, addCommand);
683
    }
684

    
685
    /*
686
     * Remove a pid from the solr index
687
     */
688
    private synchronized void removeFromIndex(String pid) throws SolrServerException, IOException {
689
        if(pid != null && !pid.trim().equals("")) {
690
            /*IndexEvent event = new IndexEvent();
691
            event.setDate(Calendar.getInstance().getTime());
692
            Identifier identifier = new Identifier();
693
            identifier.setValue(pid);
694
            event.setIdentifier(identifier);*/
695
            try {
696
                solrServer.deleteById(pid);
697
                solrServer.commit();
698
                /*event.setType(IndexEvent.SUCCESSDELETE);
699
                event.setDescription("Successfully remove the solr index for the id "+identifier.getValue());
700
                try {
701
                    EventlogFactory.createIndexEventLog().write(event);
702
                } catch (Exception e) {
703
                    log.error("SolrIndex.removeFromIndex - IndexEventLog can't log the index deleting event :"+e.getMessage());
704
                }*/
705
            } catch (SolrServerException e) {
706
                /*event.setAction(Event.DELETE);
707
                event.setDescription("Failurely remove the solr index for the id "+identifier.getValue()+" since "+e.getMessage());
708
                try {
709
                    EventlogFactory.createIndexEventLog().write(event);
710
                } catch (Exception ee) {
711
                    log.error("SolrIndex.removeFromIndex - IndexEventLog can't log the index deleting event :"+ee.getMessage());
712
                }*/
713
                throw e;
714
                
715
            } catch (IOException e) {
716
                /*event.setAction(Event.DELETE);
717
                event.setDescription("Failurely remove the solr index for the id "+identifier.getValue()+" since "+e.getMessage());
718
                try {
719
                    EventlogFactory.createIndexEventLog().write(event);
720
                } catch (Exception ee) {
721
                    log.error("SolrIndex.removeFromIndex - IndexEventLog can't log the index deleting event :"+ee.getMessage());
722
                }*/
723
                throw e;
724
            }
725
            
726
        }
727
    }
728

    
729
    /**
730
     * Get the solrServer
731
     * @return
732
     */
733
    public SolrServer getSolrServer() {
734
        return solrServer;
735
    }
736

    
737
    /**
738
     * Set the solrServer. 
739
     * @param solrServer
740
     */
741
    public void setSolrServer(SolrServer solrServer) {
742
        this.solrServer = solrServer;
743
    }
744
    
745
    /**
746
     * Get all indexed ids in the solr server. 
747
     * @return an empty list if there is no index.
748
     * @throws SolrServerException
749
     */
750
    public List<String> getSolrIds() throws SolrServerException {
751
        List<String> list = new ArrayList<String>();
752
        SolrQuery query = new SolrQuery(IDQUERY); 
753
        query.setRows(Integer.MAX_VALUE); 
754
        query.setFields(ID); 
755
        QueryResponse response = solrServer.query(query); 
756
        SolrDocumentList docs = response.getResults();
757
        if(docs != null) {
758
            for(SolrDocument doc :docs) {
759
                String identifier = (String)doc.getFieldValue(ID);
760
                //System.out.println("======================== "+identifier);
761
                list.add(identifier);
762
            }
763
        }
764
        return list;
765
    }
766
    
767
    private void writeEventLog(SystemMetadata systemMetadata, Identifier pid, String error) {
768
        IndexEvent event = new IndexEvent();
769
        event.setIdentifier(pid);
770
        event.setDate(Calendar.getInstance().getTime());
771
        String action = null;
772
        if (systemMetadata == null ) {
773
            action = Event.CREATE.xmlValue();
774
            event.setAction(Event.CREATE);
775
        }
776
        else if(systemMetadata.getArchived()) {
777
            action = Event.DELETE.xmlValue();
778
            event.setAction(Event.DELETE);
779
        } else {
780
            action = Event.CREATE.xmlValue();
781
            event.setAction(Event.CREATE);
782
        }
783
        event.setDescription("Failed to "+action+"the solr index for the id "+pid.getValue()+" since "+error);
784
        try {
785
            EventlogFactory.createIndexEventLog().write(event);
786
        } catch (Exception ee) {
787
            log.error("SolrIndex.insertToIndex - IndexEventLog can't log the index inserting event :"+ee.getMessage());
788
        }
789
    }
790
}
(5-5/6)