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

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