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.IOException;
31
import java.io.InputStream;
32
import java.util.ArrayList;
33
import java.util.HashMap;
34
import java.util.Iterator;
35
import java.util.List;
36
import java.util.Map;
37
import java.util.Set;
38

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

    
46
import org.apache.commons.codec.EncoderException;
47
import org.apache.commons.io.output.ByteArrayOutputStream;
48
import org.apache.commons.logging.Log;
49
import org.apache.commons.logging.LogFactory;
50
import org.apache.solr.client.solrj.SolrServer;
51
import org.apache.solr.client.solrj.SolrServerException;
52
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
53
//import org.apache.solr.client.solrj.impl.HttpSolrServer;
54
import org.apache.solr.client.solrj.response.UpdateResponse;
55
import org.apache.solr.common.SolrInputDocument;
56
import org.apache.solr.core.CoreContainer;
57
import org.dataone.cn.indexer.XMLNamespaceConfig;
58
import org.dataone.cn.indexer.XPathDocumentParser;
59
import org.dataone.cn.indexer.parser.IDocumentSubprocessor;
60
import org.dataone.cn.indexer.parser.SolrField;
61
import org.dataone.cn.indexer.solrhttp.SolrDoc;
62
import org.dataone.cn.indexer.solrhttp.SolrElementAdd;
63
import org.dataone.cn.indexer.solrhttp.SolrElementField;
64
import org.dataone.configuration.Settings;
65
import org.dataone.service.types.v1.SystemMetadata;
66
import org.dataone.service.util.TypeMarshaller;
67
import org.jibx.runtime.JiBXException;
68
import org.w3c.dom.Document;
69
import org.xml.sax.SAXException;
70

    
71
/**
72
 * A class does insert, update and remove indexes to a SOLR server
73
 * @author tao
74
 *
75
 */
76
public class SolrIndex {
77
    
78
    
79
    
80
    public static final String SOLRHOME = "solr.solr.home";
81
    public static final String SOLRHOMEPROPERTYNAME = "solr.homeDir";
82
    
83
    private static final String SOLRINDEXWEBCONTEXT = "metacat-index";
84
    private static final String SOLRSERVERNAME = "metacat-core";
85
    //private static final String DEFAULTSOLRHOMEPATH = "/Users/tao/Downloads/apache-solr-3.4.0/example/solr";
86
    
87
    private List<IDocumentSubprocessor> subprocessors = null;
88
    private SolrServer solrServer = null;
89
    private XMLNamespaceConfig xmlNamespaceConfig = null;
90
    private List<SolrField> sysmetaSolrFields = null;
91

    
92
    private static DocumentBuilderFactory documentBuilderFactory = null;
93
    private static DocumentBuilder builder = null;
94

    
95
    private static XPathFactory xpathFactory = null;
96
    private static XPath xpath = null;
97
    Log log = LogFactory.getLog(SolrIndex.class);
98
    
99
    static {
100
        documentBuilderFactory = DocumentBuilderFactory.newInstance();
101
        documentBuilderFactory.setNamespaceAware(true);
102
        try {
103
            builder = documentBuilderFactory.newDocumentBuilder();
104
        } catch (ParserConfigurationException e) {
105
            e.printStackTrace();
106
        }
107
        xpathFactory = XPathFactory.newInstance();
108
        xpath = xpathFactory.newXPath();
109
    }
110
    
111
    /**
112
     * Constructor
113
     * @throws SAXException 
114
     * @throws IOException 
115
     */
116
    public SolrIndex(List<SolrField> sysmetaSolrFields, XMLNamespaceConfig xmlNamespaceConfig)
117
                    throws XPathExpressionException, ParserConfigurationException, IOException, SAXException {
118
         this.xmlNamespaceConfig = xmlNamespaceConfig;
119
         this.sysmetaSolrFields = sysmetaSolrFields;
120
         initSolrServer();
121
         init();
122
    }
123
    
124
    private void initSolrServer() throws IOException, ParserConfigurationException, SAXException {
125
        String solrHomeDir = null;
126
        solrHomeDir = Settings.getConfiguration().getString(SOLRHOMEPROPERTYNAME);
127
        log.info("========================= the solr home from the metacat.properties is "+solrHomeDir);
128
        if(solrHomeDir == null || solrHomeDir.trim().equals("")) {
129
            String deployDir = Settings.getConfiguration().getString("application.deployDir");
130
            if(deployDir == null || deployDir.trim().equals("")) {
131
                solrHomeDir =  SOLRINDEXWEBCONTEXT+"/WEB-INF/classes/solr-home";
132
            } else {
133
                solrHomeDir =  deployDir + "/" +SOLRINDEXWEBCONTEXT+"/WEB-INF/classes/solr-home";
134
            }
135
            
136
        }
137
        log.info("==========================================final solr home is "+solrHomeDir);
138
        System.setProperty(SOLRHOME, solrHomeDir);
139
        CoreContainer.Initializer init = new CoreContainer.Initializer();
140
        CoreContainer c = init.initialize();
141
        solrServer = new EmbeddedSolrServer(c, "collection1");
142
    }
143
    
144
    private void init() throws ParserConfigurationException, XPathExpressionException {
145
        xpath.setNamespaceContext(xmlNamespaceConfig);
146
        initExpressions();
147
    }
148

    
149
    private void initExpressions() throws XPathExpressionException {
150
        for (SolrField field : sysmetaSolrFields) {
151
            field.initExpression(xpath);
152
        }
153

    
154
    }
155
    
156
    
157
    /**
158
     * Get the list of the Subprocessors in this index.
159
     * @return the list of the Subprocessors.
160
     */
161
    public List<IDocumentSubprocessor> getSubprocessors() {
162
        return subprocessors;
163
    }
164

    
165
    /**
166
     * Set the list of Subprocessors.
167
     * @param subprocessorList  the list will be set.
168
     */
169
    public void setSubprocessors(List<IDocumentSubprocessor> subprocessorList) {
170
        for (IDocumentSubprocessor subprocessor : subprocessorList) {
171
            subprocessor.initExpression(xpath);
172
        }
173
        this.subprocessors = subprocessorList;
174
    }
175
    
176
    /**
177
     * Generate the index for the given information
178
     * @param id
179
     * @param systemMetadata
180
     * @param dataStream
181
     * @return
182
     * @throws IOException
183
     * @throws SAXException
184
     * @throws ParserConfigurationException
185
     * @throws XPathExpressionException
186
     * @throws JiBXException 
187
     * @throws EncoderException
188
     */
189
    private Map<String, SolrDoc> process(String id, SystemMetadata systemMetadata, InputStream dataStream)
190
                    throws IOException, SAXException, ParserConfigurationException,
191
                    XPathExpressionException, JiBXException{
192

    
193
        // Load the System Metadata document
194
        ByteArrayOutputStream systemMetadataOutputStream = new ByteArrayOutputStream();
195
        TypeMarshaller.marshalTypeToOutputStream(systemMetadata, systemMetadataOutputStream);
196
        ByteArrayInputStream systemMetadataStream = new ByteArrayInputStream(systemMetadataOutputStream.toByteArray());
197
        Document sysMetaDoc = generateXmlDocument(systemMetadataStream);
198
        if (sysMetaDoc == null) {
199
            log.error("Could not load System metadata for ID: " + id);
200
            return null;
201
        }
202

    
203
        // Extract the field values from the System Metadata
204
        List<SolrElementField> sysSolrFields = processSysmetaFields(sysMetaDoc, id);
205
        SolrDoc indexDocument = new SolrDoc(sysSolrFields);
206
        Map<String, SolrDoc> docs = new HashMap<String, SolrDoc>();
207
        docs.put(id, indexDocument);
208

    
209
        // Determine if subprocessors are available for this ID
210
        if (subprocessors != null) {
211
                    // for each subprocessor loaded from the spring config
212
                    for (IDocumentSubprocessor subprocessor : subprocessors) {
213
                        // Does this subprocessor apply?
214
                        if (subprocessor.canProcess(sysMetaDoc)) {
215
                            // if so, then extract the additional information from the
216
                            // document.
217
                            try {
218
                                // docObject = the resource map document or science
219
                                // metadata document.
220
                                // note that resource map processing touches all objects
221
                                // referenced by the resource map.
222
                                Document docObject = generateXmlDocument(dataStream);
223
                                if (docObject == null) {
224
                                    log.error("Could not load OBJECT for ID " + id );
225
                                } else {
226
                                    docs = subprocessor.processDocument(id, docs, docObject);
227
                                }
228
                            } catch (Exception e) {
229
                                log.error(e.getStackTrace().toString());
230
                            }
231
                        }
232
                    }
233
       }
234

    
235
       // TODO: in the XPathDocumentParser class in d1_cn_index_process module,
236
       // merge is only for resource map. We need more work here.
237
       for (SolrDoc mergeDoc : docs.values()) {
238
           if (!mergeDoc.isMerged()) {
239
                 //mergeWithIndexedDocument(mergeDoc);
240
           }
241
       }
242

    
243
       //SolrElementAdd addCommand = getAddCommand(new ArrayList<SolrDoc>(docs.values()));
244
               
245
       return docs;
246
    }
247
    
248
    /*
249
     * Generate a Document from the InputStream
250
     */
251
    private Document generateXmlDocument(InputStream smdStream) throws SAXException {
252
        Document doc = null;
253

    
254
        try {
255
            doc = builder.parse(smdStream);
256
        } catch (IOException e) {
257
            log.error(e.getMessage(), e);
258
        }
259

    
260
        return doc;
261
    }
262
    
263
    /*
264
     * Index the fields of the system metadata
265
     */
266
    private List<SolrElementField> processSysmetaFields(Document doc, String identifier) {
267

    
268
        List<SolrElementField> fieldList = new ArrayList<SolrElementField>();
269
        // solrFields is the list of fields defined in the application context
270
       
271
        for (SolrField field : sysmetaSolrFields) {
272
            try {
273
                // the field.getFields method can return a single value or
274
                // multiple values for multi-valued fields
275
                // or can return multiple SOLR document fields.
276
                fieldList.addAll(field.getFields(doc, identifier));
277
            } catch (Exception e) {
278
                e.printStackTrace();
279
            }
280
        }
281
        return fieldList;
282

    
283
    }
284
    
285
    /**
286
     * Generate indexes for a newly inserted document.
287
     * @param pid  the id of this document
288
     * @param systemMetadata  the system metadata associated with the data object
289
     * @param data  the data object itself
290
     * @throws SolrServerException 
291
     * @throws JiBXException 
292
     */
293
    public void insert(String pid, SystemMetadata systemMetadata, InputStream data) 
294
                    throws IOException, SAXException, ParserConfigurationException,
295
                    XPathExpressionException, SolrServerException, JiBXException {
296
        Map<String, SolrDoc> docs = process(pid, systemMetadata, data);
297
        
298
        //transform the Map to the SolrInputDocument which can be used by the solr server
299
        if(docs != null) {
300
            Set<String> ids = docs.keySet();
301
            for(String id : ids) {
302
                SolrInputDocument solrDoc = new SolrInputDocument();
303
                if(id != null) {
304
                    SolrDoc doc = docs.get(id);
305
                    if(doc != null) {
306
                        List<SolrElementField> list = doc.getFieldList();
307
                        if(list != null) {
308
                            //solrDoc.addField(METACATPIDFIELD, pid);
309
                            Iterator<SolrElementField> iterator = list.iterator();
310
                            while (iterator.hasNext()) {
311
                                SolrElementField field = iterator.next();
312
                                if(field != null) {
313
                                    String value = field.getValue();
314
                                    String name = field.getName();
315
                                    //System.out.println("add name/value pair - "+name+"/"+value);
316
                                    solrDoc.addField(name, value);
317
                                }
318
                            }
319
                        }
320
                    }
321
                }
322
                if(!solrDoc.isEmpty()) {
323
                    UpdateResponse response = solrServer.add(solrDoc);
324
                    solrServer.commit();
325
                    //System.out.println("=================the response is:\n"+response.toString());
326
                }
327
            }
328
        }
329
    }
330
 
331
    /**
332
     * Remove the indexed associated with specified pid.
333
     * @param pid  the pid which the indexes are associated with
334
     * @throws IOException
335
     * @throws SolrServerException
336
     */
337
    public void remove(String pid) throws IOException, SolrServerException {
338
        solrServer.deleteById(pid);
339
        solrServer.commit();
340
       
341
    }
342

    
343
    /**
344
     * Get the solrServer
345
     * @return
346
     */
347
    SolrServer getSolrServer() {
348
        return solrServer;
349
    }
350

    
351
    /**
352
     * Set the solrServer. This method is only for setting a test solr server in the junit test.
353
     * @param solrServer
354
     */
355
    void setSolrServer(SolrServer solrServer) {
356
        this.solrServer = solrServer;
357
    }
358
}
(3-3/4)