Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A class that gets Accession Number, check for uniqueness
4
 *             and register it into db
5
 *  Copyright: 2000 Regents of the University of California and the
6
 *             National Center for Ecological Analysis and Synthesis
7
 *    Authors: Jivka Bojilova, Matt Jones
8
 *
9
 *   '$Author: leinfelder $'
10
 *     '$Date: 2011-11-02 20:40:12 -0700 (Wed, 02 Nov 2011) $'
11
 * '$Revision: 6595 $'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27
package edu.ucsb.nceas.metacat.index;
28

    
29
import java.io.ByteArrayInputStream;
30
import java.io.FileNotFoundException;
31
import java.io.IOException;
32
import java.io.InputStream;
33
import java.util.ArrayList;
34
import java.util.Calendar;
35
import java.util.HashMap;
36
import java.util.Iterator;
37
import java.util.List;
38
import java.util.Map;
39
import java.util.Set;
40

    
41
import javax.xml.parsers.DocumentBuilder;
42
import javax.xml.parsers.DocumentBuilderFactory;
43
import javax.xml.parsers.ParserConfigurationException;
44
import javax.xml.xpath.XPath;
45
import javax.xml.xpath.XPathExpressionException;
46
import javax.xml.xpath.XPathFactory;
47

    
48
import org.apache.commons.codec.EncoderException;
49
import org.apache.commons.io.output.ByteArrayOutputStream;
50
import org.apache.commons.lang.StringUtils;
51
import org.apache.commons.logging.Log;
52
import org.apache.commons.logging.LogFactory;
53
import org.apache.solr.client.solrj.SolrQuery;
54
import org.apache.solr.client.solrj.SolrServer;
55
import org.apache.solr.client.solrj.SolrServerException;
56
import org.apache.solr.client.solrj.response.QueryResponse;
57
import org.apache.solr.client.solrj.response.UpdateResponse;
58
import org.apache.solr.common.SolrDocument;
59
import org.apache.solr.common.SolrDocumentList;
60
import org.apache.solr.common.SolrInputDocument;
61
import org.dataone.cn.indexer.XMLNamespaceConfig;
62
import org.dataone.cn.indexer.parser.IDocumentSubprocessor;
63
import org.dataone.cn.indexer.parser.SolrField;
64
import org.dataone.cn.indexer.resourcemap.ResourceEntry;
65
import org.dataone.cn.indexer.resourcemap.ResourceMap;
66
import org.dataone.cn.indexer.solrhttp.SolrDoc;
67
import org.dataone.cn.indexer.solrhttp.SolrElementField;
68
import org.dataone.service.exceptions.NotFound;
69
import org.dataone.service.exceptions.NotImplemented;
70
import org.dataone.service.exceptions.ServiceFailure;
71
import org.dataone.service.exceptions.UnsupportedType;
72
import org.dataone.service.types.v1.Event;
73
import org.dataone.service.types.v1.Identifier;
74
import org.dataone.service.types.v1.SystemMetadata;
75
import org.dataone.service.util.TypeMarshaller;
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.index.event.EventlogFactory;
82
import edu.ucsb.nceas.metacat.index.resourcemap.ResourceMapSubprocessor;
83

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

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

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

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

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

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

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

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

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

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

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

    
262
    private SolrDoc mergeWithIndexedDocument(SolrDoc indexDocument) throws IOException,
263
            EncoderException, XPathExpressionException, SolrServerException, ParserConfigurationException, SAXException, NotImplemented, NotFound, UnsupportedType {
264
        List<String> ids = new ArrayList<String>();
265
        ids.add(indexDocument.getIdentifier());
266
        List<SolrDoc> indexedDocuments = ResourceMapSubprocessor.getSolrDocs(ids);
267
        SolrDoc indexedDocument = indexedDocuments == null || indexedDocuments.size() <= 0 ? null
268
                : indexedDocuments.get(0);
269
        if (indexedDocument == null || indexedDocument.getFieldList().size() <= 0) {
270
            return indexDocument;
271
        } else {
272
            for (SolrElementField field : indexedDocument.getFieldList()) {
273
                if ((field.getName().equals(SolrElementField.FIELD_ISDOCUMENTEDBY)
274
                        || field.getName().equals(SolrElementField.FIELD_DOCUMENTS) || field
275
                        .getName().equals(SolrElementField.FIELD_RESOURCEMAP))
276
                        && !indexDocument.hasFieldWithValue(field.getName(), field.getValue())) {
277
                    indexDocument.addField(field);
278
                }
279
            }
280

    
281
            indexDocument.setMerged(true);
282
            return indexDocument;
283
        }
284
    }
285
    
286
    /*
287
     * Generate a Document from the InputStream
288
     */
289
    private Document generateXmlDocument(InputStream smdStream) throws SAXException {
290
        Document doc = null;
291

    
292
        try {
293
            doc = builder.parse(smdStream);
294
        } catch (IOException e) {
295
            log.error(e.getMessage(), e);
296
        }
297

    
298
        return doc;
299
    }
300
    
301
    /*
302
     * Index the fields of the system metadata
303
     */
304
    private List<SolrElementField> processSysmetaFields(Document doc, String identifier) {
305

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

    
321
    }
322
    
323
    /**
324
     * Check the parameters of the insert or update methods.
325
     * @param pid
326
     * @param systemMetadata
327
     * @param data
328
     * @throws SolrServerException
329
     */
330
    private void checkParams(String pid, SystemMetadata systemMetadata, InputStream data) throws SolrServerException {
331
        if(pid == null || pid.trim().equals("")) {
332
            throw new SolrServerException("The identifier of the indexed document should not be null or blank.");
333
        }
334
        if(systemMetadata == null) {
335
            throw new SolrServerException("The system metadata of the indexed document should not be null.");
336
        }
337
        if(data == null) {
338
            throw new SolrServerException("The indexed document itself should not be null.");
339
        }
340
    }
341
    
342
    /**
343
     * Insert the indexes for a document.
344
     * @param pid  the id of this document
345
     * @param systemMetadata  the system metadata associated with the data object
346
     * @param data  the data object itself
347
     * @throws SolrServerException 
348
     * @throws JiBXException 
349
     * @throws EncoderException 
350
     * @throws UnsupportedType 
351
     * @throws NotFound 
352
     * @throws NotImplemented 
353
     */
354
    private synchronized void insert(String pid, SystemMetadata systemMetadata, InputStream data) 
355
                    throws IOException, SAXException, ParserConfigurationException,
356
                    XPathExpressionException, SolrServerException, JiBXException, EncoderException, NotImplemented, NotFound, UnsupportedType {
357
        checkParams(pid, systemMetadata, data);
358
        Map<String, SolrDoc> docs = process(pid, systemMetadata, data);
359
        
360
        //transform the Map to the SolrInputDocument which can be used by the solr server
361
        if(docs != null) {
362
            Set<String> ids = docs.keySet();
363
            for(String id : ids) {
364
                if(id != null) {
365
                    SolrDoc doc = docs.get(id);
366
                    insertToIndex(doc);
367
                }
368
                
369
            }
370
        }
371
    }
372
    
373
    /*
374
     * Insert a SolrDoc to the solr server.
375
     */
376
    private synchronized void insertToIndex(SolrDoc doc) throws SolrServerException, IOException {
377
        if(doc != null ) {
378
            SolrInputDocument solrDoc = new SolrInputDocument();
379
            List<SolrElementField> list = doc.getFieldList();
380
            if(list != null) {
381
                //solrDoc.addField(METACATPIDFIELD, pid);
382
                Iterator<SolrElementField> iterator = list.iterator();
383
                while (iterator.hasNext()) {
384
                    SolrElementField field = iterator.next();
385
                    if(field != null) {
386
                        String value = field.getValue();
387
                        String name = field.getName();
388
                        //System.out.println("add name/value pair - "+name+"/"+value);
389
                        solrDoc.addField(name, value);
390
                    }
391
                }
392
            }
393
            if(!solrDoc.isEmpty()) {
394
                /*IndexEvent event = new IndexEvent();
395
                event.setDate(Calendar.getInstance().getTime());
396
                Identifier pid = new Identifier();
397
                pid.setValue(doc.getIdentifier());
398
                event.setIdentifier(pid);*/
399
                try {
400
                    UpdateResponse response = solrServer.add(solrDoc);
401
                    solrServer.commit();
402
                    /*event.setType(IndexEvent.SUCCESSINSERT);
403
                    event.setDescription("Successfully insert the solr index for the id "+pid.getValue());
404
                    try {
405
                        EventlogFactory.createIndexEventLog().write(event);
406
                    } catch (Exception e) {
407
                        log.error("SolrIndex.insertToIndex - IndexEventLog can't log the index inserting event :"+e.getMessage());
408
                    }*/
409
                } catch (SolrServerException e) {
410
                    /*event.setAction(Event.CREATE);
411
                    event.setDescription("Failed to insert the solr index for the id "+pid.getValue()+" since "+e.getMessage());
412
                    try {
413
                        EventlogFactory.createIndexEventLog().write(event);
414
                    } catch (Exception ee) {
415
                        log.error("SolrIndex.insertToIndex - IndexEventLog can't log the index inserting event :"+ee.getMessage());
416
                    }*/
417
                    throw e;
418
                } catch (IOException e) {
419
                    /*event.setAction(Event.CREATE);
420
                    event.setDescription("Failed to insert the solr index for the id "+pid.getValue()+" since "+e.getMessage());
421
                    try {
422
                        EventlogFactory.createIndexEventLog().write(event);
423
                    } catch (Exception ee) {
424
                        log.error("SolrIndex.insertToIndex - IndexEventLog can't log the index inserting event :"+ee.getMessage());
425
                    }*/
426
                    throw e;
427
                    
428
                }
429
                //System.out.println("=================the response is:\n"+response.toString());
430
            }
431
        }
432
    }
433
    
434
    /**
435
     * Update the solr index. This method handles the three scenarios:
436
     * 1. Archive (or delete) - if the the system metadata shows the value of the archive is true,
437
     *    remove the index for the document and its previous versions if it has.
438
     * 2. Update an existing doc - if the the system metadata shows the value of the archive is false and it has an obsoletes,
439
     *    remove the index for the previous version(s) and generate new index for the doc.
440
     * 3. Add a new doc - if the system metadata shows the value of the archive is false and it hasn't an obsoletes, generate the
441
     *    index for the doc.
442
     * @param pid  the id of the document
443
     * @param obsoleteIds  the chain of the obsoletes by this id
444
     * @param systemMetadata  the system metadata associated with the data object
445
     * @param data  the data object itself
446
     * @throws SolrServerException 
447
     * @throws JiBXException 
448
     * @throws EncoderException 
449
     * @throws UnsupportedType 
450
     * @throws NotFound 
451
     * @throws NotImplemented 
452
     * @throws ServiceFailure 
453
     */
454
    public void update(String pid, List<String> obsoleteIds, SystemMetadata systemMetadata, InputStream data) 
455
                    throws IOException, SAXException, ParserConfigurationException,
456
                    XPathExpressionException, SolrServerException, JiBXException, EncoderException, NotImplemented, NotFound, UnsupportedType, ServiceFailure {
457
        checkParams(pid, systemMetadata, data);
458
        boolean isArchive = systemMetadata.getArchived();
459
        if(isArchive) {
460
            //archive(delete)
461
            Identifier obsolete = systemMetadata.getObsoletes();
462
            if(obsolete != null) {
463
                removeObsoletesChain(obsolete.getValue(), obsoleteIds);
464
            }
465
            remove(pid);
466
            log.info("============================= archive the idex for the identifier "+pid);
467
        } else {
468
            Identifier obsolete = systemMetadata.getObsoletes();
469
            if(obsolete != null) {
470
                removeObsoletesChain(obsolete.getValue(), obsoleteIds);
471
            }
472
            //generate index for either add or update.
473
            insert(pid, systemMetadata, data);
474
            log.info("============================= insert index for the identifier "+pid);
475
        }
476
    }
477
    
478
    
479
    private void removeObsoletesChain(String obsoleteId, List<String> obsoleteIdChain) throws SolrServerException, IOException, ServiceFailure, XPathExpressionException, NotImplemented, NotFound, UnsupportedType, SAXException, ParserConfigurationException {
480
        if(obsoleteId != null && !obsoleteId.trim().equals("")) {
481
            if(obsoleteIdChain == null || obsoleteIdChain.isEmpty()) {
482
                throw new SolrServerException("SolrIndex.removeObsoletesChain - The obsoletes chain can't be null or empty since the system metadata already has the obsoletes element."); 
483
            }
484
            if(!obsoleteIdChain.contains(obsoleteId)) {
485
                throw new SolrServerException("SolrIndex.removeObsoletesChain - The obsoletes elment in the system metadata is not in the obsoleteId chain"); 
486
            }
487
            remove(obsoleteIdChain);
488
        } else {
489
            throw new SolrServerException("SolrIndex.removeObsoletesChain - The obsolete id should be null."); 
490
        }  
491
    }
492
    
493
    /**
494
     * Remove all the indexes associated with the pids in the list.
495
     * @param pidList
496
     * @throws IOException
497
     * @throws SolrServerException
498
     * @throws ParserConfigurationException 
499
     * @throws SAXException 
500
     * @throws UnsupportedType 
501
     * @throws NotFound 
502
     * @throws NotImplemented 
503
     * @throws XPathExpressionException 
504
     * @throws ServiceFailure 
505
     */
506
    private void remove(List<String> pidList) throws IOException, SolrServerException, ServiceFailure, XPathExpressionException, NotImplemented, NotFound, UnsupportedType, SAXException, ParserConfigurationException {
507
        if(pidList != null) {
508
            for(String id : pidList) {
509
                remove(id);
510
            }
511
        }
512
    }
513
 
514
    /**
515
     * Remove the indexed associated with specified pid.
516
     * @param pid  the pid which the indexes are associated with
517
     * @throws IOException
518
     * @throws SolrServerException
519
     * @throws ParserConfigurationException 
520
     * @throws SAXException 
521
     * @throws UnsupportedType 
522
     * @throws NotFound 
523
     * @throws NotImplemented 
524
     * @throws XPathExpressionException 
525
     * @throws ServiceFailure 
526
     */
527
    public void remove(String pid) throws IOException, SolrServerException, ServiceFailure, XPathExpressionException, NotImplemented, NotFound, UnsupportedType, SAXException, ParserConfigurationException {
528
        if (isDataPackage(pid)) {
529
            removeDataPackage(pid);
530
        } else if (isPartOfDataPackage(pid)) {
531
            removeFromDataPackage(pid);
532
        } else {
533
            removeFromIndex(pid);
534
        }
535
    }
536
    
537
   
538
   
539

    
540
    /*
541
     * Remove a resource map pid
542
     */
543
    private void removeDataPackage(String pid) throws ServiceFailure, SAXException, XPathExpressionException, NotImplemented, NotFound, UnsupportedType, SolrServerException, IOException, ParserConfigurationException  {
544
        Document resourceMapDoc = generateXmlDocument(DistributedMapsFactory.getDataObject(pid));
545
        ResourceMap resourceMap = new ResourceMap(resourceMapDoc);
546
        List<String> documentIds = resourceMap.getAllDocumentIDs();
547
        List<SolrDoc> indexDocuments =ResourceMapSubprocessor.getSolrDocs(documentIds);
548
        removeFromIndex(pid);
549
        //List<SolrDoc> docsToUpdate = new ArrayList<SolrDoc>();
550
        // for each document in data package:
551
        for (SolrDoc indexDoc : indexDocuments) {
552

    
553
            if (indexDoc.getIdentifier().equals(pid)) {
554
                continue; // skipping the resource map, no need update
555
                          // it.
556
                          // will
557
                          // be removed.
558
            }
559

    
560
            // Remove resourceMap reference
561
            indexDoc.removeFieldsWithValue(SolrElementField.FIELD_RESOURCEMAP,
562
                    resourceMap.getIdentifier());
563

    
564
            // // Remove documents/documentedby values for this resource
565
            // map
566
            for (ResourceEntry entry : resourceMap.getMappedReferences()) {
567
                if (indexDoc.getIdentifier().equals(entry.getIdentifier())) {
568
                    for (String documentedBy : entry.getDocumentedBy()) {
569
                        // Using removeOneFieldWithValue in-case same
570
                        // documents
571
                        // are in more than one data package. just
572
                        // remove
573
                        // one
574
                        // instance of data package info.
575
                        indexDoc.removeOneFieldWithValue(SolrElementField.FIELD_ISDOCUMENTEDBY,
576
                                documentedBy);
577
                    }
578
                    for (String documents : entry.getDocuments()) {
579
                        indexDoc.removeOneFieldWithValue(SolrElementField.FIELD_DOCUMENTS,
580
                                documents);
581
                    }
582
                    break;
583
                }
584
            }
585
            removeFromIndex(indexDoc.getIdentifier());
586
            insertToIndex(indexDoc);
587
            //docsToUpdate.add(indexDoc);
588
        }
589
        //SolrElementAdd addCommand = new SolrElementAdd(docsToUpdate);
590
        //httpService.sendUpdate(solrIndexUri, addCommand);
591
    }
592

    
593
    private void removeFromDataPackage(String pid) throws XPathExpressionException, NotImplemented, NotFound, UnsupportedType, SolrServerException, IOException, ParserConfigurationException, SAXException  {
594
        SolrDoc indexedDoc = ResourceMapSubprocessor.getSolrDoc(pid);
595
        removeFromIndex(pid);
596
        List<SolrDoc> docsToUpdate = new ArrayList<SolrDoc>();
597

    
598
        List<String> documents = indexedDoc.getAllFieldValues(SolrElementField.FIELD_DOCUMENTS);
599
        for (String documentsValue : documents) {
600
            SolrDoc solrDoc = ResourceMapSubprocessor.getSolrDoc(documentsValue);
601
            solrDoc.removeFieldsWithValue(SolrElementField.FIELD_ISDOCUMENTEDBY, pid);
602
            removeFromIndex(documentsValue);
603
            insertToIndex(solrDoc);
604
        }
605

    
606
        List<String> documentedBy = indexedDoc
607
                .getAllFieldValues(SolrElementField.FIELD_ISDOCUMENTEDBY);
608
        for (String documentedByValue : documentedBy) {
609
            SolrDoc solrDoc = ResourceMapSubprocessor.getSolrDoc(documentedByValue);
610
            solrDoc.removeFieldsWithValue(SolrElementField.FIELD_DOCUMENTS, documentedByValue);
611
            //docsToUpdate.add(solrDoc);
612
            removeFromIndex(documentedByValue);
613
            insertToIndex(solrDoc);
614
        }
615

    
616
        //SolrElementAdd addCommand = new SolrElementAdd(docsToUpdate);
617
        //httpService.sendUpdate(solrIndexUri, addCommand);
618
    }
619

    
620
    /*
621
     * Remove a pid from the solr index
622
     */
623
    private void removeFromIndex(String pid) throws SolrServerException, IOException {
624
        if(pid != null && !pid.trim().equals("")) {
625
            /*IndexEvent event = new IndexEvent();
626
            event.setDate(Calendar.getInstance().getTime());
627
            Identifier identifier = new Identifier();
628
            identifier.setValue(pid);
629
            event.setIdentifier(identifier);*/
630
            try {
631
                solrServer.deleteById(pid);
632
                solrServer.commit();
633
                /*event.setType(IndexEvent.SUCCESSDELETE);
634
                event.setDescription("Successfully remove the solr index for the id "+identifier.getValue());
635
                try {
636
                    EventlogFactory.createIndexEventLog().write(event);
637
                } catch (Exception e) {
638
                    log.error("SolrIndex.removeFromIndex - IndexEventLog can't log the index deleting event :"+e.getMessage());
639
                }*/
640
            } catch (SolrServerException e) {
641
                /*event.setAction(Event.DELETE);
642
                event.setDescription("Failurely remove the solr index for the id "+identifier.getValue()+" since "+e.getMessage());
643
                try {
644
                    EventlogFactory.createIndexEventLog().write(event);
645
                } catch (Exception ee) {
646
                    log.error("SolrIndex.removeFromIndex - IndexEventLog can't log the index deleting event :"+ee.getMessage());
647
                }*/
648
                throw e;
649
                
650
            } catch (IOException e) {
651
                /*event.setAction(Event.DELETE);
652
                event.setDescription("Failurely remove the solr index for the id "+identifier.getValue()+" since "+e.getMessage());
653
                try {
654
                    EventlogFactory.createIndexEventLog().write(event);
655
                } catch (Exception ee) {
656
                    log.error("SolrIndex.removeFromIndex - IndexEventLog can't log the index deleting event :"+ee.getMessage());
657
                }*/
658
                throw e;
659
            }
660
            
661
        }
662
    }
663

    
664
    /*
665
     * Is the pid a resource map
666
     */
667
    private boolean isDataPackage(String pid) throws FileNotFoundException, ServiceFailure {
668
        boolean isDataPackage = false;
669
        SystemMetadata sysmeta = DistributedMapsFactory.getSystemMetadata(pid);
670
        if(sysmeta != null) {
671
            isDataPackage = IndexGenerator.isResourceMap(sysmeta.getFormatId());
672
        }
673
        return isDataPackage;
674
    }
675

    
676
    private boolean isPartOfDataPackage(String pid) throws XPathExpressionException, NotImplemented, NotFound, UnsupportedType, SolrServerException, IOException, ParserConfigurationException, SAXException {
677
        SolrDoc dataPackageIndexDoc = ResourceMapSubprocessor.getSolrDoc(pid);
678
        if (dataPackageIndexDoc != null) {
679
            String resourceMapId = dataPackageIndexDoc
680
                    .getFirstFieldValue(SolrElementField.FIELD_RESOURCEMAP);
681
            return StringUtils.isNotEmpty(resourceMapId);
682
        } else {
683
            return false;
684
        }
685
    }
686

    
687
    /**
688
     * Get the solrServer
689
     * @return
690
     */
691
    public SolrServer getSolrServer() {
692
        return solrServer;
693
    }
694

    
695
    /**
696
     * Set the solrServer. 
697
     * @param solrServer
698
     */
699
    public void setSolrServer(SolrServer solrServer) {
700
        this.solrServer = solrServer;
701
    }
702
    
703
    /**
704
     * Get all indexed ids in the solr server. 
705
     * @return an empty list if there is no index.
706
     * @throws SolrServerException
707
     */
708
    public List<String> getSolrIds() throws SolrServerException {
709
        List<String> list = new ArrayList<String>();
710
        SolrQuery query = new SolrQuery(IDQUERY); 
711
        query.setRows(Integer.MAX_VALUE); 
712
        query.setFields(ID); 
713
        QueryResponse response = solrServer.query(query); 
714
        SolrDocumentList docs = response.getResults();
715
        if(docs != null) {
716
            for(SolrDocument doc :docs) {
717
                String identifier = (String)doc.getFieldValue(ID);
718
                //System.out.println("======================== "+identifier);
719
                list.add(identifier);
720
            }
721
        }
722
        return list;
723
    }
724
}
(5-5/6)