view src/main/java/de/mpiwg/itgroup/ismi/merge/ReferenceMerge.java @ 173:aa564b1b5e1f public_by_author

publicByAuthor feature ui for selecting texts ready. actual changing of public state not yet implemented.
author Robert Casties <casties@mpiwg-berlin.mpg.de>
date Wed, 06 Jun 2018 21:01:05 +0200
parents 28a0c2726466
children
line wrap: on
line source

package de.mpiwg.itgroup.ismi.merge;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.event.ActionEvent;

import org.apache.log4j.Logger;
import org.mpi.openmind.repository.bo.Attribute;
import org.mpi.openmind.repository.bo.Entity;
import org.mpi.openmind.repository.bo.Relation;
import org.mpi.openmind.repository.services.utils.AttributeFilter;

import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean;

public class ReferenceMerge extends AbstractISMIBean implements Serializable{
	
	private static Logger logger = Logger.getLogger(ReferenceMerge.class);
	
	private static final long serialVersionUID = 1L;

	private boolean entitiesLoaded = false;

	private Entity firstEntity;
	private String firstBibId;
	private String firstEndnoteContent;
	
	private Entity secondEntity;
    private String secondBibId;
	
	private Map<Entity, Attribute> firstEntityMap;
    private Map<Entity, Attribute> secondEntityMap;
	
    private List<Map<String, String>> previewResults;
    
	private String firstId;
	private String secondId;
	
	/**
	 * Load the first reference by its endnote-id.
	 * 
	 * Start the merge preview if the second reference has already been loaded.
	 * 
	 * @param event
	 */
	public void loadFirstEntity(ActionEvent event){
		reset();
		try{
			Long id = new Long(this.firstId);
			List<AttributeFilter> filterList = new ArrayList<AttributeFilter>();
			// search using regexp match in endnote-id attribute
			filterList.add(new AttributeFilter("endnote-id", "#" + id + "[[:>:]]", REFERENCE, true));
			firstEntityMap = getWrapper().searchEntityByAttributeFilter(filterList, 1000);
			if(this.firstEntityMap.isEmpty()){
				addErrorMsg("No references found.");
			} else {
	             // show first entity as example
                Entity ent = firstEntityMap.keySet().iterator().next();
                this.firstEntity = ent;
                Attribute att = firstEntityMap.get(ent);
                this.firstBibId = att.getOwnValue();
                
                if(this.secondEntityMap != null && ! this.secondEntityMap.isEmpty()){
                    // continue merge
                    this.previewDifferences();
                }
			}
		} catch(Exception e) {
			addErrorMsg("The first entity could no be loaded.");
		}
	}
	
    /**
     * Load the second reference by its endnote-id.
     * 
     * Start the merge preview if the first reference has already been loaded.
     * 
     * @param event
     */
	public void loadSecondEntity(ActionEvent event){
		reset();
		try{
			Long id = new Long(this.secondId);
            List<AttributeFilter> filterList = new ArrayList<AttributeFilter>();
            // search using regexp match in endnote-id attribute
            filterList.add(new AttributeFilter("endnote-id", "#" + id + "[[:>:]]", REFERENCE, true));
            secondEntityMap = getWrapper().searchEntityByAttributeFilter(filterList, 1000);
            if(this.secondEntityMap.isEmpty()){
                addErrorMsg("No references found.");
            } else {
                // show first entity as example
                Entity ent = secondEntityMap.keySet().iterator().next();
                this.secondEntity = ent;
                Attribute att = secondEntityMap.get(ent);
                this.secondBibId = att.getOwnValue();

                if(this.firstEntityMap != null && ! this.firstEntityMap.isEmpty()){
                    // continue merge
                    this.previewDifferences();
                }
            }
		}catch(Exception e){
			addErrorMsg( "The second entity could no be loaded.");
		}
	}
	
	@Override
	public void reset(){		
		this.entitiesLoaded = false;
		this.previewResults = null;
	}

	public void listenerExecuteMerge(){
		this.executeMerge();
		getAppBean().getSimpleSearchCache().setMapDirty(true);
	}
	
	/**
	 * Creates preview result list of the changes in the references.
	 */
	private void previewDifferences() {
		this.entitiesLoaded = true;

		if(this.firstEntity != null && this.secondEntity != null){
		    
            this.previewResults = new ArrayList<Map<String, String>>();
            
            if (firstEntity.isLightweight()) {
                firstEntity = getWrapper().getEntityContent(firstEntity);
            }
            Attribute ecAtt = firstEntity.getAttributeByName("endnote-content");
            firstEndnoteContent = (ecAtt != null) ? ecAtt.getValue() : "";

            for (Entity ent : this.secondEntityMap.keySet()) {

                HashMap<String, String> preview = new HashMap<String,String>();
                
                // insert content from first entity
                preview.put("new-bib-id", firstBibId);
                preview.put("new-endnote-content", firstEndnoteContent);
                
                // fetch content for second entity
                if (ent.isLightweight()) {
                    ent = getWrapper().getEntityContent(ent);
                }
                String id = ent.getId().toString();
                preview.put("id", id);                
                Attribute bibidAtt = ent.getAttributeByName("endnote-id");
                preview.put("old-bib-id", bibidAtt.getValue());
                Attribute aiAtt = ent.getAttributeByName("additional_information");
                if (aiAtt != null) {
                    preview.put("additional-information", aiAtt.getValue());
                }
                
                // get relations
                String relatedEnts = "";
                for (Relation rel : ent.getSourceRelations()) {
                    relatedEnts += rel.getObjectClass() + " ";
                    Entity relEnt = getWrapper().getEntityById(rel.getTargetId());
                    relatedEnts += "[" + relEnt.getObjectClass() + "] ";
                    relatedEnts += relEnt.getOwnValue() + " ";
                    relatedEnts += "[" + relEnt.getId() + "] ";
                }
                preview.put("related-entities", relatedEnts);
                
                previewResults.add(preview);
            }
            
		}
	}
	
	/**
	 * Execute the changes in the references.
	 * 
	 * Replaces the endnote-id and endnote-content attributes of the secondEntityMap
	 * with the values of the firstEntity.
	 */
	private void executeMerge() {
		
		logger.info("Starting reference merge execution " + firstEntity.getObjectClass() 
				+ " ["+ getUserName() +"]"
				+ "[firstEntity=" + firstEntity.getId() 
				+ ", secondEntity=" + secondEntity.getId() + "]");
		try {
		    
		    for (Entity ent : secondEntityMap.keySet()) {
		        // fetch content (should not be necessary)
                if (ent.isLightweight()) {
                    ent = getWrapper().getEntityContent(ent);
                }
		        
                // replace endnote-id
                Attribute bibidAtt = ent.getAttributeByName("endnote-id");
                if (firstBibId != null) {
                    bibidAtt.setOwnValue(firstBibId);
                } else {
                    throw new NullPointerException("Missing endnote-id to replace!");
                }
                // replace endnote-content
                Attribute ecAtt = ent.getAttributeByName("endnote-content");
                if (firstEndnoteContent != null) {
                    ecAtt.setOwnValue(firstEndnoteContent);
                } else {
                    ecAtt.setOwnValue("");
                }
                
                // save entity
                this.getWrapper().saveEntity(ent, getSessionUser().getEmail() + "_merge", null);
		    }

		    addGeneralMsg(secondEntityMap.size() + " references were changed successfully");
            this.reset();
		    
		} catch (Exception e) {
			printInternalError(e);
			logger.error("["+ getUserName() +"] " + e.getMessage(), e);			
		}
	}
	
	
	public Entity getFirstEntity() {
		return firstEntity;
	}

	public void setFirstEntity(Entity firstEntity) {
		this.firstEntity = firstEntity;
	}

	public Entity getSecondEntity() {
		return secondEntity;
	}

	public void setSecondEntity(Entity secondEntity) {
		this.secondEntity = secondEntity;
	}

	public String getFirstId() {
		return firstId;
	}

	public void setFirstId(String firstId) {
		this.firstId = firstId;
	}

	public String getSecondId() {
		return secondId;
	}

	public void setSecondId(String secondId) {
		this.secondId = secondId;
	}
	
	public boolean isEntitiesLoaded() {
		return entitiesLoaded;
	}

	public void setEntitiesLoaded(boolean entitiesLoaded) {
		this.entitiesLoaded = entitiesLoaded;
	}
	

    /**
     * @return the firstBibId
     */
    public String getFirstBibId() {
        return firstBibId;
    }

    /**
     * @return the secondBibId
     */
    public String getSecondBibId() {
        return secondBibId;
    }

    /**
     * @return the previewResults
     */
    public List<Map<String, String>> getPreviewResults() {
        return previewResults;
    }
}