source: vlo/trunk/vlo_webapp/src/main/java/eu/clarin/cmdi/vlo/importer/MetadataImporter.java @ 988

Last change on this file since 988 was 988, checked in by patdui, 13 years ago
  • using Xpath to generate solrDocs
  • Added fileName to facets
  • Changed importerConfig to support caseInsensitive parameter
File size: 6.9 KB
Line 
1package eu.clarin.cmdi.vlo.importer;
2
3import java.io.File;
4import java.io.IOException;
5import java.net.MalformedURLException;
6import java.util.ArrayList;
7import java.util.HashSet;
8import java.util.List;
9import java.util.Set;
10
11import javax.xml.xpath.XPathExpressionException;
12
13import org.apache.solr.client.solrj.SolrServerException;
14import org.apache.solr.client.solrj.impl.StreamingUpdateSolrServer;
15import org.apache.solr.common.SolrInputDocument;
16import org.slf4j.Logger;
17import org.slf4j.LoggerFactory;
18import org.springframework.beans.factory.BeanFactory;
19import org.springframework.context.support.ClassPathXmlApplicationContext;
20import org.xml.sax.SAXException;
21
22import eu.clarin.cmdi.vlo.Configuration;
23import eu.clarin.cmdi.vlo.dao.FacetConstants;
24
25@SuppressWarnings("serial")
26public final class MetadataImporter {
27
28    private final static Logger LOG = LoggerFactory.getLogger(MetadataImporter.class);
29    private static Throwable serverError;
30    private final StreamingUpdateSolrServer solrServer;
31
32    private Set<String> processedIds = new HashSet<String>();
33    private List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
34    private final ImporterConfig config;
35
36    private int nrOFDocumentsUpdated;
37    private int nrOfNonExistendResourceFiles = 0;
38    private int nrOfFilesAnalyzed = 0;
39    private int nrOfFilesWithoutId = 0;
40
41    public MetadataImporter(ImporterConfig config) throws MalformedURLException {
42        this.config = config;
43        String solrUrl = Configuration.getInstance().getSolrUrl();
44        LOG.info("Initializing Solr Server on " + solrUrl);
45        solrServer = new StreamingUpdateSolrServer(solrUrl, 1000, 2) {
46            @Override
47            public void handleError(Throwable ex) {
48                super.handleError(ex);
49                serverError = ex;
50            }
51        };
52    }
53
54    //TODO PD can have multiple origins
55    private void startImport() {
56        List<DataRoot> dataRoots = config.getDataRoots();
57        for (DataRoot dataRoot : dataRoots) {
58            if (!dataRoot.getRootFile().exists()) {
59                LOG.error("Root file " + dataRoot.getRootFile() + " does not exist. Probable configuration error so stopping import.");
60                System.exit(1);
61            }
62        }
63
64        long start = System.currentTimeMillis();
65        try {
66            if (config.isDeleteFirst()) {
67                LOG.info("Deleting original data...");
68                solrServer.deleteByQuery("*:*");//Delete the whole solr db.
69                LOG.info("Deleting original data done.");
70            }
71            for (DataRoot dataRoot : dataRoots) {
72                LOG.info("Start of processing: "+dataRoot.getOriginName());
73                CMDIDigester digester = new CMDIDigester(dataRoot.getFacetMapping());
74                processCmdi(dataRoot.getRootFile(), dataRoot.getOriginName(), digester);
75                if (!docs.isEmpty()) {
76                    sendDocs();
77                }
78                LOG.info("End of processing: "+dataRoot.getOriginName());
79            }
80        } catch (SolrServerException e) {
81            LOG.error("error updating files:\n", e);
82            LOG.error("Also see vlo_solr server logs for more information");
83        } catch (IOException e) {
84            LOG.error("error updating files:\n", e);
85        } finally {
86            try {
87                solrServer.commit();
88            } catch (SolrServerException e) {
89                LOG.error("cannot commit:\n", e);
90            } catch (IOException e) {
91                LOG.error("cannot commit:\n", e);
92            }
93        }
94        long took = (System.currentTimeMillis() - start) / 1000;
95        LOG.info("Found " + nrOfNonExistendResourceFiles + " non existing resources files.");
96        LOG.info("Found " + nrOfFilesWithoutId + " file(s) without an id.");
97        LOG.info("Update of " + nrOFDocumentsUpdated + " took " + took + " secs. Total nr of files analyzed " + nrOfFilesAnalyzed);
98    }
99
100    private void processCmdi(File file, String origin, CMDIDigester digester) throws SolrServerException, IOException {
101        nrOfFilesAnalyzed++;
102        CMDIData cmdiData = null;
103        try {
104            cmdiData = digester.process(file);
105        } catch (IOException e) {
106            LOG.error("error in file: " + file + " Exception", e);
107        } catch (SAXException e) {
108            LOG.error("error in file: " + file + " Exception", e);
109        } catch (XPathExpressionException e) {
110            LOG.error("error in file: " + file + " Exception", e);
111        }
112        if (cmdiData != null && processedIds.add(cmdiData.getId())) {
113            SolrInputDocument solrDocument = cmdiData.getSolrDocument();
114            if (solrDocument != null) {
115                updateDocument(solrDocument, cmdiData, file, origin);
116            }
117            List<String> resources = cmdiData.getResources();
118            for (String cmdiResource : resources) {
119                File resourceFile = new File(file.getParentFile(), cmdiResource);
120                if (resourceFile.exists()) {
121                    processCmdi(resourceFile, origin, digester);
122                } else {
123                    nrOfNonExistendResourceFiles++;
124                    LOG.error("Found nonexistent resource file (" + cmdiResource + ") in cmdi: " + file);
125                }
126
127            }
128        }
129    }
130
131    private void updateDocument(SolrInputDocument solrDocument, CMDIData cmdiData, File file, String origin) throws SolrServerException,
132            IOException {
133        if (cmdiData.getId() == null || cmdiData.getId().isEmpty()) {
134            nrOfFilesWithoutId++;
135            LOG.info("Ignoring document without id, fileName: " + file);
136        } else {
137            solrDocument.addField(FacetConstants.FIELD_ORIGIN, origin);
138            solrDocument.addField(FacetConstants.FIELD_ID, cmdiData.getId());
139            solrDocument.addField(FacetConstants.FIELD_FILENAME, file.toString());
140            docs.add(solrDocument);
141            if (docs.size() == 1000) {
142                sendDocs();
143            }
144        }
145    }
146
147    private void sendDocs() throws SolrServerException, IOException {
148        LOG.info("Sending "+docs.size()+" docs to solr server. Total number of docs updated till now: "+nrOFDocumentsUpdated);
149        nrOFDocumentsUpdated += docs.size();
150        solrServer.add(docs);
151        if (serverError != null) {
152            throw new SolrServerException(serverError);
153        }
154        docs = new ArrayList<SolrInputDocument>();
155    }
156
157    /**
158     * @param args
159     * @throws MalformedURLException
160     */
161    public static void main(String[] args) throws MalformedURLException {
162        BeanFactory factory = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml", "importerConfig.xml" });
163        factory.getBean("configuration");
164        ImporterConfig config = (ImporterConfig) factory.getBean("importerConfig", ImporterConfig.class);
165        MetadataImporter importer = new MetadataImporter(config);
166        importer.startImport();
167    }
168
169}
Note: See TracBrowser for help on using the repository browser.