/******************************************************************************* | |
* Copyright (C) 2017 ANSYS medini Technologies AG | |
* | |
* This program and the accompanying materials are made | |
* available under the terms of the Eclipse Public License 2.0 | |
* which is available at https://www.eclipse.org/legal/epl-2.0/ | |
* | |
* SPDX-License-Identifier: EPL-2.0 | |
* | |
* Contributors: | |
* ANSYS medini Technologies AG - initial API and implementation | |
******************************************************************************/ | |
package org.eclipse.opencert.elastic; | |
import java.util.ArrayList; | |
import java.util.Iterator; | |
import java.util.List; | |
import org.apache.commons.codec.digest.DigestUtils; | |
import org.eclipse.emf.ecore.EClass; | |
import org.eclipse.emf.ecore.EObject; | |
import org.eclipse.emf.ecore.resource.Resource; | |
import com.google.gson.JsonObject; | |
/** | |
* Helper to "serialize" an EMF object to an Elastic document. | |
* | |
* @author mauersberger | |
* @see EObjectToJson | |
*/ | |
public class EObjectToDocument { | |
/** | |
* Global singleton, no need to create an own instance. | |
*/ | |
public final static EObjectToDocument INSTANCE = new EObjectToDocument(); | |
/** | |
* Converts the given {@link EObject} to an {@link ElasticDocument} using | |
* {@link EObjectToJson}. | |
* | |
* @param object | |
* @param index | |
* @return the {@link ElasticDocument} never <code>null</code> | |
* @see EObjectToJson | |
*/ | |
public ElasticDocument convert(EObject object, String index) { | |
EClass type = object.eClass(); | |
Resource resource = object.eResource(); | |
JsonObject source = EObjectToJson.INSTANCE.convert(object); | |
ElasticDocument doc = new ElasticDocument(source, index, type != null ? type.getName() : "EObject", | |
resource != null ? DigestUtils.md5Hex(resource.getURIFragment(object)) : "null"); | |
return doc; | |
} | |
/** | |
* Converts the given list of {@link EObject} to a list of | |
* {@link ElasticDocument} using {@link EObjectToJson}. | |
* | |
* @param object | |
* @param index | |
* @return the list of {@link ElasticDocument} never <code>null</code> | |
* @see EObjectToJson | |
*/ | |
public List<ElasticDocument> convert(Iterator<EObject> objects, String index) { | |
List<ElasticDocument> list = new ArrayList<>(); | |
while (objects.hasNext()) { | |
EObject object = (EObject) objects.next(); | |
list.add(convert(object, index)); | |
} | |
return list; | |
} | |
} |