Project

General

Profile

« Previous | Next » 

Revision 28334

removed java folder

View differences:

modules/cnr-index-solr-common/branches/2.0.0/src/main/java/eu/dnetlib/functionality/index/solr/utils/MetadataReferenceFactory.java
1
package eu.dnetlib.functionality.index.solr.utils;
2

  
3
import org.springframework.beans.factory.annotation.Required;
4

  
5
public class MetadataReferenceFactory {
6

  
7
	/**
8
	 * Default interpretation, to be used for the lookup method which doesn't have an interpretation parameter.
9
	 */
10
	private String interpretation;
11

  
12
	public MetadataReference getMetadata(final String format, final String layout, final String interpretation) {
13
		return new MetadataReference(format, layout, interpretation);
14
	}
15
	
16
	public MetadataReference getMetadata(final String format, final String layout) {
17
		return getMetadata(format, layout, interpretation);
18
	}
19
	
20
	public MetadataReference decodeMetadata(final String encoded) {
21
		String[] split = encoded.split("-");
22
		if (split.length == 3) 
23
			return getMetadata(split[0], split[1], split[2]);
24
		
25
		if (split.length == 2) 
26
			return getMetadata(split[0], split[1]);
27
		
28
		throw new IllegalStateException("malformed metadata reference: " + encoded);
29
	}
30
	
31
	@Required
32
	public void setInterpretation(String interpretation) {
33
		this.interpretation = interpretation;
34
	}
35

  
36
	public String getInterpretation() {
37
		return interpretation;
38
	}
39
	
40
}
modules/cnr-index-solr-common/branches/2.0.0/src/main/java/eu/dnetlib/functionality/index/solr/utils/HighlightUtils.java
1
package eu.dnetlib.functionality.index.solr.utils;
2

  
3
import org.apache.oro.text.perl.Perl5Util;
4

  
5
import eu.dnetlib.miscutils.functional.UnaryFunction;
6

  
7
/**
8
 * This function removes extra highlight tags from the given document, 
9
 * according to the CLEAN_REGEX regular expression
10
 * 
11
 * @param document
12
 * 			the document 
13
 * @return
14
 * 			cleaned document
15
 * 
16
 * @author claudio
17
 *
18
 */
19
public class HighlightUtils implements UnaryFunction<String, String> {
20
	
21
	public final static String DEFAULT_HL_PRE  = "[hl]";
22
	
23
	public final static String DEFAULT_HL_POST = "[/hl]";
24

  
25
	private static String CLEAN_HEADER = "s#\\[/?hl\\]##gm"; 
26
	private static String CLEAN_REGEX_OPEN = "<([^>]*)\\[hl\\]([^>]*)>";
27
	private static String CLEAN_REGEX_CLOSE = "<([^>]*)\\[\\/hl\\]([^>]*)>";
28
	
29
//	private static String CLEAN_REGEX_OPEN = "s#<([^>]*)\\[hl\\]([^>]*)>#<$1$2>#gm";
30
//	private static String CLEAN_REGEX_CLOSE = "s#<([^>]*)\\[\\/hl\\]([^>]*)>#<$1$2>#gm";	
31
	
32
	private Perl5Util p5util = new Perl5Util();
33
	
34
	@Override
35
	public String evaluate(String doc) {
36
		String[] chunk = doc.split("</header>");
37
		String string = cleanHeader(chunk[0]) + "</header>" + cleanBody(chunk[1]);
38
		return  string;
39
	}
40
	
41
	private String cleanHeader(String header) {
42
		return p5util.substitute(CLEAN_HEADER, header);
43
	}
44
	
45
	//TODO: implement a faster way to do this
46
	private String cleanBody(String body) {
47
		String res = body.replaceAll(CLEAN_REGEX_OPEN, "<$1$2>").replaceAll(CLEAN_REGEX_CLOSE, "<$1$2>");
48

  
49
		if (res.equals(body))
50
			return res;
51
		
52
		return cleanBody(res);
53
	}	
54
	
55
}
modules/cnr-index-solr-common/branches/2.0.0/src/main/java/eu/dnetlib/functionality/index/solr/utils/IndexField.java
1
package eu.dnetlib.functionality.index.solr.utils;
2

  
3
/**
4
 * IndexMap keeps track of IndexDataStructure-to-physical index mappings and vice-versa.
5
 * 
6
 * @author claudio
7
 * 
8
 */
9
public class IndexField {
10

  
11
	public static final String INDEX_FIELD_PREFIX = "__";
12

  
13
	public static final String INDEX_DSID_ALL = "ALL";
14

  
15
	public static final String SCORE_FIELD = "score";
16

  
17
	public static final String DS_ID = INDEX_FIELD_PREFIX + "dsid";
18

  
19
	public static final String DS_VERSION = INDEX_FIELD_PREFIX + "dsversion";
20

  
21
	public static final String RESULT = INDEX_FIELD_PREFIX + "result";
22

  
23
	public static final String ALL_FIELDS = INDEX_FIELD_PREFIX + "all";
24

  
25
	public static final String DELETE_DOCUMENT = INDEX_FIELD_PREFIX + "deleted";
26

  
27
	public static final String INDEX_RECORD_ID = INDEX_FIELD_PREFIX + "indexrecordidentifier";
28

  
29
	public static final String FULLTEXT_ID = INDEX_FIELD_PREFIX + "fulltext";
30

  
31
	public static final String INDEXNAME_PARAM = INDEX_FIELD_PREFIX + "indexName";
32

  
33
	public static final String queryAll = "*:*";
34

  
35
	public static final String FIELD_NAME = "name";
36

  
37
	public static final String FIELD_BROWSING_ALIAS_FOR = "browsingAliasFor";
38

  
39
	public static final String XPATH_BROWSING_ALIAS_FOR = "//FIELD[@" + FIELD_BROWSING_ALIAS_FOR + "]";
40

  
41
}
modules/cnr-index-solr-common/branches/2.0.0/src/main/java/eu/dnetlib/functionality/index/solr/utils/MetadataReference.java
1
package eu.dnetlib.functionality.index.solr.utils;
2

  
3
import com.google.common.collect.ComparisonChain;
4

  
5
/**
6
 * Container class for metadata format, layout and interpretation.
7
 * 
8
 * @author claudio
9
 *
10
 */
11
public class MetadataReference {
12
	
13
	/**
14
	 * Metadata format.
15
	 */
16
	private String format;
17

  
18
	/**
19
	 * Metadata layout.
20
	 */
21
	private String layout;
22
	
23
	/**
24
	 * Metadata interpretation.
25
	 */
26
	private String interpretation;
27
	
28
	/**
29
	 * Constructor for MetadataReference.
30
	 * 
31
	 * @param format
32
	 * 			Metadata format
33
	 * @param layout
34
	 * 			Metadata layout
35
	 * @param interpretation
36
	 * 			Metadata interpretation
37
	 */
38
	public MetadataReference(final String format, final String layout, final String interpretation) {
39
		this.format = format;
40
		this.layout = layout;
41
		this.interpretation = interpretation;
42
	}
43
	
44
	public String getFormat() {
45
		return format;
46
	}
47

  
48
	public String getLayout() {
49
		return layout;
50
	}
51

  
52
	public String getInterpretation() {
53
		return interpretation;
54
	}
55

  
56
	@Override
57
	public boolean equals(final Object that) {
58
		
59
		if (!(that instanceof MetadataReference))
60
			return false;
61
		
62
		final MetadataReference mdRef = (MetadataReference) that;
63
		
64
		return ComparisonChain.start()
65
	        .compare(this.format, mdRef.getFormat())
66
	        .compare(this.layout, mdRef.getLayout())
67
	        .compare(this.interpretation, mdRef.getInterpretation())
68
	        .result() == 0;		
69
	}
70
	
71
	@Override
72
	public int hashCode() {
73
		return getFormat().hashCode() + getLayout().hashCode() + getInterpretation().hashCode();
74
	}	
75
	
76
	@Override
77
	public String toString() {
78
		return getFormat() + "-" + getLayout() + "-" + getInterpretation();
79
	}
80
	
81
}
modules/cnr-index-solr-common/branches/2.0.0/src/main/java/eu/dnetlib/functionality/index/solr/utils/XmlUtils.java
1
package eu.dnetlib.functionality.index.solr.utils;
2

  
3
import java.io.StringReader;
4

  
5
import org.dom4j.Document;
6
import org.dom4j.DocumentException;
7
import org.dom4j.io.SAXReader;
8
import org.xml.sax.InputSource;
9

  
10
public class XmlUtils {
11

  
12
	/**
13
	 * helper method, parses a list of fields.
14
	 * 
15
	 * @param fields
16
	 *            the given fields
17
	 * @return the parsed fields
18
	 * @throws IndexServiceException
19
	 *             if cannot parse the fields
20
	 */
21
	public static Document parse(String xml) {
22
		try {
23
			return new SAXReader().read(new StringReader(xml));
24
		} catch (DocumentException e) {
25
			throw new IllegalArgumentException("cannot parse: " + xml);
26
		}
27
	}
28

  
29
	public static InputSource asInputSource(final String input) throws DocumentException {
30
		return new InputSource(new StringReader(parse(input).asXML()));
31
	}
32
}
modules/cnr-index-solr-common/branches/2.0.0/src/main/java/eu/dnetlib/functionality/index/solr/feed/SolrServerPool.java
1
package eu.dnetlib.functionality.index.solr.feed;
2

  
3
import java.io.IOException;
4
import java.net.MalformedURLException;
5
import java.net.URI;
6
import java.net.URL;
7
import java.util.Collection;
8
import java.util.Iterator;
9
import java.util.List;
10
import java.util.regex.Matcher;
11
import java.util.regex.Pattern;
12

  
13
import org.apache.commons.logging.Log;
14
import org.apache.commons.logging.LogFactory;
15
import org.apache.solr.client.solrj.SolrServer;
16
import org.apache.solr.client.solrj.SolrServerException;
17
import org.apache.solr.client.solrj.impl.CloudSolrServer;
18
import org.apache.solr.client.solrj.impl.HttpSolrServer;
19
import org.apache.solr.client.solrj.response.UpdateResponse;
20
import org.apache.solr.common.SolrInputDocument;
21

  
22
import com.google.common.base.Splitter;
23
import com.google.common.collect.Lists;
24
import com.google.common.hash.HashFunction;
25
import com.google.common.hash.Hashing;
26

  
27
import eu.dnetlib.miscutils.functional.xml.DnetXsltFunctions;
28

  
29
public class SolrServerPool {
30

  
31
	/**
32
	 * logger.
33
	 */
34
	private static final Log log = LogFactory.getLog(SolrServerPool.class); // NOPMD by marko on 11/24/08 5:02 PM
35

  
36
	/*
37
	 * We run into problems when using the ConcurrentUpdateSolrServer, so we're sticking to the HttpSolrServer.
38
	 */
39
	private final List<HttpSolrServer> updateServerPool = Lists.newArrayList();
40

  
41
	private CloudSolrServer cloudServer;
42

  
43
	private final HashFunction hash = Hashing.murmur3_32();
44

  
45
	public SolrServerPool(final String updateUrlLocal, final String updateUrlList, final String zkHost, final String collection, final boolean localFeeding) {
46
		for (URL url : parseUrlListPattern(updateUrlLocal, updateUrlList, localFeeding)) {
47
			updateServerPool.add(new HttpSolrServer(url + "/" + collection));
48
		}
49
		try {
50
			cloudServer = new CloudSolrServer(zkHost);
51
			cloudServer.setDefaultCollection(collection);
52
		} catch (MalformedURLException e) {
53
			throw new IllegalArgumentException(e);
54
		}
55
	}
56

  
57
	public UpdateResponse add(final SolrInputDocument doc) throws SolrServerException, IOException {
58
		return updateServerPool.get(hashPick(doc)).add(doc);
59
	}
60

  
61
	public UpdateResponse addAll(final Iterator<SolrInputDocument> docs) throws SolrServerException, IOException {
62
		if (updateServerPool.size() == 1) { return updateServerPool.get(0).add(docs); }
63
		int i = Integer.parseInt(DnetXsltFunctions.randomInt(updateServerPool.size()));
64
		return updateServerPool.get(i).add(docs);
65
	}
66

  
67
	public UpdateResponse addAll(final Collection<SolrInputDocument> docs) throws SolrServerException, IOException {
68
		if (updateServerPool.size() == 1) { return updateServerPool.get(0).add(docs); }
69
		int i = Integer.parseInt(DnetXsltFunctions.randomInt(updateServerPool.size()));
70
		return updateServerPool.get(i).add(docs);
71
	}
72

  
73
	public void deleteByQuery(final String query) throws SolrServerException, IOException {
74
		cloudServer.deleteByQuery(query);
75
	}
76

  
77
	public void commitAll() throws SolrServerException, IOException {
78
		cloudServer.commit();
79
	}
80

  
81
	public void shutdownAll() throws SolrServerException {
82
		cloudServer.shutdown();
83
		for (SolrServer server : updateServerPool) {
84
			server.shutdown();
85
		}
86
	}
87

  
88
	// //////////////////
89

  
90
	private int hashPick(final SolrInputDocument doc) {
91
		final int hashCode = hash.hashBytes(doc.getFieldValue("__indexrecordidentifier").toString().getBytes()).asInt();
92
		return Math.abs(hashCode) % updateServerPool.size();
93
	}
94

  
95
	public List<URL> parseUrlListPattern(final String local, final String list, final boolean localFeeding) {
96
		final List<URL> res = Lists.newArrayList();
97
		try {
98
			if (localFeeding) {
99
				res.add(new URL(local));
100
			} else {
101
				Matcher matcher = Pattern.compile("(^.*)\\[(\\d+)\\.\\.(\\d+)\\](.*$)").matcher(list);
102
				if (matcher.matches()) {
103
					final String prefix = matcher.group(1);
104
					int lb = Integer.parseInt(matcher.group(2));
105
					int ub = Integer.parseInt(matcher.group(3));
106
					final String suffix = matcher.group(4);
107

  
108
					for (int i = lb; i <= ub; i++) {
109
						res.add(new URL(prefix + i + suffix));
110
					}
111
				}
112
			}
113
		} catch (MalformedURLException e) {
114
			throw new IllegalArgumentException("invalid url list: " + list, e);
115
		}
116

  
117
		log.info("parsed url(s): " + res);
118
		return res;
119
	}
120

  
121
	public List<URL> parseUrlList(final String list) throws MalformedURLException {
122
		final List<URL> res = Lists.newArrayList();
123
		for (final String url : Splitter.on(",").trimResults().split(list)) {
124
			res.add(URI.create(url).toURL());
125
		}
126
		return res;
127
	}
128

  
129
}
modules/cnr-index-solr-common/branches/2.0.0/src/main/java/eu/dnetlib/functionality/index/solr/feed/StreamingInputDocumentFactory.java
1
package eu.dnetlib.functionality.index.solr.feed;
2

  
3
import java.io.StringReader;
4
import java.io.StringWriter;
5
import java.util.ArrayList;
6

  
7
import javax.xml.stream.XMLEventFactory;
8
import javax.xml.stream.XMLEventReader;
9
import javax.xml.stream.XMLEventWriter;
10
import javax.xml.stream.XMLInputFactory;
11
import javax.xml.stream.XMLOutputFactory;
12
import javax.xml.stream.XMLStreamException;
13
import javax.xml.stream.events.Namespace;
14
import javax.xml.stream.events.StartElement;
15
import javax.xml.stream.events.XMLEvent;
16

  
17
import org.apache.solr.common.SolrInputDocument;
18

  
19
import com.google.common.collect.Lists;
20

  
21
/**
22
 * Optimized version of the document parser, drop in replacement of InputDocumentFactory.
23
 * 
24
 * <p>
25
 * Faster because:
26
 * </p>
27
 * <ul>
28
 * <li>Doesn't create a DOM for the full document</li>
29
 * <li>Doesn't execute xpaths agains the DOM</li>
30
 * <li>Quickly serialize the 'result' element directly in a string.</li>
31
 * <li>Uses less memory: less pressure on GC and allows more threads to process this in parallel</li>
32
 * </ul>
33
 * 
34
 * <p>
35
 * This class is fully reentrant and can be invoked in parallel.
36
 * </p>
37
 * 
38
 * @author marko
39
 * 
40
 */
41
public class StreamingInputDocumentFactory extends InputDocumentFactory {
42

  
43
	protected static final String DNETRESULT = "dnetResult";
44

  
45
	protected static final String TARGETFIELDS = "targetFields";
46

  
47
	protected static final String INDEX_RECORD_ID_ELEMENT = "indexRecordIdentifier";
48

  
49
	protected ThreadLocal<XMLInputFactory> inputFactory = new ThreadLocal<XMLInputFactory>() {
50
		@Override
51
		protected XMLInputFactory initialValue() {
52
			return XMLInputFactory.newInstance();
53
		}
54
	};
55

  
56
	protected ThreadLocal<XMLOutputFactory> outputFactory = new ThreadLocal<XMLOutputFactory>() {
57
		@Override
58
		protected XMLOutputFactory initialValue() {
59
			return XMLOutputFactory.newInstance();
60
		}
61
	};
62

  
63
	protected ThreadLocal<XMLEventFactory> eventFactory = new ThreadLocal<XMLEventFactory>() {
64
		@Override
65
		protected XMLEventFactory initialValue() {
66
			return XMLEventFactory.newInstance();
67
		}
68
	};
69

  
70
	/**
71
	 * {@inheritDoc}
72
	 * 
73
	 * @throws XMLStreamException
74
	 * @throws DocumentException
75
	 * 
76
	 * @see eu.dnetlib.functionality.index.solr.feed.InputDocumentFactory#parseDocument(eu.dnetlib.functionality.index.solr.feed.IndexDocument,
77
	 *      java.lang.String)
78
	 */
79
	@Override
80
	public SolrInputDocument parseDocument(final String version, final String inputDocument, String dsId) {
81

  
82
		final StringWriter results = new StringWriter();
83

  
84
		try {
85
			XMLEventReader parser = inputFactory.get().createXMLEventReader(new StringReader(inputDocument));
86

  
87
			final SolrInputDocument indexDocument = new SolrInputDocument();
88

  
89
			while (parser.hasNext()) {
90
				final XMLEvent event = parser.nextEvent();
91
				if (event != null && event.isStartElement()) {
92
					final String localName = event.asStartElement().getName().getLocalPart();
93

  
94
					if (INDEX_RECORD_ID_ELEMENT.equals(localName)) {
95
						final XMLEvent text = parser.nextEvent();
96
						String recordId = getText(text);
97
						indexDocument.addField(INDEX_RECORD_ID, recordId);
98
					} else if (TARGETFIELDS.equals(localName)) {
99
						parseTargetFields(indexDocument, parser);
100
					} else if (DNETRESULT.equals(localName)) {
101
						copyResult(indexDocument, results, parser);
102
					}
103
				}
104
			}
105

  
106
			if (version != null) {
107
				indexDocument.addField(DS_VERSION, version);
108
			}
109

  
110
			if (dsId != null) {
111
				indexDocument.addField(DS_ID, dsId);
112
			}
113

  
114
			if (!indexDocument.containsKey(INDEX_RECORD_ID)) {
115
				indexDocument.clear();
116
				System.err.println("missing indexrecord id:\n" + inputDocument);
117
			}
118

  
119
			return indexDocument;
120
		} catch (XMLStreamException e) {
121
			return new SolrInputDocument();
122
		}
123
	}
124

  
125
	/**
126
	 * Parse the targetFields block and add fields to the solr document.
127
	 * 
128
	 * @param indexDocument
129
	 * @param parser
130
	 * @throws XMLStreamException
131
	 */
132
	protected void parseTargetFields(final SolrInputDocument indexDocument, final XMLEventReader parser) throws XMLStreamException {
133

  
134
		boolean hasFields = false;
135

  
136
		while (parser.hasNext()) {
137
			final XMLEvent targetEvent = parser.nextEvent();
138
			if (targetEvent.isEndElement() && targetEvent.asEndElement().getName().getLocalPart().equals(TARGETFIELDS)) {
139
				break;
140
			}
141

  
142
			if (targetEvent.isStartElement()) {
143
				final String fieldName = targetEvent.asStartElement().getName().getLocalPart();
144
				final XMLEvent text = parser.nextEvent();
145

  
146
				String data = getText(text);
147

  
148
				addField(indexDocument, fieldName, data);
149
				hasFields = true;
150
			}
151
		}
152

  
153
		if (!hasFields) {
154
			indexDocument.clear();
155
		}
156
	}
157

  
158
	/**
159
	 * Copy the /indexRecord/result element and children, preserving namespace declarations etc.
160
	 * 
161
	 * @param indexDocument
162
	 * @param results
163
	 * @param parser
164
	 * @throws XMLStreamException
165
	 */
166
	protected void copyResult(final SolrInputDocument indexDocument, final StringWriter results, final XMLEventReader parser) throws XMLStreamException {
167
		final XMLEventWriter writer = outputFactory.get().createXMLEventWriter(results);
168

  
169
		// TODO: newRecord should copy all the namespace prefixes setup in parents
170
		// fortunately the only parent of the result element is the 'indexrecord', so it should be easy to get
171
		// the namespaces declared on the root element (and fast)
172

  
173
		final ArrayList<Namespace> namespaces = Lists.newArrayList(
174
				eventFactory.get().createNamespace("dri", "http://www.driver-repository.eu/namespace/dri"),
175
				eventFactory.get().createNamespace("dr", "http://www.driver-repository.eu/namespace/dr"),
176
				eventFactory.get().createNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"),
177
				eventFactory.get().createNamespace("dc", "http://purl.org/dc/elements/1.1/"),
178
				eventFactory.get().createNamespace("oaf", "http://namespace.openaire.eu/oaf"));
179

  
180
		StartElement newRecord = eventFactory.get().createStartElement("", null, RESULT, null, namespaces.iterator());
181

  
182
		// new root record
183
		writer.add(newRecord);
184

  
185
		// copy the rest as it is
186
		while (parser.hasNext()) {
187
			final XMLEvent resultEvent = parser.nextEvent();
188

  
189
			// TODO: replace with depth tracking instead of close tag tracking. 
190
			if (resultEvent.isEndElement() && resultEvent.asEndElement().getName().getLocalPart().equals(DNETRESULT)) {
191
				writer.add(eventFactory.get().createEndElement("", null, RESULT));
192
				break;
193
			}
194

  
195
			writer.add(resultEvent);
196
		}
197
		writer.close();
198

  
199
		indexDocument.addField(INDEX_RESULT, results);
200
	}
201

  
202
	/**
203
	 * Helper used to add a field to a solr doc. It avoids to add empy fields
204
	 * 
205
	 * @param indexDocument
206
	 * @param field
207
	 * @param value
208
	 */
209
	private final void addField(SolrInputDocument indexDocument, String field, String value) {
210
		String cleaned = value.trim();
211
		if (!cleaned.isEmpty()) {
212
			//log.info("\n\n adding field " + field.toLowerCase() + " value: " + cleaned + "\n");
213
			indexDocument.addField(field.toLowerCase(), cleaned);
214
		}
215
	}
216

  
217
	/**
218
	 * Helper used to get the string from a text element.
219
	 * 
220
	 * @param text
221
	 * @return
222
	 */
223
	protected final String getText(XMLEvent text) {
224
		if (text.isEndElement()) {
225
			//			log.warn("skipping because isEndOfElement " + text.asEndElement().getName().getLocalPart());
226
			return "";
227
		}
228

  
229
		return text.asCharacters().getData();
230
	}
231

  
232
}
modules/cnr-index-solr-common/branches/2.0.0/src/main/java/eu/dnetlib/functionality/index/solr/feed/InputDocumentFactory.java
1
package eu.dnetlib.functionality.index.solr.feed;
2

  
3
import java.text.ParseException;
4
import java.text.SimpleDateFormat;
5
import java.util.Arrays;
6
import java.util.List;
7

  
8
import javax.xml.stream.XMLStreamException;
9

  
10
import org.apache.solr.common.SolrInputDocument;
11

  
12
/**
13
 * 
14
 * @author claudio
15
 * 
16
 */
17
public abstract class InputDocumentFactory {
18

  
19
	public static final String INDEX_FIELD_PREFIX = "__";
20

  
21
	public static final String DS_VERSION = INDEX_FIELD_PREFIX + "dsversion";
22

  
23
	public static final String DS_ID = INDEX_FIELD_PREFIX + "dsid";
24

  
25
	public static final String RESULT = "result";
26

  
27
	public static final String INDEX_RESULT = INDEX_FIELD_PREFIX + RESULT;
28

  
29
	public static final String INDEX_RECORD_ID = INDEX_FIELD_PREFIX + "indexrecordidentifier";
30

  
31
	private static final String outFormat = new String("yyyy-MM-dd'T'hh:mm:ss'Z'");
32

  
33
	private final static List<String> dateFormats = Arrays.asList("yyyy-MM-dd'T'hh:mm:ss", "yyyy-MM-dd", "dd-MM-yyyy", "dd/MM/yyyy", "yyyy");
34

  
35
	public abstract SolrInputDocument parseDocument(final String version, String inputDocument, String dsId) throws XMLStreamException;
36

  
37
	/**
38
	 * method return a solr-compatible string representation of a date
39
	 * 
40
	 * @param date
41
	 * @return
42
	 * @throws DocumentException
43
	 * @throws ParseException
44
	 */
45
	public static String getParsedDateField(final String date) {
46
		for (String formatString : dateFormats) {
47
			try {
48
				return new SimpleDateFormat(outFormat).format(new SimpleDateFormat(formatString).parse(date));
49
			} catch (ParseException e) {
50
			}
51
		}
52
		throw new IllegalStateException("unable to parse date: " + date);
53
	}
54

  
55
	public String parseDate(final String date) {
56
		return getParsedDateField(date);
57
	}
58

  
59
}
modules/cnr-index-solr-common/branches/2.0.0/src/main/java/eu/dnetlib/functionality/index/solr/browsing/BrowsingRow.java
1
package eu.dnetlib.functionality.index.solr.browsing;
2

  
3
import java.util.List;
4

  
5
import javax.xml.bind.annotation.XmlAccessorType;
6
import javax.xml.bind.annotation.XmlElement;
7
import javax.xml.bind.annotation.XmlRootElement;
8
import javax.xml.bind.annotation.XmlAccessType;
9

  
10
import org.springframework.beans.factory.annotation.Required;
11

  
12
/**
13
 * 
14
 *	serialization of the browsing result.
15
 * 
16
 *	<row>
17
 *		<groupresult field="facetFieldName1">
18
 *			<value>facetFieldValue</value>
19
 *			<count>1</count>
20
 *     </groupresult>
21
 *     
22
 *		<groupresult field="facetFieldName2">
23
 *			<value>facetFieldValue</value>
24
 *			<count>1</count>
25
 *     </groupresult>
26
 *     
27
 *	</row>
28
 *
29
 * @author claudio
30
 *
31
 */
32
@XmlRootElement(namespace = "", name = "row")
33
@XmlAccessorType(XmlAccessType.FIELD)
34
public class BrowsingRow {
35
	
36
	@XmlElement(name = "groupresult", required = true)
37
	private List<GroupResult> groupresult;
38
	
39
	public BrowsingRow() { }
40
	
41
	public BrowsingRow(List<GroupResult> groupresult) {
42
		this.groupresult = groupresult;
43
	}
44
	
45
	/**
46
	 * adds a GroupResult.
47
	 * 
48
	 * @param fieldName
49
	 * @param fieldValue
50
	 * @param count
51
	 */
52
	public void addBrowsingRow(String fieldName, String fieldValue, int count) {
53
		groupresult.add(new GroupResult(fieldName, fieldValue, count));
54
	}
55
	
56
	@Override
57
	public boolean equals(Object obj) {
58
		
59
		if (!(obj instanceof BrowsingRow)) return false;
60

  
61
		final BrowsingRow brws = (BrowsingRow) obj;
62
		
63
		return groupresult.equals(brws.getGroupResult());
64
	}
65

  
66
	public List<GroupResult> getGroupResult() {
67
		return groupresult;
68
	}
69
	
70
	@Required
71
	public void setGroupResult(List<GroupResult> groupresult) {
72
		this.groupresult = groupresult;
73
	}
74

  
75
}
modules/cnr-index-solr-common/branches/2.0.0/src/main/java/eu/dnetlib/functionality/index/solr/browsing/GroupResult.java
1
package eu.dnetlib.functionality.index.solr.browsing;
2

  
3
import javax.xml.bind.annotation.XmlAttribute;
4
import javax.xml.bind.annotation.XmlRootElement;
5

  
6
import org.springframework.beans.factory.annotation.Required;
7

  
8
/**
9
 * <pre>
10
 * {@code
11
 *	<groupresult field="facetFieldName">
12
 *		<value>facetFieldValue</value>
13
 *		<count>1</count>
14
 *	</groupresult>
15
 * }
16
 * </pre>
17
 * 
18
 * @author claudio
19
 *
20
 */
21
@XmlRootElement(namespace = "", name = "groupresult")
22
public class GroupResult {
23
	
24
	private String name;
25
	
26
	private String value;
27
	
28
	private int count; 
29

  
30
	public GroupResult() { }
31
	
32
	/**
33
	 * Builds a groupResult.
34
	 * 
35
	 * @param fieldName
36
	 * @param fieldValue
37
	 * @param count
38
	 */
39
	public GroupResult(String name, String value, int count) {
40
		this.name = name;
41
		this.value = value;
42
		this.count = count;
43
	}
44

  
45
	@Override
46
	public boolean equals(Object obj) {
47
		if (!(obj instanceof GroupResult)) return false;
48
		final GroupResult g = (GroupResult)obj;
49
		if (this.getCount() == g.getCount() &&
50
			this.getName().equals(g.getName()) &&
51
			this.getValue().equals(g.getValue()))
52
			return true;
53
		return false;
54
	}
55

  
56
	@XmlAttribute(name = "field", required = true)
57
	public String getName() {
58
		return name;
59
	}
60

  
61
	public String getValue() {
62
		return value;
63
	}
64

  
65
	public int getCount() {
66
		return count;
67
	}
68
	
69
	@Required
70
	public void setName(String name) {
71
		this.name = name;
72
	}
73

  
74
	@Required
75
	public void setValue(String value) {
76
		this.value = value;
77
	}
78
	
79
	@Required
80
	public void setCount(int count) {
81
		this.count = count;
82
	}
83

  
84
}
modules/cnr-index-solr-common/branches/2.0.0/src/main/java/eu/dnetlib/functionality/index/model/AnySeq.java
1
package eu.dnetlib.functionality.index.model;
2

  
3
import java.util.Date;
4
import java.util.List;
5

  
6
/**
7
 * Interface for a sequence of Any objects.
8
 * 
9
 * <p>
10
 * AnySeq does <b>not</b> allow <code>null</code> values!
11
 * </p>
12
 * 
13
 */
14
public interface AnySeq extends List<Any>, Any {
15

  
16
	/**
17
	 * @param element
18
	 *            The string object to add
19
	 * @return true if successfully added, false else
20
	 */
21
	boolean add(String element);
22

  
23
	/**
24
	 * Long, Integer, Short and Byte values will be converted to Value object of type LONG, all others to Value object
25
	 * of type DOUBLE.
26
	 * 
27
	 * @param number
28
	 *            The number object to add
29
	 * @return true if successfully added, false else
30
	 */
31
	boolean add(Number number);
32

  
33
	/**
34
	 * @param index
35
	 *            The index where to add the any object
36
	 * @param element
37
	 *            The any object to add
38
	 */
39
	@Override
40
	void add(int index, Any element);
41

  
42
	/**
43
	 * @param index
44
	 *            The index of the object to return
45
	 * @return The AnyMap matching to the index, an InvalidValueTypeException is thrown if the value is not of type
46
	 *         AnyMap
47
	 */
48
	AnyMap getMap(int index);
49

  
50
	/**
51
	 * @param index
52
	 *            The index of the object to return
53
	 * @return The AnySeq matching to this index, an InvalidValueTypeException is thrown if the value is not of type
54
	 */
55
	AnySeq getSeq(int index);
56

  
57
	/**
58
	 * @param index
59
	 *            The index of the object to return
60
	 * @return The value matching to this index, an InvalidValueTypeException is thrown if the value is no value type.
61
	 */
62
	Value getValue(int index);
63

  
64
	/**
65
	 * @param index
66
	 *            The index of the object to return
67
	 * @return The string value matching to this index, an InvalidValueTypeException is thrown if the value is not of
68
	 *         type string
69
	 */
70
	String getStringValue(int index);
71

  
72
	/**
73
	 * @param index
74
	 *            The index of the object to return
75
	 * @return The double value matching to this index, an InvalidValueTypeException is thrown if the value is not of
76
	 *         type double
77
	 */
78
	Double getDoubleValue(int index);
79

  
80
	/**
81
	 * @param index
82
	 *            The index of the object to return
83
	 * @return The long value matching to this index, an InvalidValueTypeException is thrown if the value is not of type
84
	 *         long
85
	 */
86
	Long getLongValue(int index);
87

  
88
	/**
89
	 * @param index
90
	 *            The index of the object to return
91
	 * @return The boolean value matching to this index, an InvalidValueTypeException is thrown if the value is not of
92
	 *         type boolean
93
	 */
94
	Boolean getBooleanValue(int index);
95

  
96
	/**
97
	 * @param index
98
	 *            The index of the object to return
99
	 * @return The date value matching to this index, an InvalidValueTypeException is thrown if the value is not of type
100
	 *         date
101
	 */
102
	Date getDateValue(int index);
103

  
104
	/**
105
	 * @param index
106
	 *            The index of the object to return
107
	 * @return The date time value matching to this index, an InvalidValueTypeException is thrown if the value is not of
108
	 *         type date time
109
	 */
110
	Date getDateTimeValue(int index);
111

  
112
	/**
113
	 * returns all values as a List of Strings.
114
	 * 
115
	 * @throws InvalidValueTypeException
116
	 *             if not all contained values are strings.
117
	 */
118
	List<String> asStrings();
119

  
120
	/**
121
	 * returns all values as a List of Long.
122
	 * 
123
	 * @throws InvalidValueTypeException
124
	 *             if not all contained values are Longs.
125
	 */
126
	List<Long> asLongs();
127

  
128
}
129 0

  
modules/cnr-index-solr-common/branches/2.0.0/src/main/java/eu/dnetlib/functionality/index/model/DataFactoryCreator.java
1
package eu.dnetlib.functionality.index.model;
2

  
3
import eu.dnetlib.functionality.index.model.impl.DefaultDataFactoryImpl;
4

  
5
/**
6
 * Helper class to decouple Any and Record interfaces better from default implementation.
7
 */
8
public final class DataFactoryCreator {
9

  
10
	/**
11
	 * Private default constructor to avoid instance creation.
12
	 */
13
	private DataFactoryCreator() {
14
	}
15

  
16
	/**
17
	 * @return instance of the default DataFactory.
18
	 */
19
	public static DataFactory newInstance() {
20
		return new DefaultDataFactoryImpl();
21
	}
22
}
modules/cnr-index-solr-common/branches/2.0.0/src/main/java/eu/dnetlib/functionality/index/model/impl/AnyMapImpl.java
1
package eu.dnetlib.functionality.index.model.impl;
2

  
3
import java.util.Collection;
4
import java.util.Date;
5
import java.util.Iterator;
6
import java.util.LinkedHashMap;
7
import java.util.Map;
8
import java.util.Set;
9

  
10
import eu.dnetlib.functionality.index.model.Any;
11
import eu.dnetlib.functionality.index.model.AnyMap;
12
import eu.dnetlib.functionality.index.model.AnySeq;
13
import eu.dnetlib.functionality.index.model.InvalidValueTypeException;
14
import eu.dnetlib.functionality.index.model.Value;
15

  
16
/**
17
 * Class implementing AnyMap.
18
 */
19
public final class AnyMapImpl extends AbstractAny implements AnyMap {
20

  
21
	/** version. */
22
	private static final long serialVersionUID = 1L;
23

  
24
	/** internal representation of the AnyMap. */
25
	private final Map<String, Any> _anyMap;
26

  
27
	/** Constructs a new AnyMapImpl. */
28
	AnyMapImpl() {
29
		super(ValueType.MAP);
30
		_anyMap = new LinkedHashMap<String, Any>();
31
	}
32

  
33
	/** {@inheritDoc} */
34
	@Override
35
	public void add(final String key, final Any value) {
36
		final Any any = _anyMap.get(key);
37
		AnySeq anySeq = null;
38
		if (any == null) {
39
			anySeq = getFactory().createAnySeq();
40
			_anyMap.put(key, anySeq);
41
		} else if (any.isValue() || any.isMap()) {
42
			anySeq = getFactory().createAnySeq();
43
			anySeq.add(any);
44
			_anyMap.put(key, anySeq);
45
		} else { // any.isSeq()
46
			anySeq = (AnySeq) any;
47
		}
48
		anySeq.add(value);
49
	}
50

  
51
	/** {@inheritDoc} */
52
	@Override
53
	public void clear() {
54
		_anyMap.clear();
55
	}
56

  
57
	/** {@inheritDoc} */
58
	@Override
59
	public boolean isEmpty() {
60
		return _anyMap.isEmpty();
61
	}
62

  
63
	/** {@inheritDoc} */
64
	@Override
65
	public Set<String> keySet() {
66
		return _anyMap.keySet();
67
	}
68

  
69
	/** {@inheritDoc} */
70
	@Override
71
	public Any put(final String key, final String value) {
72
		try {
73
			return put(key, new ValueImpl(ValueType.STRING, value));
74
		} catch (final Exception e) {
75
			throw new IllegalArgumentException("cannot add value for key: " + key, e);
76
		}
77
	}
78

  
79
	/** {@inheritDoc} */
80
	@Override
81
	public Any put(final String key, final Number value) {
82
		if (value == null) {
83
			throw new IllegalArgumentException("The value of any Any must not be null.");
84
		}
85
		if (value instanceof Double) {
86
			return put(key, new ValueImpl(ValueType.DOUBLE, value));
87
		} else if (value instanceof Long) {
88
			return put(key, new ValueImpl(ValueType.LONG, value));
89
		} else if (value instanceof Integer) {
90
			return put(key, new ValueImpl(ValueType.LONG, Long.valueOf(value.longValue())));
91
		} else if (value instanceof Short) {
92
			return put(key, new ValueImpl(ValueType.LONG, Long.valueOf(value.longValue())));
93
		} else if (value instanceof Byte) {
94
			return put(key, new ValueImpl(ValueType.LONG, Long.valueOf(value.longValue())));
95
		} else { // default: DOUBLE
96
			return put(key, new ValueImpl(ValueType.DOUBLE, Double.valueOf(value.doubleValue())));
97
		}
98
	}
99

  
100
	/** {@inheritDoc} */
101
	@Override
102
	public Any put(final String key, final Boolean value) {
103
		return put(key, new ValueImpl(ValueType.BOOLEAN, value));
104
	}
105

  
106
	/** {@inheritDoc} */
107
	@Override
108
	public Any put(final String key, final Any value) {
109
		if (value == null) {
110
			throw new IllegalArgumentException("The value of any Any must not be null.");
111
		}
112
		return _anyMap.put(key, value);
113
	}
114

  
115
	/** {@inheritDoc} */
116
	@Override
117
	public int size() {
118
		return _anyMap.size();
119
	}
120

  
121
	/** {@inheritDoc} */
122
	@Override
123
	public Collection<Any> values() {
124
		return _anyMap.values();
125
	}
126

  
127
	/** {@inheritDoc} */
128
	@Override
129
	public Iterator<Any> iterator() {
130
		return _anyMap.values().iterator();
131
	}
132

  
133
	/** {@inheritDoc} */
134
	@Override
135
	public AnyMap getMap(final String key) {
136
		final Any anyValue = get(key);
137
		if (anyValue != null) {
138
			if (anyValue.isMap()) {
139
				return (AnyMap) anyValue;
140
			} else {
141
				throw new InvalidValueTypeException("Cannot convert value of type '" + anyValue.getValueType() + "' to AnyMap.");
142
			}
143
		}
144
		return null;
145
	}
146

  
147
	/** {@inheritDoc} */
148
	@Override
149
	public AnySeq getSeq(final String key) {
150
		final Any anyValue = get(key);
151
		if (anyValue != null) {
152
			if (anyValue.isSeq()) {
153
				return (AnySeq) anyValue;
154
			} else {
155
				throw new InvalidValueTypeException("Cannot convert value of type '" + anyValue.getValueType() + "' to AnySeq.");
156
			}
157
		}
158
		return null;
159
	}
160

  
161
	/** {@inheritDoc} */
162
	@Override
163
	public Value getValue(final String key) {
164
		final Any anyValue = get(key);
165
		if (anyValue != null) {
166
			if (anyValue instanceof Value) {
167
				return (Value) anyValue;
168
			} else {
169
				throw new InvalidValueTypeException("Cannot convert value of type '" + anyValue.getValueType() + "' to Value.");
170
			}
171
		}
172
		return null;
173
	}
174

  
175
	/** {@inheritDoc} */
176
	@Override
177
	public String getStringValue(final String key) {
178
		final Any anyValue = get(key);
179
		if (anyValue != null) {
180
			if (anyValue instanceof Value) {
181
				return ((Value) anyValue).asString();
182
			} else {
183
				throw new InvalidValueTypeException("Cannot convert value of type '" + anyValue.getValueType() + "' to String.");
184
			}
185
		}
186
		return null;
187
	}
188

  
189
	/** {@inheritDoc} */
190
	@Override
191
	public Double getDoubleValue(final String key) {
192
		final Any anyValue = get(key);
193
		if (anyValue != null) {
194
			if (anyValue instanceof Value) {
195
				return ((Value) anyValue).asDouble();
196
			} else {
197
				throw new InvalidValueTypeException("Cannot convert value of type '" + anyValue.getValueType() + "' to double.");
198
			}
199
		}
200
		return null;
201
	}
202

  
203
	/** {@inheritDoc} */
204
	@Override
205
	public Long getLongValue(final String key) {
206
		final Any anyValue = get(key);
207
		if (anyValue != null) {
208
			if (anyValue instanceof Value) {
209
				return ((Value) anyValue).asLong();
210
			} else {
211
				throw new InvalidValueTypeException("Cannot convert value of type '" + anyValue.getValueType() + "' to long.");
212
			}
213
		}
214
		return null;
215
	}
216

  
217
	/** {@inheritDoc} */
218
	@Override
219
	public Boolean getBooleanValue(final String key) {
220
		final Any anyValue = get(key);
221
		if (anyValue != null) {
222
			if (anyValue instanceof Value) {
223
				return ((Value) anyValue).asBoolean();
224
			} else {
225
				throw new InvalidValueTypeException("Cannot convert value of type '" + anyValue.getValueType() + "' to boolean.");
226
			}
227
		}
228
		return null;
229
	}
230

  
231
	/** {@inheritDoc} */
232
	@Override
233
	public Date getDateValue(final String key) {
234
		final Any anyValue = get(key);
235
		if (anyValue != null) {
236
			if (anyValue instanceof Value) {
237
				return ((Value) anyValue).asDate();
238
			} else {
239
				throw new InvalidValueTypeException("Cannot convert value of type '" + anyValue.getValueType() + "' to Date.");
240
			}
241
		}
242
		return null;
243
	}
244

  
245
	/** {@inheritDoc} */
246
	@Override
247
	public Date getDateTimeValue(final String key) {
248
		final Any anyValue = get(key);
249
		if (anyValue != null) {
250
			if (anyValue instanceof Value) {
251
				return ((Value) anyValue).asDateTime();
252
			} else {
253
				throw new InvalidValueTypeException("Cannot convert value of type '" + anyValue.getValueType() + "' to DateTime.");
254
			}
255
		}
256
		return null;
257
	}
258

  
259
	/** {@inheritDoc} */
260
	@Override
261
	public int hashCode() {
262
		final int prime = 31;
263
		int result = 1;
264
		result = prime * result + (_anyMap == null ? 0 : _anyMap.hashCode());
265
		return result;
266
	}
267

  
268
	/** {@inheritDoc} */
269
	@Override
270
	public boolean equals(final Object obj) {
271
		if (this == obj) {
272
			return true;
273
		}
274
		if (obj == null) {
275
			return false;
276
		}
277
		if (getClass() != obj.getClass()) {
278
			return false;
279
		}
280
		final AnyMapImpl other = (AnyMapImpl) obj;
281
		if (_anyMap == null) {
282
			if (other._anyMap != null) {
283
				return false;
284
			}
285
		} else if (!_anyMap.equals(other._anyMap)) {
286
			return false;
287
		}
288
		return true;
289
	}
290

  
291
	/**
292
	 * {@inheritDoc}
293
	 */
294
	@Override
295
	public String toString() {
296
		return _anyMap.toString();
297
	}
298

  
299
	/** {@inheritDoc} */
300
	@Override
301
	public boolean containsKey(final Object key) {
302
		return _anyMap.containsKey(key);
303
	}
304

  
305
	/** {@inheritDoc} */
306
	@Override
307
	public boolean containsValue(final Object value) {
308
		return _anyMap.containsValue(value);
309
	}
310

  
311
	/** {@inheritDoc} */
312
	@Override
313
	public Any get(final Object key) {
314
		return _anyMap.get(key);
315
	}
316

  
317
	/** {@inheritDoc} */
318
	@Override
319
	public void putAll(final Map<? extends String, ? extends Any> map) {
320
		_anyMap.putAll(map);
321
	}
322

  
323
	/** {@inheritDoc} */
324
	@Override
325
	public Any remove(final Object key) {
326
		return _anyMap.remove(key);
327
	}
328

  
329
	/** {@inheritDoc} */
330
	@Override
331
	public Set<java.util.Map.Entry<String, Any>> entrySet() {
332
		return _anyMap.entrySet();
333
	}
334

  
335
	/**
336
	 * {@inheritDoc}
337
	 * 
338
	 * @see org.eclipse.smila.datamodel.impl.AbstractAny#asMap()
339
	 */
340
	@Override
341
	public AnyMap asMap() {
342
		return this;
343
	}
344

  
345
	/**
346
	 * {@inheritDoc}
347
	 * 
348
	 * @see org.eclipse.smila.datamodel.AnyMap#getMap(java.lang.String, boolean)
349
	 */
350
	@Override
351
	public AnyMap getMap(final String key, final boolean create) {
352
		AnyMap val = getMap(key);
353
		if (val == null && create) {
354
			val = getFactory().createAnyMap();
355
			this.put(key, val);
356
		}
357
		return val;
358

  
359
	}
360

  
361
	/**
362
	 * {@inheritDoc}
363
	 * 
364
	 * @see org.eclipse.smila.datamodel.AnyMap#getSeq(java.lang.String, boolean)
365
	 */
366
	@Override
367
	public AnySeq getSeq(final String key, final boolean create) {
368
		AnySeq val = getSeq(key);
369
		if (val == null && create) {
370
			val = getFactory().createAnySeq();
371
			this.put(key, val);
372
		}
373
		return val;
374

  
375
	}
376
}
377 0

  
modules/cnr-index-solr-common/branches/2.0.0/src/main/java/eu/dnetlib/functionality/index/model/impl/ImmutableAnyMapImpl.java
1
package eu.dnetlib.functionality.index.model.impl;
2

  
3
import java.util.Collection;
4
import java.util.Collections;
5
import java.util.Date;
6
import java.util.Iterator;
7
import java.util.Map;
8
import java.util.Set;
9

  
10
import eu.dnetlib.functionality.index.model.Any;
11
import eu.dnetlib.functionality.index.model.AnyMap;
12
import eu.dnetlib.functionality.index.model.AnySeq;
13
import eu.dnetlib.functionality.index.model.DataFactory;
14
import eu.dnetlib.functionality.index.model.Value;
15

  
16
/**
17
 * immutable decorator for an AnyMap.
18
 */
19
public class ImmutableAnyMapImpl implements AnyMap {
20

  
21
	/** The underlying anymap. */
22
	private final AnyMap _anyMap;
23

  
24
	/** The underlying map, as immutable. */
25
	private final Map<String, Any> _immutable;
26

  
27
	/**
28
	 * @param createAnyMap
29
	 */
30
	public ImmutableAnyMapImpl(AnyMap map) {
31
		_anyMap = map;
32
		_immutable = Collections.unmodifiableMap(map);
33
	}
34

  
35
	@Override
36
	public void add(String key, Any value) {
37
		throw new UnsupportedOperationException();
38
	}
39

  
40
	@Override
41
	public AnyMap asMap() {
42
		return _anyMap.asMap();
43
	}
44

  
45
	@Override
46
	public AnySeq asSeq() {
47
		return _anyMap.asSeq();
48
	}
49

  
50
	@Override
51
	public Value asValue() {
52
		return _anyMap.asValue();
53
	}
54

  
55
	/**
56
	 * 
57
	 * @see java.util.Map#clear()
58
	 */
59
	@Override
60
	public void clear() {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff