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

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

    
45
import org.apache.commons.codec.EncoderException;
46
import org.apache.commons.io.output.ByteArrayOutputStream;
47
import org.apache.commons.logging.Log;
48
import org.apache.commons.logging.LogFactory;
49
import org.apache.solr.client.solrj.SolrServer;
50
import org.apache.solr.client.solrj.SolrServerException;
51
import org.apache.solr.client.solrj.impl.HttpSolrServer;
52
import org.apache.solr.client.solrj.response.UpdateResponse;
53
import org.apache.solr.common.SolrInputDocument;
54
import org.dataone.cn.indexer.XMLNamespaceConfig;
55
import org.dataone.cn.indexer.XPathDocumentParser;
56
import org.dataone.cn.indexer.parser.IDocumentSubprocessor;
57
import org.dataone.cn.indexer.parser.SolrField;
58
import org.dataone.cn.indexer.solrhttp.SolrDoc;
59
import org.dataone.cn.indexer.solrhttp.SolrElementAdd;
60
import org.dataone.cn.indexer.solrhttp.SolrElementField;
61
import org.w3c.dom.Document;
62
import org.xml.sax.SAXException;
63

    
64
/**
65
 * A class does insert, update and remove indexes to a SOLR server
66
 * @author tao
67
 *
68
 */
69
public class SolrIndex {
70
    
71
    //private static final String INPUT_ENCODING = "UTF-8";
72
    public static final String METACATPIDFIELD = "id";
73
    private List<IDocumentSubprocessor> subprocessors = null;
74
    private SolrServer solrServer = null;
75
    private XMLNamespaceConfig xmlNamespaceConfig = null;
76
    private List<SolrField> sysmetaSolrFields = null;
77

    
78
    private static DocumentBuilderFactory documentBuilderFactory = null;
79
    private static DocumentBuilder builder = null;
80

    
81
    private static XPathFactory xpathFactory = null;
82
    private static XPath xpath = null;
83
    Log log = LogFactory.getLog(SolrIndex.class);
84
    
85
    static {
86
        documentBuilderFactory = DocumentBuilderFactory.newInstance();
87
        documentBuilderFactory.setNamespaceAware(true);
88
        try {
89
            builder = documentBuilderFactory.newDocumentBuilder();
90
        } catch (ParserConfigurationException e) {
91
            e.printStackTrace();
92
        }
93
        xpathFactory = XPathFactory.newInstance();
94
        xpath = xpathFactory.newXPath();
95
    }
96
    
97
    /**
98
     * Constructor
99
     */
100
    public SolrIndex(List<SolrField> sysmetaSolrFields, XMLNamespaceConfig xmlNamespaceConfig)
101
                    throws XPathExpressionException, ParserConfigurationException {
102
                this.xmlNamespaceConfig = xmlNamespaceConfig;
103
                this.sysmetaSolrFields = sysmetaSolrFields;
104
                solrServer = new HttpSolrServer("http://localhost:8080/solr/");
105
                init();
106
    }
107
    
108
    private void init() throws ParserConfigurationException, XPathExpressionException {
109
        xpath.setNamespaceContext(xmlNamespaceConfig);
110
        initExpressions();
111
    }
112

    
113
    private void initExpressions() throws XPathExpressionException {
114
        for (SolrField field : sysmetaSolrFields) {
115
            field.initExpression(xpath);
116
        }
117

    
118
    }
119
    
120
    
121
    /**
122
     * Get the list of the Subprocessors in this index.
123
     * @return the list of the Subprocessors.
124
     */
125
    public List<IDocumentSubprocessor> getSubprocessors() {
126
        return subprocessors;
127
    }
128

    
129
    /**
130
     * Set the list of Subprocessors.
131
     * @param subprocessorList  the list will be set.
132
     */
133
    public void setSubprocessors(List<IDocumentSubprocessor> subprocessorList) {
134
        for (IDocumentSubprocessor subprocessor : subprocessorList) {
135
            subprocessor.initExpression(xpath);
136
        }
137
        this.subprocessors = subprocessorList;
138
    }
139
    
140
    /**
141
     * Generate the index for the given information
142
     * @param id
143
     * @param systemMetaDataStream
144
     * @param dataStream
145
     * @return
146
     * @throws IOException
147
     * @throws SAXException
148
     * @throws ParserConfigurationException
149
     * @throws XPathExpressionException
150
     * @throws EncoderException
151
     */
152
    private Map<String, SolrDoc> process(String id, InputStream systemMetaDataStream, InputStream dataStream)
153
                    throws IOException, SAXException, ParserConfigurationException,
154
                    XPathExpressionException{
155

    
156
        // Load the System Metadata document
157
        Document sysMetaDoc = generateXmlDocument(systemMetaDataStream);
158
        if (sysMetaDoc == null) {
159
            log.error("Could not load System metadata for ID: " + id);
160
            return null;
161
        }
162

    
163
        // Extract the field values from the System Metadata
164
        List<SolrElementField> sysSolrFields = processSysmetaFields(sysMetaDoc, id);
165
        SolrDoc indexDocument = new SolrDoc(sysSolrFields);
166
        Map<String, SolrDoc> docs = new HashMap<String, SolrDoc>();
167
        docs.put(id, indexDocument);
168

    
169
        // Determine if subprocessors are available for this ID
170
        if (subprocessors != null) {
171
                    // for each subprocessor loaded from the spring config
172
                    for (IDocumentSubprocessor subprocessor : subprocessors) {
173
                        // Does this subprocessor apply?
174
                        if (subprocessor.canProcess(sysMetaDoc)) {
175
                            // if so, then extract the additional information from the
176
                            // document.
177
                            try {
178
                                // docObject = the resource map document or science
179
                                // metadata document.
180
                                // note that resource map processing touches all objects
181
                                // referenced by the resource map.
182
                                Document docObject = generateXmlDocument(dataStream);
183
                                if (docObject == null) {
184
                                    log.error("Could not load OBJECT for ID " + id );
185
                                } else {
186
                                    docs = subprocessor.processDocument(id, docs, docObject);
187
                                }
188
                            } catch (Exception e) {
189
                                log.error(e.getStackTrace().toString());
190
                            }
191
                        }
192
                    }
193
       }
194

    
195
       // TODO: in the XPathDocumentParser class in d1_cn_index_process module,
196
       // merge is only for resource map. We need more work here.
197
       for (SolrDoc mergeDoc : docs.values()) {
198
           if (!mergeDoc.isMerged()) {
199
                 //mergeWithIndexedDocument(mergeDoc);
200
           }
201
       }
202

    
203
       //SolrElementAdd addCommand = getAddCommand(new ArrayList<SolrDoc>(docs.values()));
204
               
205
       return docs;
206
    }
207
    
208
    /*
209
     * Generate a Document from the InputStream
210
     */
211
    private Document generateXmlDocument(InputStream smdStream) throws SAXException {
212
        Document doc = null;
213

    
214
        try {
215
            doc = builder.parse(smdStream);
216
        } catch (IOException e) {
217
            log.error(e.getMessage(), e);
218
        }
219

    
220
        return doc;
221
    }
222
    
223
    /*
224
     * Index the fields of the system metadata
225
     */
226
    private List<SolrElementField> processSysmetaFields(Document doc, String identifier) {
227

    
228
        List<SolrElementField> fieldList = new ArrayList<SolrElementField>();
229
        // solrFields is the list of fields defined in the application context
230
       
231
        for (SolrField field : sysmetaSolrFields) {
232
            try {
233
                // the field.getFields method can return a single value or
234
                // multiple values for multi-valued fields
235
                // or can return multiple SOLR document fields.
236
                fieldList.addAll(field.getFields(doc, identifier));
237
            } catch (Exception e) {
238
                e.printStackTrace();
239
            }
240
        }
241
        return fieldList;
242

    
243
    }
244
    
245
    /**
246
     * Generate indexes for a newly inserted document.
247
     * @param pid  the id of this document
248
     * @param systemMetadata  the system metadata associated with the data object
249
     * @param data  the data object itself
250
     * @throws SolrServerException 
251
     */
252
    public void insert(String pid, InputStream systemMetadata, InputStream data) 
253
                    throws IOException, SAXException, ParserConfigurationException,
254
                    XPathExpressionException, SolrServerException {
255
        Map<String, SolrDoc> docs = process(pid, systemMetadata, data);
256
        
257
        //transform the Map to the SolrInputDocument which can be used by the solr server
258
        if(docs != null) {
259
            Set<String> ids = docs.keySet();
260
            for(String id : ids) {
261
                SolrInputDocument solrDoc = new SolrInputDocument();
262
                if(id != null) {
263
                    SolrDoc doc = docs.get(id);
264
                    if(doc != null) {
265
                        List<SolrElementField> list = doc.getFieldList();
266
                        if(list != null) {
267
                            //solrDoc.addField(METACATPIDFIELD, pid);
268
                            Iterator<SolrElementField> iterator = list.iterator();
269
                            while (iterator.hasNext()) {
270
                                SolrElementField field = iterator.next();
271
                                if(field != null) {
272
                                    String value = field.getValue();
273
                                    String name = field.getName();
274
                                    //System.out.println("add name/value pair - "+name+"/"+value);
275
                                    solrDoc.addField(name, value);
276
                                }
277
                            }
278
                        }
279
                    }
280
                }
281
                if(!solrDoc.isEmpty()) {
282
                    UpdateResponse response = solrServer.add(solrDoc);
283
                    solrServer.commit();
284
                    //System.out.println("=================the response is:\n"+response.toString());
285
                }
286
            }
287
        }
288
    }
289
 
290
    /**
291
     * Remove the indexed associated with specified pid.
292
     * @param pid  the pid which the indexes are associated with
293
     * @throws IOException
294
     * @throws SolrServerException
295
     */
296
    public void remove(String pid) throws IOException, SolrServerException {
297
        solrServer.deleteByQuery(METACATPIDFIELD + ":" + pid);
298
       
299
    }
300
}
(2-2/3)