Mercurial > hg > ismi-richfaces
changeset 1:2e911857a759
(none)
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/Borrar.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,10 @@ + +public class Borrar { + + public static void main(String[] args) { + String s = new String("CODEX:distinguishing_features&CODEX¬es_on_ownership&CODEX:notes"); + String[] array = s.split("&"); + System.out.println(array.length); + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/com/sun/faces/renderkit/html_basic/MenuRenderer.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,1047 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +/* + * (C) Copyright International Business Machines Corp., 2001,2002 + * The source code for this program is not published or otherwise + * divested of its trade secrets, irrespective of what has been + * deposited with the U. S. Copyright Office. + */ + +// MenuRenderer.java + +package com.sun.faces.renderkit.html_basic; + +import java.io.IOException; +import java.lang.reflect.Array; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.HashSet; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.Queue; +import java.util.LinkedList; +import java.util.logging.Level; + +import javax.el.ELException; +import javax.el.ValueExpression; +import javax.el.ExpressionFactory; +import javax.faces.component.UIComponent; +import javax.faces.component.UISelectMany; +import javax.faces.component.UISelectOne; +import javax.faces.component.ValueHolder; +import javax.faces.context.FacesContext; +import javax.faces.context.ResponseWriter; +import javax.faces.convert.Converter; +import javax.faces.convert.ConverterException; +import javax.faces.model.SelectItem; +import javax.faces.model.SelectItemGroup; +import javax.faces.FacesException; + +import org.apache.commons.lang.StringUtils; + +import com.sun.faces.RIConstants; +import com.sun.faces.io.FastStringWriter; +import com.sun.faces.renderkit.Attribute; +import com.sun.faces.renderkit.AttributeManager; +import com.sun.faces.renderkit.RenderKitUtils; +import com.sun.faces.util.MessageUtils; +import com.sun.faces.util.Util; +import com.sun.faces.util.RequestStateManager; +import com.sun.faces.util.ReflectionUtils; + +/** + * <B>MenuRenderer</B> is a class that renders the current value of + * <code>UISelectOne<code> or <code>UISelectMany<code> component as a list of + * menu options. + */ + +public class MenuRenderer extends HtmlBasicInputRenderer { + + + private static final Attribute[] ATTRIBUTES = + AttributeManager.getAttributes(AttributeManager.Key.SELECTMANYMENU); + + + // ---------------------------------------------------------- Public Methods + + + public Object convertSelectManyValue(FacesContext context, + UISelectMany uiSelectMany, + String[] newValues) + throws ConverterException { + + // if we have no local value, try to get the valueExpression. + ValueExpression valueExpression = + uiSelectMany.getValueExpression("value"); + + Object result = newValues; // default case, set local value + boolean throwException = false; + + // If we have a ValueExpression + if (null != valueExpression) { + Class modelType = valueExpression.getType(context.getELContext()); + // Does the valueExpression resolve properly to something with + // a type? + if (modelType != null) { + result = convertSelectManyValuesForModel(context, + uiSelectMany, + modelType, + newValues); + } + // If it could not be converted, as a fall back try the type of + // the valueExpression's current value covering some edge cases such + // as where the current value came from a Map. + if(result == null) { + Object value = valueExpression.getValue(context.getELContext()); + if(value != null) { + result = convertSelectManyValuesForModel(context, + uiSelectMany, + value.getClass(), + newValues); + } + } + if(result == null) { + throwException = true; + } + } else { + // No ValueExpression, just use Object array. + result = convertSelectManyValues(context, uiSelectMany, + Object[].class, + newValues); + } + if (throwException) { + StringBuffer values = new StringBuffer(); + if (null != newValues) { + for (int i = 0; i < newValues.length; i++) { + if (i == 0) { + values.append(newValues[i]); + } else { + values.append(' ').append(newValues[i]); + } + } + } + Object[] params = { + values.toString(), + valueExpression.getExpressionString() + }; + throw new ConverterException + (MessageUtils.getExceptionMessage(MessageUtils.CONVERSION_ERROR_MESSAGE_ID, + params)); + } + + // At this point, result is ready to be set as the value + if (logger.isLoggable(Level.FINE)) { + logger.fine("SelectMany Component " + uiSelectMany.getId() + + " convertedValues " + result); + } + return result; + + } + + + public Object convertSelectOneValue(FacesContext context, + UISelectOne uiSelectOne, + String newValue) + throws ConverterException { + + if (RIConstants.NO_VALUE.equals(newValue)) { + return null; + } + if (newValue == null) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("No conversion necessary for SelectOne Component " + + uiSelectOne.getId() + + " since the new value is null "); + } + return null; + } + + Object convertedValue = + super.getConvertedValue(context, uiSelectOne, newValue); + if (logger.isLoggable(Level.FINE)) { + logger.fine("SelectOne Component " + uiSelectOne.getId() + + " convertedValue " + convertedValue); + } + return convertedValue; + + } + + @Override + public void decode(FacesContext context, UIComponent component) { + + rendererParamsNotNull(context, component); + + if (!shouldDecode(component)) { + return; + } + + String clientId = decodeBehaviors(context, component); + + if (clientId == null) { + clientId = component.getClientId(context); + } + assert(clientId != null); + // currently we assume the model type to be of type string or + // convertible to string and localized by the application. + if (component instanceof UISelectMany) { + Map<String, String[]> requestParameterValuesMap = + context.getExternalContext(). + getRequestParameterValuesMap(); + if (requestParameterValuesMap.containsKey(clientId)) { + String newValues[] = requestParameterValuesMap. + get(clientId); + setSubmittedValue(component, newValues); + if (logger.isLoggable(Level.FINE)) { + logger.fine("submitted values for UISelectMany component " + + + component.getId() + + " after decoding " + + Arrays.toString(newValues)); + } + } else { + // Use the empty array, not null, to distinguish + // between an deselected UISelectMany and a disabled one + setSubmittedValue(component, new String[0]); + if (logger.isLoggable(Level.FINE)) { + logger.fine("Set empty array for UISelectMany component " + + component.getId() + " after decoding "); + } + } + } else { + // this is a UISelectOne + Map<String, String> requestParameterMap = + context.getExternalContext(). + getRequestParameterMap(); + if (requestParameterMap.containsKey(clientId)) { + String newValue = requestParameterMap.get(clientId); + setSubmittedValue(component, newValue); + if (logger.isLoggable(Level.FINE)) { + logger.fine("submitted value for UISelectOne component " + + + component.getId() + + " after decoding " + + newValue); + } + + } else { + // there is no value, but this is different from a null + // value. + setSubmittedValue(component, RIConstants.NO_VALUE); + } + } + + } + + + @Override + public void encodeBegin(FacesContext context, UIComponent component) + throws IOException { + + rendererParamsNotNull(context, component); + + } + + + @Override + public void encodeEnd(FacesContext context, UIComponent component) + throws IOException { + + rendererParamsNotNull(context, component); + + if (!shouldEncode(component)) { + return; + } + + renderSelect(context, component); + + } + + + @Override + public Object getConvertedValue(FacesContext context, UIComponent component, + Object submittedValue) + throws ConverterException { + + if (component instanceof UISelectMany) { + // need to set the 'TARGET_COMPONENT_ATTRIBUTE_NAME' request attr so the + // coerce-value call in the jsf-api UISelectMany.matchValue will work + // (need a better way to determine the currently processing UIComponent ...) + RequestStateManager.set(context, + RequestStateManager.TARGET_COMPONENT_ATTRIBUTE_NAME, + component); + return convertSelectManyValue(context, + ((UISelectMany) component), + (String[]) submittedValue); + } else { + return convertSelectOneValue(context, + ((UISelectOne) component), + (String) submittedValue); + } + + } + + // ------------------------------------------------------- Protected Methods + + + /* + * Converts the provided string array and places them into the correct provided model type. + */ + protected Object convertSelectManyValuesForModel(FacesContext context, + UISelectMany uiSelectMany, + Class modelType, + String[] newValues) { + + if (modelType.isArray()) { + return convertSelectManyValues(context, + uiSelectMany, + modelType, + newValues); + } else if (Collection.class.isAssignableFrom(modelType)) { + Object[] values = (Object[]) convertSelectManyValues(context, + uiSelectMany, + Object[].class, + newValues); + + Collection targetCollection = null; + + // see if the collectionType hint is available, if so, use that + Object collectionTypeHint = uiSelectMany.getAttributes().get("collectionType"); + if (collectionTypeHint != null) { + targetCollection = createCollectionFromHint(collectionTypeHint); + } else { + // try to get a new Collection to store the values based + // by trying to create a clone + Collection currentValue = (Collection) uiSelectMany.getValue(); + if (currentValue != null) { + targetCollection = cloneValue(currentValue); + } + + // No cloned instance so if the modelType happens to represent a + // concrete type (probably not the norm) try to reflect a + // no-argument constructor and invoke if available. + if (targetCollection == null) { + //noinspection unchecked + targetCollection = + createCollection(currentValue, modelType); + } + + // No suitable instance to work with, make our best guess + // based on the type. + if (targetCollection == null) { + //noinspection unchecked + targetCollection = bestGuess(modelType, values.length); + } + } + + //noinspection ManualArrayToCollectionCopy + for (Object v : values) { + //noinspection unchecked + targetCollection.add(v); + } + + return targetCollection; + } else if (Object.class.equals(modelType)) { + return convertSelectManyValues(context, + uiSelectMany, + Object[].class, + newValues); + } else { + throw new FacesException("Target model Type is no a Collection or Array"); + } + + } + + + + + protected Object convertSelectManyValues(FacesContext context, + UISelectMany uiSelectMany, + Class arrayClass, + String[] newValues) + throws ConverterException { + + Object result; + Converter converter; + int len = (null != newValues ? newValues.length : 0); + + Class elementType = arrayClass.getComponentType(); + + // Optimization: If the elementType is String, we don't need + // conversion. Just return newValues. + if (elementType.equals(String.class)) { + return newValues; + } + + try { + result = Array.newInstance(elementType, len); + } catch (Exception e) { + throw new ConverterException(e); + } + + // bail out now if we have no new values, returning our + // oh-so-useful zero-length array. + if (null == newValues) { + return result; + } + + // obtain a converter. + + // attached converter takes priority + if (null == (converter = uiSelectMany.getConverter())) { + // Otherwise, look for a by-type converter + if (null == (converter = Util.getConverterForClass(elementType, + context))) { + // if that fails, and the attached values are of Object type, + // we don't need conversion. + if (elementType.equals(Object.class)) { + return newValues; + } + StringBuffer valueStr = new StringBuffer(); + for (int i = 0; i < len; i++) { + if (i == 0) { + valueStr.append(newValues[i]); + } else { + valueStr.append(' ').append(newValues[i]); + } + } + Object[] params = { + valueStr.toString(), + "null Converter" + }; + + throw new ConverterException(MessageUtils.getExceptionMessage( + MessageUtils.CONVERSION_ERROR_MESSAGE_ID, params)); + } + } + + assert(null != result); + if (elementType.isPrimitive()) { + for (int i = 0; i < len; i++) { + if (elementType.equals(Boolean.TYPE)) { + Array.setBoolean(result, i, + ((Boolean) converter.getAsObject(context, + uiSelectMany, + newValues[i]))); + } else if (elementType.equals(Byte.TYPE)) { + Array.setByte(result, i, + ((Byte) converter.getAsObject(context, + uiSelectMany, + newValues[i]))); + } else if (elementType.equals(Double.TYPE)) { + Array.setDouble(result, i, + ((Double) converter.getAsObject(context, + uiSelectMany, + newValues[i]))); + } else if (elementType.equals(Float.TYPE)) { + Array.setFloat(result, i, + ((Float) converter.getAsObject(context, + uiSelectMany, + newValues[i]))); + } else if (elementType.equals(Integer.TYPE)) { + Array.setInt(result, i, + ((Integer) converter.getAsObject(context, + uiSelectMany, + newValues[i]))); + } else if (elementType.equals(Character.TYPE)) { + Array.setChar(result, i, + ((Character) converter.getAsObject(context, + uiSelectMany, + newValues[i]))); + } else if (elementType.equals(Short.TYPE)) { + Array.setShort(result, i, + ((Short) converter.getAsObject(context, + uiSelectMany, + newValues[i]))); + } else if (elementType.equals(Long.TYPE)) { + Array.setLong(result, i, + ((Long) converter.getAsObject(context, + uiSelectMany, + newValues[i]))); + } + } + } else { + for (int i = 0; i < len; i++) { + if (logger.isLoggable(Level.FINE)) { + Object converted = converter.getAsObject(context, + uiSelectMany, + newValues[i]); + logger.fine("String value: " + newValues[i] + + " converts to : " + converted); + } + Array.set(result, i, converter.getAsObject(context, + uiSelectMany, + newValues[i])); + } + } + return result; + + } + + + protected boolean renderOption(FacesContext context, + UIComponent component, + Converter converter, + SelectItem curItem, + Object currentSelections, + Object[] submittedValues, + OptionComponentInfo optionInfo) throws IOException { + + Object valuesArray; + Object itemValue; + String valueString = getFormattedValue(context, component, + curItem.getValue(), converter); + boolean containsValue; + if (submittedValues != null) { + containsValue = containsaValue(submittedValues); + if (containsValue) { + valuesArray = submittedValues; + itemValue = valueString; + } else { + valuesArray = currentSelections; + itemValue = curItem.getValue(); + } + } else { + valuesArray = currentSelections; + itemValue = curItem.getValue(); + } + + boolean isSelected = isSelected(context, component, itemValue, valuesArray, converter); + if (optionInfo.isHideNoSelection() + && curItem.isNoSelectionOption() + && currentSelections != null + && !isSelected) { + return false; + } + + ResponseWriter writer = context.getResponseWriter(); + assert (writer != null); + writer.writeText("\t", component, null); + writer.startElement("option", component); + writer.writeAttribute("value", valueString, "value"); + + if (isSelected) { + writer.writeAttribute("selected", true, "selected"); + } + + // if the component is disabled, "disabled" attribute would be rendered + // on "select" tag, so don't render "disabled" on every option. + if ((!optionInfo.isDisabled()) && curItem.isDisabled()) { + writer.writeAttribute("disabled", true, "disabled"); + } + + + //jurzua + if(StringUtils.isNotEmpty(curItem.getStyle())){ + writer.writeAttribute("style", curItem.getStyle(), curItem.getStyle()); + } + + + String labelClass; + if (optionInfo.isDisabled() || curItem.isDisabled()) { + labelClass = optionInfo.getDisabledClass(); + } else { + labelClass = optionInfo.getEnabledClass(); + } + if (labelClass != null) { + writer.writeAttribute("class", labelClass, "labelClass"); + } + + if (curItem.isEscape()) { + String label = curItem.getLabel(); + if (label == null) { + label = valueString; + } + writer.writeText(label, component, "label"); + } else { + writer.write(curItem.getLabel()); + } + writer.endElement("option"); + writer.writeText("\n", component, null); + return true; + } + + + protected void writeDefaultSize(ResponseWriter writer, int itemCount) + throws IOException { + + // if size is not specified default to 1. + writer.writeAttribute("size", "1", "size"); + + } + + + protected boolean containsaValue(Object valueArray) { + + if (null != valueArray) { + int len = Array.getLength(valueArray); + for (int i = 0; i < len; i++) { + Object value = Array.get(valueArray, i); + if (value != null && !(value.equals(RIConstants.NO_VALUE))) { + return true; + } + } + } + return false; + + } + + + protected Object getCurrentSelectedValues(UIComponent component) { + + if (component instanceof UISelectMany) { + UISelectMany select = (UISelectMany) component; + Object value = select.getValue(); + if (value == null) { + return null; + } else if (value instanceof Collection) { + return ((Collection) value).toArray(); + } else if (value.getClass().isArray()) { + if (Array.getLength(value) == 0) { + return null; + } + } else if (!value.getClass().isArray()) { + logger.warning( + "The UISelectMany value should be an array or a collection type, the actual type is " + + value.getClass().getName()); + } + + return value; + } + + UISelectOne select = (UISelectOne) component; + Object val = select.getValue(); + if (val != null) { + return new Object[] { val }; + } + return null; + + } + + + // To derive a selectOne type component from this, override + // these methods. + protected String getMultipleText(UIComponent component) { + + if (component instanceof UISelectMany) { + return " multiple "; + } + return ""; + + } + + protected Object[] getSubmittedSelectedValues(UIComponent component) { + + if (component instanceof UISelectMany) { + UISelectMany select = (UISelectMany) component; + return (Object[]) select.getSubmittedValue(); + } + + UISelectOne select = (UISelectOne) component; + Object val = select.getSubmittedValue(); + if (val != null) { + return new Object[] { val }; + } + return null; + + } + + + protected boolean isSelected(FacesContext context, + UIComponent component, + Object itemValue, + Object valueArray, + Converter converter) { + + if (itemValue == null && valueArray == null) { + return true; + } + if (null != valueArray) { + if (!valueArray.getClass().isArray()) { + logger.warning("valueArray is not an array, the actual type is " + + valueArray.getClass()); + return valueArray.equals(itemValue); + } + int len = Array.getLength(valueArray); + for (int i = 0; i < len; i++) { + Object value = Array.get(valueArray, i); + if (value == null && itemValue == null) { + return true; + } else { + if ((value == null) ^ (itemValue == null)) { + continue; + } + Object compareValue; + if (converter == null) { + compareValue = coerceToModelType(context, + itemValue, + value.getClass()); + } else { + compareValue = itemValue; + if (compareValue instanceof String && !(value instanceof String)) { + // type mismatch between the time and the value we're + // comparing. Invoke the Converter. + compareValue = converter.getAsObject(context, + component, + (String) compareValue); + } + } + + if (value.equals(compareValue)) { + return (true); + } + } + } + } + return false; + + } + + + protected int renderOptions(FacesContext context, + UIComponent component, + Iterator<SelectItem> items) + throws IOException { + + ResponseWriter writer = context.getResponseWriter(); + assert(writer != null); + + Converter converter = null; + if(component instanceof ValueHolder) { + converter = ((ValueHolder)component).getConverter(); + } + int count = 0; + Object currentSelections = getCurrentSelectedValues(component); + Object[] submittedValues = getSubmittedSelectedValues(component); + Map<String,Object> attributes = component.getAttributes(); + boolean componentDisabled = Util.componentIsDisabled(component); + + OptionComponentInfo optionInfo = + new OptionComponentInfo((String) attributes.get("disabledClass"), + (String) attributes.get("enabledClass"), + componentDisabled, + isHideNoSelection(component)); + RequestStateManager.set(context, + RequestStateManager.TARGET_COMPONENT_ATTRIBUTE_NAME, + component); + while (items.hasNext()) { + SelectItem item = items.next(); + + if (item instanceof SelectItemGroup) { + // render OPTGROUP + writer.startElement("optgroup", component); + writer.writeAttribute("label", item.getLabel(), "label"); + + // if the component is disabled, "disabled" attribute would be rendered + // on "select" tag, so don't render "disabled" on every option. + if ((!componentDisabled) && item.isDisabled()) { + writer.writeAttribute("disabled", true, "disabled"); + } + count++; + // render options of this group. + SelectItem[] itemsArray = + ((SelectItemGroup) item).getSelectItems(); + for (int i = 0; i < itemsArray.length; ++i) { + if (renderOption(context, + component, + converter, + itemsArray[i], + currentSelections, + submittedValues, + optionInfo)) { + count++; + } + } + writer.endElement("optgroup"); + } else { + if (renderOption(context, + component, + converter, + item, + currentSelections, + submittedValues, + optionInfo)) { + count ++; + } + } + } + + return count; + + } + + + // Render the "select" portion.. + // + protected void renderSelect(FacesContext context, + UIComponent component) throws IOException { + + ResponseWriter writer = context.getResponseWriter(); + assert(writer != null); + + if (logger.isLoggable(Level.FINER)) { + logger.log(Level.FINER, "Rendering 'select'"); + } + writer.startElement("select", component); + writeIdAttributeIfNecessary(context, writer, component); + writer.writeAttribute("name", component.getClientId(context), + "clientId"); + // render styleClass attribute if present. + String styleClass; + if (null != + (styleClass = + (String) component.getAttributes().get("styleClass"))) { + writer.writeAttribute("class", styleClass, "styleClass"); + } + if (!getMultipleText(component).equals("")) { + writer.writeAttribute("multiple", true, "multiple"); + } + + // Determine how many option(s) we need to render, and update + // the component's "size" attribute accordingly; The "size" + // attribute will be rendered as one of the "pass thru" attributes + Iterator<SelectItem> items = RenderKitUtils.getSelectItems(context, component); + + // render the options to a buffer now so that we can determine + // the size + FastStringWriter bufferedWriter = new FastStringWriter(128); + context.setResponseWriter(writer.cloneWithWriter(bufferedWriter)); + int count = renderOptions(context, component, items); + context.setResponseWriter(writer); + // If "size" is *not* set explicitly, we have to default it correctly + Integer size = (Integer) component.getAttributes().get("size"); + if (size == null || size == Integer.MIN_VALUE) { + size = count; + } + writeDefaultSize(writer, size); + + RenderKitUtils.renderPassThruAttributes(context, + writer, + component, + ATTRIBUTES, + getNonOnChangeBehaviors(component)); + RenderKitUtils.renderXHTMLStyleBooleanAttributes(writer, + component); + + RenderKitUtils.renderOnchange(context, component, false); + + // Now, write the buffered option content + writer.write(bufferedWriter.toString()); + + writer.endElement("select"); + + } + + protected Object coerceToModelType(FacesContext ctx, + Object value, + Class itemValueType) { + + Object newValue; + try { + ExpressionFactory ef = ctx.getApplication().getExpressionFactory(); + newValue = ef.coerceToType(value, itemValueType); + } catch (ELException ele) { + newValue = value; + } catch (IllegalArgumentException iae) { + // If coerceToType fails, per the docs it should throw + // an ELException, however, GF 9.0 and 9.0u1 will throw + // an IllegalArgumentException instead (see GF issue 1527). + newValue = value; + } + + return newValue; + + } + + + /** + * @param collection a Collection instance + * + * @return a new <code>Collection</code> instance or null if the instance + * cannot be created + */ + protected Collection createCollection(Collection collection, + Class<? extends Collection> fallBackType) { + + Class<? extends Collection> lookupClass = + ((collection != null) ? collection.getClass() : fallBackType); + + if (!lookupClass.isInterface() + && !Modifier.isAbstract(lookupClass.getModifiers())) { + try { + return lookupClass.newInstance(); + } catch (Exception e) { + if (logger.isLoggable(Level.SEVERE)) { + logger.log(Level.SEVERE, + "Unable to create new Collection instance for type " + + lookupClass.getName(), + e); + } + } + } + + return null; + + } + + + /** + * <p> + * Utility method to invoke the the <code>clone</code> method on the provided + * value. + * </p> + * + * @param value the value to clone + * @return the result of invoking <code>clone()</code> or <code>null</code> + * if the value could not be cloned or does not implement the + * {@link Cloneable} interface + */ + protected Collection cloneValue(Object value) { + + if (value instanceof Cloneable) { + // even though Clonable marks an instance of a Class as being + // safe to call .clone(), .clone() by default is protected. + // The Collection classes that do implement Clonable do so at variable + // locations within the class hierarchy, so we're stuck having to + // use reflection. + Method clone = + ReflectionUtils.lookupMethod(value.getClass(), "clone"); + if (clone != null) { + try { + Collection c = (Collection) clone.invoke(value); + c.clear(); + return c; + } catch (Exception e) { + if (logger.isLoggable(Level.SEVERE)) { + logger.log(Level.SEVERE, + "Unable to clone collection type: {0}", + value.getClass().getName()); + logger.log(Level.SEVERE, e.toString(), e); + } + } + } else { + // no public clone method + if (logger.isLoggable(Level.FINE)) { + logger.log(Level.FINE, + "Type {0} implements Cloneable, but has no public clone method.", + value.getClass().getName()); + } + } + } + + return null; + + } + + + /** + * @param type the target model type + * @param initialSize the initial size of the <code>Collection</code> + * @return a <code>Collection</code> instance that best matches + * <code>type</code> + */ + protected Collection bestGuess(Class<? extends Collection> type, + int initialSize) { + + if (SortedSet.class.isAssignableFrom(type)) { + return new TreeSet(); + } else if (Queue.class.isAssignableFrom(type)) { + return new LinkedList(); + } else if (Set.class.isAssignableFrom(type)) { + return new HashSet(initialSize); + } else { + // this covers the where type is List or Collection + return new ArrayList(initialSize); + } + + } + + + /** + * <p> + * Create a collection from the provided hint. + * @param collectionTypeHint the Collection type as either a String or Class + * @return a new Collection instance + */ + protected Collection createCollectionFromHint(Object collectionTypeHint) { + + Class<? extends Collection> collectionType; + if (collectionTypeHint instanceof Class) { + //noinspection unchecked + collectionType = (Class<? extends Collection>) collectionTypeHint; + } else if (collectionTypeHint instanceof String) { + try { + //noinspection unchecked + collectionType = Util.loadClass((String) collectionTypeHint, + this); + } catch (ClassNotFoundException cnfe) { + throw new FacesException(cnfe); + } + } else { + // RELEASE_PENDING (i18n) + throw new FacesException( + "'collectionType' should resolve to type String or Class. Found: " + + collectionTypeHint.getClass().getName()); + } + + Collection c = createCollection(null, collectionType); + if (c == null) { + // RELEASE_PENDING (i18n) + throw new FacesException("Unable to create collection type " + collectionType); + } + return c; + + } + + + protected boolean isHideNoSelection(UIComponent component) { + + Object result = component.getAttributes().get("hideNoSelectionOption"); + return ((result != null) ? (Boolean) result : false); + + } + +} // end of class MenuRenderer
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/diva/jsp/AbsJSPWrapper.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,87 @@ +package de.mpiwg.itgroup.diva.jsp; + +import javax.faces.FactoryFinder; +import javax.faces.context.FacesContext; +import javax.faces.context.FacesContextFactory; +import javax.faces.lifecycle.Lifecycle; +import javax.faces.lifecycle.LifecycleFactory; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.mpi.openmind.cache.WrapperService; + +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; +import de.mpiwg.itgroup.ismi.entry.beans.SessionBean; + +public abstract class AbsJSPWrapper { + + private HttpServletRequest request; + private HttpServletResponse response; + + public static String APP_BEAN = "ApplicationBean1"; + public static String SESSION_BEAN = "Session"; + + public SessionBean getSessionBean(){ + return (SessionBean)getSessionBean(SESSION_BEAN); + } + + public WrapperService getWrapper(){ + return getAppBean().getWrapper(); + } + + public ApplicationBean getAppBean() { + ApplicationBean appBean = (ApplicationBean)getApplicationBean(APP_BEAN); + + if(appBean == null){ + appBean = new ApplicationBean(); + getFacesContext(request, response).getCurrentInstance().getExternalContext().getApplicationMap().put(APP_BEAN, appBean); + } + return appBean; + } + + private Object getApplicationBean(String bean) { + return getFacesContext(request, response).getExternalContext().getApplicationMap().get(bean); + } + + private Object getSessionBean(String bean) { + return getFacesContext(request, response).getExternalContext().getSessionMap().get(bean); + } + + + public HttpServletRequest getRequest() { + return request; + } + + public void setRequest(HttpServletRequest request) { + this.request = request; + } + + public HttpServletResponse getResponse() { + return response; + } + + public void setResponse(HttpServletResponse response) { + System.out.println(response); + this.response = response; + } + + + public void init(){ + System.out.println("THIS METHOD SHOULD BE IMPLEMENTED!!!!"); + } + + public FacesContext getFacesContext(HttpServletRequest request, + HttpServletResponse response) { + ServletContext servletContext = ((HttpServletRequest) request) + .getSession().getServletContext(); + FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder + .getFactory(FactoryFinder.FACES_CONTEXT_FACTORY); + LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder + .getFactory(FactoryFinder.LIFECYCLE_FACTORY); + Lifecycle lifecycle = lifecycleFactory + .getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE); + return contextFactory.getFacesContext(servletContext, request, + response, lifecycle); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/diva/jsp/JSPContext.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,5 @@ +package de.mpiwg.itgroup.diva.jsp; + +public class JSPContext extends AbsJSPWrapper{ + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/diva/jsp/JSPDigitalization.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,122 @@ +package de.mpiwg.itgroup.diva.jsp; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.utils.templates.CodexTemplate; +import de.mpiwg.itgroup.ismi.utils.templates.WitnessTemplate; + + +public class JSPDigitalization extends AbsJSPWrapper{ + + private Long digiId; + private Entity digi; + + private String name; + private String numFiles; + + + private CodexTemplate codex; + private List<WitnessTemplate> witnessList = new ArrayList<WitnessTemplate>(); + private List<WitnessTemplate> unknownList = new ArrayList<WitnessTemplate>(); + + public String getDigiLabel(){ + return (digi == null) ? null : digi.getOwnValue(); + } + + public String getUserName(){ + if(getSessionBean() != null) + return getSessionBean().getUsername(); + return null; + } + + public boolean hasLogin(){ + return !StringUtils.isEmpty(getUserName()); + } + + public boolean canEdit(){ + if(getSessionBean() != null) + return getSessionBean().isCanEdit(); + return false; + } + + @Override + public void init(){ + try { + this.loadDigitalization(Long.parseLong(getRequest().getParameter("digiId"))); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void reset(){ + this.witnessList = new ArrayList<WitnessTemplate>(); + this.unknownList = new ArrayList<WitnessTemplate>(); + this.codex = null; + this.digi = null; + this.digiId = null; + this.name = null; + this.numFiles = null; + } + + private void loadDigitalization(Long digiId){ + this.reset(); + if(digiId != null){ + this.digiId = digiId; + this.digi = getWrapper().getEntityByIdWithContent(digiId); + this.name = digi.getOwnValue(); + this.numFiles = (digi.getAttributeByName("num_files") != null)? digi.getAttributeByName("num_files").getValue() : ""; + + List<Entity> list = getWrapper().getTargetsForSourceRelation(digi, "is_digitalization_of", "CODEX", 1); + if(list.size() > 0){ + this.codex = new CodexTemplate(list.get(0), getWrapper()); + List<Entity> list0 = getWrapper().getSourcesForTargetRelation(list.get(0), "is_part_of", "WITNESS", -1); + for(Entity witness : list0){ + WitnessTemplate tmp = new WitnessTemplate(witness, getWrapper(), true); + this.witnessList.add(tmp); + if(tmp.isUnknown()){ + this.unknownList.add(tmp); + } + } + } + } + Collections.sort(this.witnessList); + Collections.sort(this.unknownList); + } + + public Entity getDigi() { + return digi; + } + + public CodexTemplate getCodex() { + return codex; + } + + public List<WitnessTemplate> getWitnessList() { + return this.witnessList; + } + + public List<WitnessTemplate> getUnknownList() { + return unknownList; + } + + public String getName() { + return name; + } + + public String getNumFiles() { + return numFiles; + } + + public Long getDigiId(){ + return this.digiId; + } +} + + +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/diva/rest/DivaProxy.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,74 @@ +package de.mpiwg.itgroup.diva.rest; + +import java.io.PrintWriter; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import de.mpiwg.itgroup.diva.utils.JSONParam; +import de.mpiwg.itgroup.ismi.utils.HTTPUtils; +import de.mpiwg.itgroup.ismi.utils.HTTPUtils.HttpResponse; +import de.mpiwg.itgroup.ismi.utils.HTTPUtils.HttpStringResponse; + +@Path("/diva/proxy") +public class DivaProxy { + + private static String IMG_SERVER = "https://images.rasi.mcgill.ca/fcgi-bin/iipsrv.fcgi?FIF=/data7/srv/images/"; + + @GET + @Path("/image") + @Produces("image/jpeg") + public Response + image( + @QueryParam("f") String f, + @QueryParam("w") String w) throws Exception{ + + String dirName = getDirName(f); + + String url = IMG_SERVER + dirName + "/" + f + "&WID=" + w + "&CVT=JPG"; + + + HttpResponse resp = HTTPUtils.getHttpSSLResponse(url); + + if(resp.code == 200){ + return Response.ok(resp.content).build(); + } + + return Response.status(Response.Status.NOT_FOUND).build(); + } + + + @GET + @Path("/json/{file}") + @Produces(MediaType.APPLICATION_JSON) + public Response + json( + @PathParam("file") String file) throws Exception{ + + HttpStringResponse resp = HTTPUtils.getHttpSSLStringResponse("https://images.rasi.mcgill.ca/data/" + file + ".json"); + if(resp.code == 200){ + return Response.ok(resp.content).build(); + } + + return Response.status(Response.Status.NOT_FOUND).build(); + + } + + + + private String getDirName(String fileName){ + String[] array = fileName.split("_"); + return fileName.replace("_" + array[array.length-1], ""); + } + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/diva/rest/RestEntity.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,89 @@ +package de.mpiwg.itgroup.diva.rest; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.json.JSONException; +import org.json.JSONObject; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.diva.utils.JSONArrayParam; +import de.mpiwg.itgroup.diva.utils.JSONEntity; +import de.mpiwg.itgroup.diva.utils.JSONParam; + +@Path("/entity") +public class RestEntity extends RestInterface{ + + + public RestEntity(){ + System.out.println("%%%%%%%%%%%%%% RestWitness %%%%%%%%%%%%%%%%%%%%"); + } + + /* + @GET + @Path("/get") + @Produces(MediaType.APPLICATION_JSON) + public Track getTrackInJSON() { + + Track track = new Track(); + track.setTitle("Enter Sandman"); + track.setSinger("Metallica"); + + return track; + + }*/ + + @GET + @Path("/update") + @Produces(MediaType.APPLICATION_JSON) + public Response + saveWitnessPagesIndexing( + @Context HttpServletRequest request, + @Context HttpServletResponse response, + @QueryParam("data") JSONParam jsonParam) throws Exception{ + + + JSONObject json = jsonParam.getObj(); + System.out.println(json.toString()); + + List<JSONEntity> entityList = JSONEntity.json2EntityList(json); + + + List<Entity> toSave = new ArrayList<Entity>(); + for(JSONEntity jsonEnt : entityList){ + Entity ent = getWrapper(request, response).getEntityByIdWithContent(jsonEnt.id); + ent = jsonEnt.updateEntity(ent); + toSave.add(ent); + //getWrapper(request, response).saveEntity(ent, "jojojo"); + + } + + getWrapper(request, response).saveEntityList(toSave, "test"); + + + System.out.println(getSessionBean(request, response).getUsername()); + System.out.println(getSessionBean(request, response).getUser()); + /* + if(userCanEdit(request, response)){ + + }else{ + + }*/ + + String json0 = "{}"; + return Response.ok(json0, MediaType.APPLICATION_JSON).build(); + } + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/diva/rest/RestInterface.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,73 @@ +package de.mpiwg.itgroup.diva.rest; + +import javax.faces.FactoryFinder; +import javax.faces.context.FacesContext; +import javax.faces.context.FacesContextFactory; +import javax.faces.lifecycle.Lifecycle; +import javax.faces.lifecycle.LifecycleFactory; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.mpi.openmind.cache.WrapperService; + +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; +import de.mpiwg.itgroup.ismi.entry.beans.SessionBean; + +public abstract class RestInterface { + + public static String APP_BEAN = "ApplicationBean1"; + public static String SESSION_BEAN = "Session"; + + + protected boolean userCanEdit(HttpServletRequest request, HttpServletResponse response){ + SessionBean session = getSessionBean(request, response); + return session.isCanEdit(); + + } + + public SessionBean getSessionBean(HttpServletRequest request, + HttpServletResponse response){ + return (SessionBean)getSessionBean(SESSION_BEAN, request, response); + } + + public WrapperService getWrapper(HttpServletRequest request, + HttpServletResponse response){ + return getAppBean(request, response).getWrapper(); + } + + public ApplicationBean getAppBean(HttpServletRequest request, HttpServletResponse response) { + ApplicationBean appBean = (ApplicationBean)getApplicationBean(APP_BEAN, request, response); + + if(appBean == null){ + appBean = new ApplicationBean(); + getFacesContext(request, response).getCurrentInstance().getExternalContext().getApplicationMap().put(APP_BEAN, appBean); + } + return appBean; + } + + private Object getApplicationBean(String bean, HttpServletRequest request, + HttpServletResponse response) { + return getFacesContext(request, response).getExternalContext().getApplicationMap().get(bean); + } + + private Object getSessionBean(String bean, HttpServletRequest request, HttpServletResponse response) { + return getFacesContext(request, response).getExternalContext().getSessionMap().get(bean); + } + + + public FacesContext getFacesContext(HttpServletRequest request, + HttpServletResponse response) { + ServletContext servletContext = ((HttpServletRequest) request) + .getSession().getServletContext(); + FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder + .getFactory(FactoryFinder.FACES_CONTEXT_FACTORY); + LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder + .getFactory(FactoryFinder.LIFECYCLE_FACTORY); + Lifecycle lifecycle = lifecycleFactory + .getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE); + return contextFactory.getFacesContext(servletContext, request, + response, lifecycle); + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/diva/rest/RestWitness.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,76 @@ +package de.mpiwg.itgroup.diva.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.log4j.Logger; +import org.json.JSONObject; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.diva.utils.JSONEntity; +import de.mpiwg.itgroup.diva.utils.JSONParam; +import de.mpiwg.itgroup.ismi.entry.beans.CurrentCodexBean; + + +@Path("/witness") +public class RestWitness extends RestInterface{ + + + private static Logger logger = Logger.getLogger(RestWitness.class); + + @GET + @Path("/update") + @Produces(MediaType.APPLICATION_JSON) + public Response + saveWitnessPagesIndexing( + @Context HttpServletRequest request, + @Context HttpServletResponse response, + @QueryParam("data") JSONParam jsonParam) throws Exception{ + + JSONObject resp = new JSONObject(); + + try { + if(getSessionBean(request, response).isCanEdit()){ + JSONObject json = jsonParam.getObj(); + + logger.info(json.toString()); + + if(json.getJSONObject("witness") != null && json.getJSONObject("witness").get("id") != null){ + + JSONEntity jsonEnt = new JSONEntity(json.getJSONObject("witness"), json.getJSONObject("witness").getLong("id")); + Long digiId = json.getLong("digi_id"); + + Entity ent = getWrapper(request, response).getEntityByIdWithContent(jsonEnt.id); + ent = jsonEnt.updateEntity(ent); + + getWrapper(request, response).saveEntity(ent, getSessionBean(request, response).getUsername()); + } + + resp.put("state", "ok"); + }else{ + resp.put("state", "error"); + + if(getSessionBean(request, response).getUser() == null){ + resp.put("message", "Action was not executed. You must log in."); + }else{ + resp.put("message", "Action was not executed. User can not edit."); + } + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + resp.put("state", "error"); + resp.put("message", e.getMessage()); + } + + + return Response.ok(resp.toString(), MediaType.APPLICATION_JSON).build(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/diva/utils/JSONArrayParam.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,28 @@ +package de.mpiwg.itgroup.diva.utils; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.json.JSONArray; +import org.json.JSONException; + +public class JSONArrayParam { + + private JSONArray json; + + public JSONArrayParam(String string) throws WebApplicationException { + + try { + json = new JSONArray(string); + } catch (JSONException e) { + throw new WebApplicationException(Response.status(Status.BAD_REQUEST) + .entity("Couldn't parse JSON string: " + e.getMessage()) + .build()); + } + } + + public JSONArray getArray() { + return json; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/diva/utils/JSONEntity.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,59 @@ +package de.mpiwg.itgroup.diva.utils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; + +public class JSONEntity { + + public Long id; + public Map<String, String> attrs = new HashMap<String, String>(); + + public JSONEntity(JSONObject json, Long id) throws JSONException{ + this.id = id; + for(String attName : JSONObject.getNames(json)){ + if(!StringUtils.equals(attName, "id")){ + this.attrs.put(attName, json.getString(attName)); + } + } + } + + public Entity updateEntity(Entity ent){ + + for(String attName : this.attrs.keySet()){ + + if(ent.getAttributeByName(attName) == null){ + //TODO content type ??? + ent.addAttribute(new Attribute(attName, "text", attrs.get(attName))); + }else{ + ent.getAttributeByName(attName).setValue(attrs.get(attName)); + } + } + + return ent; + } + + + public static List<JSONEntity> json2EntityList(JSONObject json) throws JSONException{ + + List<JSONEntity> rs = new ArrayList<JSONEntity>(); + + String[] idList = JSONObject.getNames(json); + + for(String idString : idList){ + Long id = Long.parseLong(idString); + rs.add(new JSONEntity(json.getJSONObject(idString), id)); + } + + return rs; + + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/diva/utils/JSONParam.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,28 @@ +package de.mpiwg.itgroup.diva.utils; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.json.JSONException; +import org.json.JSONObject; + +public class JSONParam { + + private JSONObject json; + + public JSONParam(String string) throws WebApplicationException { + + try { + json = new JSONObject(string); + } catch (JSONException e) { + throw new WebApplicationException(Response.status(Status.BAD_REQUEST) + .entity("Couldn't parse JSON string: " + e.getMessage()) + .build()); + } + } + + public JSONObject getObj() { + return json; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/dm2e/AddAgents.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,50 @@ +package de.mpiwg.itgroup.dm2e; + +import java.util.List; + +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; +import org.openrdf.model.Model; +import org.openrdf.model.URI; +import org.openrdf.model.ValueFactory; + +import de.mpiwg.itgroup.ismi.utils.templates.WitnessTemplate; + +public class AddAgents { + + + public static void execute(Model g, ValueFactory f, URI providedCHO, WitnessTemplate witness, WrapperService wrapper) throws Exception { + + List<Entity> list = wrapper.getTargetsForSourceRelation(witness.titleId, "was_created_by", "PERSON", 1); + if(list.size() > 0){ + Entity author = list.get(0); + + URI uriPerson = f.createURI("http://data.dm2e.eu/data/agent/mpiwg/" + NameSpaces.mpiwgCollection + "/" + author.getId()); + + g.add(f.createStatement(uriPerson, URIUtils.skosPrefLabel, f.createLiteral(author.getOwnValue()))); + g.add(f.createStatement(uriPerson, URIUtils.rdfType, f.createURI("http://xmlns.com/foaf/0.1/Person"))); + g.add(f.createStatement(providedCHO, URIUtils.proAuthor, uriPerson)); + + } + + + //COPY_EVENT + list = wrapper.getSourcesForTargetRelation(witness.id, "is_a_copy_of", "COPY_EVENT", -1); + for(Entity copyEvent : list){ + List<Entity> list0 = wrapper.getTargetsForSourceRelation(copyEvent.getId(), "has_person_copying_text", "PERSON", 1); + if(list0.size() > 0){ + + Entity personCopyingText = list0.get(0); + + URI uriPerson = f.createURI("http://data.dm2e.eu/data/agent/mpiwg/" + NameSpaces.mpiwgCollection + "/" + personCopyingText.getId()); + + g.add(f.createStatement(uriPerson, URIUtils.skosPrefLabel, f.createLiteral(personCopyingText.getOwnValue()))); + g.add(f.createStatement(uriPerson, URIUtils.rdfType, f.createURI("http://xmlns.com/foaf/0.1/Person"))); + g.add(f.createStatement(providedCHO, URIUtils.dm2eCopyist, uriPerson)); + } + } + + + + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/dm2e/DM2E.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,156 @@ +package de.mpiwg.itgroup.dm2e; + +import org.openrdf.model.URI; +import org.openrdf.model.ValueFactory; +import org.openrdf.model.impl.ValueFactoryImpl; + +/** + * http://onto.dm2e.eu/schemas/dm2e/1.0/ + * + * @author jurzua + * + */ +public class DM2E { + + static ValueFactory f; + + //edm:PhysicalThing + static public URI dm2eOnto10; + static public URI Archive; //Superclass: foaf:Organization + static public URI Collection; //Superclass: edm:NonInformationResource + static public URI Document; //Subclass: dm2e:Manuscript + static public URI File; //Superclasses: edm:PhysicalThing + static public URI Manuscript; //Superclass: dm2e:Document + static public URI Paragraph; //Superclass: skos:Concept + static public URI Photo; //Superclasses: edm:PhysicalThing, foaf:Image + static public URI Publication; //Superclass: skos:Concept + static public URI Work; //Superclass: skos:Concept + + static public URI Page; + static public URI Book; + + + //Properties + static public URI artist; + static public URI callNumber; + static public URI composer; + static public URI condition; + static public URI contributor; + static public URI copyist; + static public URI explicit; + static public URI hasPartCHO; + static public URI hasPartPlace; + static public URI hasPartTimeSpan; + static public URI hasPartWebResource; + static public URI honoree; + static public URI illustration; + static public URI incipit; + static public URI influencedBy; + static public URI isDerivativeOfCHO; + static public URI isDerivativeOfWebResource; + static public URI isPartOfCHO; + static public URI isPartOfPlace; + static public URI isPartOfTimeSpan; + static public URI isPartOfWebResource; + static public URI levelOfGenesis; + static public URI mentioned; + static public URI misattributed; + static public URI owner; + static public URI pageDimension; + static public URI painter; + static public URI patron; + static public URI portrayed; + static public URI previousOwner; + static public URI principal; + static public URI printedAt; + static public URI publishedAt; + static public URI refersTo; + static public URI restoration; + static public URI scopeNote; + static public URI shelfmarkLocation; + static public URI sponsor; + static public URI studentOf; + static public URI subtitle; + static public URI subtitleTransliteration; + static public URI titleTransliteration; + static public URI wasStudiedBy; + static public URI wasTaughtBy; + static public URI watermark; + static public URI writer; + static public URI writtenAt; + static public URI writtenAreaDimension; + + static { + f = ValueFactoryImpl.getInstance(); + + //http://onto.dm2e.eu/schemas/dm2e/1.0/#Manuscript + dm2eOnto10 = f.createURI("http://onto.dm2e.eu/schemas/dm2e/"); + Archive = f.createURI(dm2eOnto10 + "Collection"); + Collection = f.createURI(dm2eOnto10 + "Collection"); + Document = f.createURI(dm2eOnto10 + "Document"); + File = f.createURI(dm2eOnto10 + "File"); + Manuscript = f.createURI(dm2eOnto10 + "Manuscript"); + Paragraph = f.createURI(dm2eOnto10 + "Paragraph"); + Photo = f.createURI(dm2eOnto10 + "Photo"); + Publication = f.createURI(dm2eOnto10 + "Publication"); + Work = f.createURI(dm2eOnto10 + "Publication"); + + + //Page = f.createURI("http://purl.org/spar/fabio/Page"); + // Page now served by dm2e + Page = f.createURI(dm2eOnto10 + "Page"); + Book = f.createURI("http://purl.org/ontology/bibo/Book"); + + //Properties + + artist = f.createURI(dm2eOnto10 + "artist"); + callNumber = f.createURI(dm2eOnto10 + "callNumber"); + composer = f.createURI(dm2eOnto10 + "composer"); + condition = f.createURI(dm2eOnto10 + "condition"); + contributor = f.createURI(dm2eOnto10 + "contributor"); + copyist = f.createURI(dm2eOnto10 + "copyist"); + explicit = f.createURI(dm2eOnto10 + "explicit"); + hasPartCHO = f.createURI(dm2eOnto10 + "hasPartCHO"); + hasPartPlace = f.createURI(dm2eOnto10 + "hasPartPlace"); + hasPartTimeSpan = f.createURI(dm2eOnto10 + "hasPartTimeSpan"); + hasPartWebResource = f.createURI(dm2eOnto10 + "hasPartWebResource"); + honoree = f.createURI(dm2eOnto10 + "honoree"); + illustration = f.createURI(dm2eOnto10 + "illustration"); + incipit = f.createURI(dm2eOnto10 + "incipit"); + influencedBy = f.createURI(dm2eOnto10 + "influencedBy"); + isDerivativeOfCHO = f.createURI(dm2eOnto10 + "isDerivativeOfCHO"); + isDerivativeOfWebResource = f.createURI(dm2eOnto10 + "isDerivativeOfWebResource"); + isPartOfCHO = f.createURI(dm2eOnto10 + "isPartOfCHO"); + isPartOfPlace = f.createURI(dm2eOnto10 + "isPartOfPlace"); + isPartOfTimeSpan = f.createURI(dm2eOnto10 + "isPartOfTimeSpan"); + isPartOfWebResource = f.createURI(dm2eOnto10 + "isPartOfWebResource"); + levelOfGenesis = f.createURI(dm2eOnto10 + "levelOfGenesis"); + mentioned = f.createURI(dm2eOnto10 + "mentioned"); + misattributed = f.createURI(dm2eOnto10 + "misattributed"); + owner = f.createURI(dm2eOnto10 + "owner"); + pageDimension = f.createURI(dm2eOnto10 + "pageDimension"); + painter = f.createURI(dm2eOnto10 + "painter"); + patron = f.createURI(dm2eOnto10 + "patron"); + portrayed = f.createURI(dm2eOnto10 + "portrayed"); + previousOwner = f.createURI(dm2eOnto10 + "previousOwner"); + principal = f.createURI(dm2eOnto10 + "principal"); + printedAt = f.createURI(dm2eOnto10 + "printedAt"); + publishedAt = f.createURI(dm2eOnto10 + "publishedAt"); + refersTo = f.createURI(dm2eOnto10 + "refersTo"); + restoration = f.createURI(dm2eOnto10 + "restoration"); + scopeNote = f.createURI(dm2eOnto10 + "scopeNote"); + shelfmarkLocation = f.createURI(dm2eOnto10 + "shelfmarkLocation"); + sponsor = f.createURI(dm2eOnto10 + "sponsor"); + studentOf = f.createURI(dm2eOnto10 + "studentOf"); + subtitle = f.createURI(dm2eOnto10 + "subtitle"); + subtitleTransliteration = f.createURI(dm2eOnto10 + "subtitleTransliteration"); + titleTransliteration = f.createURI(dm2eOnto10 + "titleTransliteration"); + wasStudiedBy = f.createURI(dm2eOnto10 + "wasStudiedBy"); + wasTaughtBy = f.createURI(dm2eOnto10 + "wasTaughtBy"); + watermark = f.createURI(dm2eOnto10 + "watermark"); + writer = f.createURI(dm2eOnto10 + "writer"); + writtenAreaDimension = f.createURI(dm2eOnto10 + "writtenAreaDimension"); + writtenAt = f.createURI(dm2eOnto10 + "writtenAt"); + + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/dm2e/DM2ECodexConverter.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,197 @@ +package de.mpiwg.itgroup.dm2e; + +import java.util.Date; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.services.ServiceRegistry; +import org.mpi.openmind.repository.utils.OMUtils; +import org.openrdf.model.Literal; +import org.openrdf.model.Model; +import org.openrdf.model.URI; +import org.openrdf.model.ValueFactory; + +import de.mpiwg.itgroup.dm2e.utils.EDM; +import de.mpiwg.itgroup.ismi.utils.templates.CodexTemplate; + +public class DM2ECodexConverter { + + + public static URI getProvidedCHO(CodexTemplate codexTempl, + WrapperService wrapper, Model g, ValueFactory f) throws Exception{ + + String identifier = (StringUtils.isNotEmpty(codexTempl.mpiwgId)) ? codexTempl.mpiwgId : codexTempl.id.toString(); + + URI providedCHO = f.createURI(NameSpaces.edmProvidedCHO, identifier); + + // + Literal title = f.createLiteral(codexTempl.ov, "en"); + g.add(f.createStatement(providedCHO, URIUtils.dcTitle, title)); + + // uri edm providedcho + g.add(f.createStatement(providedCHO, URIUtils.rdfType, f.createURI("http://www.europeana.eu/schemas/edm/ProvidedCHO"))); + + //dc:type -> Specialisation of edm:PhysicalThing + g.add(f.createStatement(providedCHO, URIUtils.dcType, DM2E.Manuscript)); + + g.add(f.createStatement(providedCHO, URIUtils.dm2eLevelOfHierarchy, f.createLiteral(1))); + + //edm:type -> Literal + g.add(f.createStatement(providedCHO, URIUtils.edmType, f.createLiteral("TEXT"))); + + String description = getDescription(codexTempl); + g.add(f.createStatement(providedCHO, URIUtils.dcDescription, f.createLiteral(description))); + + g.add(f.createStatement(providedCHO, URIUtils.dcLanguage, f.createLiteral("ar"))); + + //TODO: Places + + g.add(f.createStatement(providedCHO, URIUtils.dcIdentifier, f.createLiteral(identifier))); + + //dm2eCallNumber + g.add(f.createStatement(providedCHO, URIUtils.dm2eCallNumber, f.createLiteral(codexTempl.identifier))); + + + for(String subject : OMUtils.resolveQuery(codexTempl.id, "CODEX|target:is_part_of|WITNESS|source:is_exemplar_of|TEXT|source:has_subject|SUBJECT", wrapper, null)){ + URI uriConcept = f.createURI("http://data.dm2e.eu/data/concept/mpiwg/authority_ismi/" + DM2EUtils.encodeString(subject)); + g.add(f.createStatement(uriConcept, URIUtils.rdfType, URIUtils.skosConcept)); + g.add(f.createStatement(providedCHO, URIUtils.dcSubject, uriConcept)); + g.add(f.createStatement(uriConcept, URIUtils.skosPrefLabel, f.createLiteral(subject, "en"))); + } + + //AddAgents.execute(g, f, providedCHO, witnessTempl, wrapper); + + //dm2e:writtenAt + for(String placeWrittenAt : OMUtils.resolveQuery(codexTempl.id, "CODEX|target:is_part_of|WITNESS|source:was_created_in|PLACE", wrapper, null)){ + URI uriPlace = f.createURI(NameSpaces.edmPlace + codexTempl.id + "/" + DM2EUtils.generateID() + "_" + DM2EUtils.encodeString(placeWrittenAt)); + g.add(f.createStatement(uriPlace, f.createURI("http://www.w3.org/2004/02/skos/core#prefLabel"), f.createLiteral(placeWrittenAt, "en"))); + g.add(f.createStatement(providedCHO, DM2E.writtenAt, uriPlace)); + g.add(f.createStatement(uriPlace, URIUtils.rdfType, URIUtils.edmPlace)); + } + + + //pro:author + for(String personId : OMUtils.resolveQuery(codexTempl.id, "CODEX|target:is_part_of|WITNESS|source:is_exemplar_of|TEXT|source:was_created_by|PERSON:id", wrapper, null)){ + + Entity person = wrapper.getEntityById(Long.parseLong(personId)); + + URI uriPerson = f.createURI( + "http://data.dm2e.eu/data/agent/mpiwg/" + NameSpaces.mpiwgCollection + "/" + codexTempl.identifier + "/" + DM2EUtils.generateID() + "_" + personId); + g.add(f.createStatement(uriPerson, URIUtils.skosPrefLabel, f.createLiteral(person.getOwnValue()))); + g.add(f.createStatement(uriPerson, URIUtils.rdfType, f.createURI("http://xmlns.com/foaf/0.1/Person"))); + g.add(f.createStatement(providedCHO, URIUtils.proAuthor, uriPerson)); + } + + return providedCHO; + } + + public static URI getAggregation(CodexTemplate codexTemp, + WrapperService wrapper, Model g, ValueFactory f) throws Exception{ + + URI aggregation = f.createURI(NameSpaces.oreAggregation, codexTemp.mpiwgId); + + //edm:provider + URI provider = f.createURI("http://data.dm2e.eu/data/agent/mpiwg/" + NameSpaces.mpiwgCollection + "/DM2E"); + g.add(f.createStatement(aggregation, URIUtils.rdfType, f.createURI("http://www.openarchives.org/ore/terms/Aggregation"))); + g.add(f.createStatement(aggregation, URIUtils.edmProvider, provider)); + g.add(f.createStatement(provider, URIUtils.rdfType, f.createURI("http://xmlns.com/foaf/0.1/Organization"))); + g.add(f.createStatement(provider, URIUtils.skosPrefLabel, f.createLiteral("DM2E", "en"))); + g.add(f.createStatement(provider, URIUtils.skosAltLabel, f.createLiteral("Digitised Manuscripts to Europeana", "en"))); + + //data provider + URI dataProvider = f.createURI("http://data.dm2e.eu/data/agent/mpiwg/" + NameSpaces.mpiwgCollection + "/MPIWG"); + g.add(f.createStatement(aggregation, URIUtils.edmDataProvider, dataProvider)); + g.add(f.createStatement(dataProvider, URIUtils.skosPrefLabel, f.createLiteral("Max Planck Institute for the History of Science", "en"))); + g.add(f.createStatement(dataProvider, URIUtils.skosPrefLabel, f.createLiteral("Max-Planck-Institut für Wissenschaftsgeschichte", "de"))); + g.add(f.createStatement(dataProvider, URIUtils.rdfType, f.createURI("http://xmlns.com/foaf/0.1/Organization"))); + + //edm:rights + g.add(f.createStatement(aggregation, URIUtils.edmRights, f.createURI(DM2EConverter.RIGHTS))); + + //dm2e:displayLevel mandatory + g.add(f.createStatement(aggregation, URIUtils.dm2eDisplayLevel, f.createLiteral(true))); + + //dcterms:created + Entity witnessEnt = wrapper.getEntityById(codexTemp.id); + Date created = new Date(witnessEnt.getModificationTime()); + + g.add(f.createStatement(aggregation, URIUtils.dctCreated, + f.createLiteral(DM2EConverter.timeFormat.format(created), + f.createURI("http://www.w3.org/2001/XMLSchema#dateTime")))); + + addIsShownAt(codexTemp, aggregation, wrapper, g, f); + addLandingPageObject(codexTemp, aggregation, wrapper, g, f); + + return aggregation; + } + + private static URI addLandingPageObject(CodexTemplate codexTemp, URI agg, + WrapperService wrapper, Model g, ValueFactory f) throws Exception{ + + String indexmetaDir = codexTemp.indexmetaFolder.replace("/mpiwg/online", ""); + + + URI ws = f.createURI("http://digilib.mpiwg-berlin.mpg.de/digitallibrary/servlet/Scaler?dw=50&fn=" + indexmetaDir + "/pageimg"); + + g.add(f.createStatement(ws, f.createURI("http://purl.org/dc/elements/1.1/format"), f.createLiteral("image/jpeg"))); + g.add(f.createStatement(ws, URIUtils.dcDescription, f.createLiteral("Landing page of codex: " + codexTemp.ov))); + + //edm:rights [any URL] mandatory + g.add(f.createStatement(ws, EDM.rights, f.createLiteral(DM2EConverter.RIGHTS))); + + g.add(f.createStatement(agg, EDM.object, ws)); + // KT added type + g.add(f.createStatement(ws, URIUtils.rdfType, EDM.WebResource)); + + return ws; + } + + private static URI addIsShownAt(CodexTemplate codexTemp, URI agg, + WrapperService wrapper, Model g, ValueFactory f) throws Exception{ + + URI ws = f.createURI( + "http://echo.mpiwg-berlin.mpg.de/" + codexTemp.mpiwgId); + + g.add(f.createStatement(ws, f.createURI("http://purl.org/dc/elements/1.1/format"), f.createLiteral("text/html-named-content"))); + g.add(f.createStatement(ws, URIUtils.dcDescription, f.createLiteral("ECHO View of codex: " + codexTemp.ov))); + + //edm:rights [any URL] mandatory + g.add(f.createStatement(ws, EDM.rights, f.createLiteral(DM2EConverter.RIGHTS))); + + g.add(f.createStatement(agg, EDM.isShownAt,ws)); + + g.add(f.createStatement(ws, URIUtils.rdfType, EDM.WebResource)); + + return ws; + } + + + private static String getDescription(CodexTemplate temp){ + //TODO it can be improved! + return "Codex: " + temp.ov; + } + + public static void main(String[] args){ + + ServiceRegistry sr = new ServiceRegistry(); + + try { + //List<String> rs = OMUtils.resolveQuery(new Long(4202), "CODEX|target:is_part_of|WITNESS|source:is_exemplar_of|TEXT|source:has_subject|SUBJECT", sr.getWrapper()); + //List<String> rs = OMUtils.resolveQuery(new Long(159098), "CODEX|target:is_part_of|WITNESS|source:is_exemplar_of|TEXT|source:was_created_in|PLACE", sr.getWrapper()); + + List<String> rs = OMUtils.resolveQuery(new Long(159098), "CODEX|target:is_part_of|WITNESS|source:is_exemplar_of|TEXT|source:was_created_by|PERSON:id", sr.getWrapper(), null); + + for(String s : rs){ + System.out.println(s); + } + System.out.println(rs.size()); + + } catch (Exception e) { + e.printStackTrace(); + } + System.exit(0); + + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/dm2e/DM2EConverter.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,353 @@ +package de.mpiwg.itgroup.dm2e; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.services.ServiceRegistry; +import org.openrdf.model.Model; +import org.openrdf.model.Statement; +import org.openrdf.model.URI; +import org.openrdf.model.ValueFactory; +import org.openrdf.model.impl.LinkedHashModel; +import org.openrdf.model.impl.ValueFactoryImpl; +import org.openrdf.rio.RDFFormat; +import org.openrdf.rio.RDFHandlerException; +import org.openrdf.rio.RDFWriter; +import org.openrdf.rio.Rio; + +import de.mpiwg.itgroup.dm2e.utils.EDM; +import de.mpiwg.itgroup.ismi.utils.templates.CodexTemplate; +import de.mpiwg.itgroup.ismi.utils.templates.WitnessTemplate; + + +public class DM2EConverter { + + private static List<Long> codexIdList = new ArrayList<Long>(); + static{ + codexIdList.add(new Long(27543)); + codexIdList.add(new Long(36745)); + codexIdList.add(new Long(58453)); + codexIdList.add(new Long(87298)); + codexIdList.add(new Long(259646)); + codexIdList.add(new Long(35093)); + codexIdList.add(new Long(22863)); + codexIdList.add(new Long(34870)); + codexIdList.add(new Long(36882)); + codexIdList.add(new Long(101488)); + codexIdList.add(new Long(36696)); + codexIdList.add(new Long(31794)); + codexIdList.add(new Long(37240)); + codexIdList.add(new Long(35014)); + codexIdList.add(new Long(35583)); + codexIdList.add(new Long(37025)); + codexIdList.add(new Long(35960)); + codexIdList.add(new Long(172492)); + codexIdList.add(new Long(98286)); + codexIdList.add(new Long(165721)); + codexIdList.add(new Long(260111)); + codexIdList.add(new Long(90980)); + codexIdList.add(new Long(36316)); + codexIdList.add(new Long(260120)); + codexIdList.add(new Long(36241)); + codexIdList.add(new Long(260129)); + codexIdList.add(new Long(260138)); + codexIdList.add(new Long(38860)); + codexIdList.add(new Long(176694)); + codexIdList.add(new Long(72545)); + codexIdList.add(new Long(36185)); + codexIdList.add(new Long(36575)); + codexIdList.add(new Long(260146)); + codexIdList.add(new Long(31672)); + codexIdList.add(new Long(37739)); + codexIdList.add(new Long(89861)); + codexIdList.add(new Long(176778)); + codexIdList.add(new Long(180743)); + codexIdList.add(new Long(86328)); + codexIdList.add(new Long(260150)); + codexIdList.add(new Long(90658)); + codexIdList.add(new Long(58423)); + codexIdList.add(new Long(181058)); + codexIdList.add(new Long(105948)); + codexIdList.add(new Long(35526)); + codexIdList.add(new Long(74078)); + codexIdList.add(new Long(260158)); + codexIdList.add(new Long(181096)); + codexIdList.add(new Long(31606)); + codexIdList.add(new Long(31568)); + codexIdList.add(new Long(27872)); + codexIdList.add(new Long(36938)); + codexIdList.add(new Long(4836)); + codexIdList.add(new Long(34668)); + codexIdList.add(new Long(76866)); + codexIdList.add(new Long(102230)); + codexIdList.add(new Long(76888)); + codexIdList.add(new Long(74070)); + codexIdList.add(new Long(73757)); + codexIdList.add(new Long(182685)); + codexIdList.add(new Long(260162)); + codexIdList.add(new Long(260170)); + codexIdList.add(new Long(1102)); + codexIdList.add(new Long(172888)); + codexIdList.add(new Long(260174)); + codexIdList.add(new Long(34806)); + codexIdList.add(new Long(28088)); + codexIdList.add(new Long(36713)); + codexIdList.add(new Long(37323)); + codexIdList.add(new Long(34551)); + codexIdList.add(new Long(35943)); + codexIdList.add(new Long(98095)); + codexIdList.add(new Long(260178)); + codexIdList.add(new Long(260182)); + codexIdList.add(new Long(182770)); + codexIdList.add(new Long(260186)); + codexIdList.add(new Long(260190)); + codexIdList.add(new Long(260194)); + codexIdList.add(new Long(36114)); + codexIdList.add(new Long(85003)); + codexIdList.add(new Long(31630)); + codexIdList.add(new Long(157290)); + codexIdList.add(new Long(37153)); + codexIdList.add(new Long(37213)); + codexIdList.add(new Long(172952)); + codexIdList.add(new Long(86871)); + codexIdList.add(new Long(64406)); + codexIdList.add(new Long(102590)); + codexIdList.add(new Long(82615)); + codexIdList.add(new Long(58245)); + codexIdList.add(new Long(179791)); + codexIdList.add(new Long(179550)); + codexIdList.add(new Long(12419)); + codexIdList.add(new Long(95861)); + codexIdList.add(new Long(36429)); + codexIdList.add(new Long(36099)); + codexIdList.add(new Long(74237)); + codexIdList.add(new Long(36065)); + codexIdList.add(new Long(74822)); + codexIdList.add(new Long(87549)); + codexIdList.add(new Long(83765)); + codexIdList.add(new Long(36733)); + codexIdList.add(new Long(19259)); + codexIdList.add(new Long(260198)); + codexIdList.add(new Long(34986)); + codexIdList.add(new Long(88041)); + codexIdList.add(new Long(260202)); + codexIdList.add(new Long(36550)); + codexIdList.add(new Long(260206)); + codexIdList.add(new Long(37228)); + codexIdList.add(new Long(39880)); + codexIdList.add(new Long(36318)); + codexIdList.add(new Long(36597)); + codexIdList.add(new Long(35035)); + codexIdList.add(new Long(58328)); + codexIdList.add(new Long(80831)); + codexIdList.add(new Long(58354)); + codexIdList.add(new Long(74277)); + codexIdList.add(new Long(36529)); + codexIdList.add(new Long(36380)); + codexIdList.add(new Long(69450)); + codexIdList.add(new Long(200246)); + codexIdList.add(new Long(260222)); + codexIdList.add(new Long(81178)); + codexIdList.add(new Long(260226)); + codexIdList.add(new Long(199952)); + codexIdList.add(new Long(262557)); + codexIdList.add(new Long(87212)); + codexIdList.add(new Long(99059)); + codexIdList.add(new Long(64270)); + codexIdList.add(new Long(81811)); + codexIdList.add(new Long(65785)); + codexIdList.add(new Long(36645)); + } + + + + public static SimpleDateFormat timeFormat = new SimpleDateFormat("yyy-mm-dd'T'hh:mm:ss"); + //private static String RIGHTS = "http://www.mpiwg-berlin.mpg.de/en/institute/licences.html"; + public static String RIGHTS = "http://www.europeana.eu/portal/rights/rr-f.html"; + + public static String formatRdfXml = "rdf-xml"; + public static String formatRdfJson = "rdf-json"; + public static String formatNTripes = "ntriples"; + + public static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy.MM.dd_HH.mm"); + + public static void convertCodexList(String file, String output, List<Long> list, WrapperService wrapper) throws Exception{ + + Model g = new LinkedHashModel(); + ValueFactory f = ValueFactoryImpl.getInstance(); + + int counter = 0; + for(Long codexId : list){ + + Entity codex = wrapper.getEntityById(codexId); + if(codex != null && StringUtils.equals(codex.getObjectClass(), "CODEX")){ + CodexTemplate codexTempl = new CodexTemplate(codex, wrapper); + if(StringUtils.isNotEmpty(codexTempl.mpiwgId)){ + URI providedCHO = DM2ECodexConverter.getProvidedCHO(codexTempl, wrapper, g, f); + URI aggregation = DM2ECodexConverter.getAggregation(codexTempl, wrapper, g, f); + g.add(aggregation, EDM.aggregatedCHO, providedCHO); + counter++; + } + } + } + + + System.out.println("Transformed " + counter + " of " + list.size()); + + write(file, output, g); + } + + public void convertCodexList(String file, String output, WrapperService wrapper, Long... list) throws Exception{ + convertCodexList(file, output, Arrays.asList(list), wrapper); + } + + public static void convertCodex(String file, String output, Long codexId, WrapperService wrapper) throws Exception{ + + Model g = new LinkedHashModel(); + ValueFactory f = ValueFactoryImpl.getInstance(); + + Entity codex = wrapper.getEntityById(codexId); + if(codex != null && StringUtils.equals(codex.getObjectClass(), "CODEX")){ + CodexTemplate codexTempl = new CodexTemplate(codex, wrapper); + if(StringUtils.isNotEmpty(codexTempl.mpiwgId)){ + URI providedCHO = DM2ECodexConverter.getProvidedCHO(codexTempl, wrapper, g, f); + URI aggregation = DM2ECodexConverter.getAggregation(codexTempl, wrapper, g, f); + g.add(aggregation, EDM.aggregatedCHO, providedCHO); + write(file, output, g); + } + } + + + } + + + + public void convertWitnessList(String file, String output, WrapperService wrapper, Long... list) throws Exception{ + + Model g = new LinkedHashModel(); + ValueFactory f = ValueFactoryImpl.getInstance(); + + for(Long id : list){ + Entity witness = wrapper.getEntityById(id); + + if(witness != null && witness.getObjectClass().equals("WITNESS")){ + WitnessTemplate witnessTempl = new WitnessTemplate(witness, wrapper, true, true); + if(witnessTempl.hasTitle()){ + URI providedCHO = DM2EWitnessConverter.getProvidedCHO(witnessTempl, wrapper, g, f); + URI aggregation = DM2EWitnessConverter.getAggregation(witnessTempl, wrapper, g, f); + g.add(aggregation, EDM.aggregatedCHO, providedCHO); + } + }else{ + + } + } + write(file, output, g); + } + + public void execute0(String file, String output, WrapperService wrapper) throws Exception{ + + Model g = new LinkedHashModel(); + ValueFactory f = ValueFactoryImpl.getInstance(); + + for(Entity witness : wrapper.getEntitiesByDef("WITNESS")){ + WitnessTemplate witnessTempl = new WitnessTemplate(witness, wrapper, true, true); + if(witnessTempl.hasTitle()){ + URI providedCHO = DM2EWitnessConverter.getProvidedCHO(witnessTempl, wrapper, g, f); + URI aggregation = DM2EWitnessConverter.getAggregation(witnessTempl, wrapper, g, f); + g.add(aggregation, EDM.aggregatedCHO, providedCHO); + } + } + write(file, output, g); + } + + private static void write(String file, String output, Model g) throws RDFHandlerException, IOException{ + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + FileOutputStream fos = null; + RDFWriter writer = null; + + if(formatRdfXml.equals(output)){ + writer = Rio.createWriter(RDFFormat.RDFXML, out); + }else if(formatRdfJson.equals(output)){ + writer = Rio.createWriter(RDFFormat.RDFJSON, out); + }else if(formatNTripes.equals(output)){ + writer = Rio.createWriter(RDFFormat.NTRIPLES , out); + } + + writer.startRDF(); + for (Statement st : g) { + writer.handleStatement(st); + } + writer.endRDF(); + + try { + fos = new FileOutputStream (new File(file)); + out.writeTo(fos); + } catch (Exception e) { + e.printStackTrace(); + } finally { + fos.close(); + } + } + + /** + * Execute with maven: + * mvn exec:java -Dexec.mainClass="de.mpiwg.itgroup.dm2e.DM2EConverter" -Dexec.args="/Users/jurzua/ismi_dm2e ntriples" + * @param args + */ + public static void main(String[] args){ + + System.out.println("***************************"); + System.out.println("### DM2EConverter ###"); + + try { + String output = (args.length > 1) ? args[1] : formatNTripes; + + + String folder = DATE_FORMAT.format(new Date()); + folder = args[0] + "/" + folder; + File file = new File(folder); + file.mkdirs(); + + WrapperService wrapper = (new ServiceRegistry()).getWrapper(); + + for(Long codexId : codexIdList){ + convertCodex(folder + "/" + codexId + ".nt", output, codexId, wrapper); + System.out.print("*"); + } + } catch (Exception e) { + e.printStackTrace(); + } + + + /* + Long[] codicesList = {(long) 35093}; + + try { + + + converter.convertCodexList(args[0], output, codexIdList); + + //converter.convertWitnessList(args[0], output, list); + //converter.execute(args[0], output); + } catch (Exception e) { + e.printStackTrace(); + e.printStackTrace(); + } + */ + System.out.println("### Finished ###"); + System.out.println("***************************"); + System.exit(0); + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/dm2e/DM2EUtils.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,21 @@ +package de.mpiwg.itgroup.dm2e; + +import java.net.URLEncoder; + +import org.apache.commons.lang.RandomStringUtils; + +public class DM2EUtils { + + public static String encodeString(String toURI) throws Exception { + toURI = toURI.replaceAll("/|:|<|>|,","_"); + toURI = URLEncoder.encode(toURI,"UTF-8"); + toURI = toURI.replace("+", "_"); + toURI = toURI.replace("__", "_"); + + return toURI; + } + + public static String generateID(){ + return RandomStringUtils.randomAlphabetic(1) + RandomStringUtils.randomAlphanumeric(6); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/dm2e/DM2EWitnessConverter.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,207 @@ +package de.mpiwg.itgroup.dm2e; + +import java.util.Date; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.openrdf.model.Model; +import org.openrdf.model.URI; +import org.openrdf.model.ValueFactory; + +import de.mpiwg.itgroup.dm2e.utils.DM2EUtils; +import de.mpiwg.itgroup.dm2e.utils.EDM; +import de.mpiwg.itgroup.ismi.util.guiComponents.Calendar; +import de.mpiwg.itgroup.ismi.utils.templates.WitnessTemplate; + +public class DM2EWitnessConverter { + + + public static URI getProvidedCHO(WitnessTemplate witnessTempl, + WrapperService wrapper, Model g, ValueFactory f) throws Exception{ + + System.out.println("\tgetProvidedCHO witness: " + witnessTempl.id); + + URI providedCHO = f.createURI(NameSpaces.edmProvidedCHO, witnessTempl.id.toString()); + + // uri edm providedcho + g.add(f.createStatement(providedCHO, URIUtils.rdfType, f.createURI("http://www.europeana.eu/schemas/edm/ProvidedCHO"))); + + //dc:type -> Specialisation of edm:PhysicalThing + g.add(f.createStatement(providedCHO, URIUtils.dcType, DM2E.Manuscript)); + + g.add(f.createStatement(providedCHO, URIUtils.dm2eLevelOfHierarchy, f.createLiteral(1))); + + //edm:type -> Literal + g.add(f.createStatement(providedCHO, URIUtils.edmType, f.createLiteral("TEXT"))); + + String description = getDescription(witnessTempl); + g.add(f.createStatement(providedCHO, URIUtils.dcDescription, f.createLiteral(description))); + + //Literal label = (StringUtils.isNotEmpty(title.lang)) ? f.createLiteral(title.label, title.lang) : f.createLiteral(title.label); + //TODO language of the title?? + g.add(f.createStatement(providedCHO, URIUtils.dcTitle, f.createLiteral(witnessTempl.title))); + + //TODO alternative title, arabic translitareation?? + //g.add(f.createStatement(providedCHO, URIUtils.dctAlternative, label)); + + + if(StringUtils.isNotEmpty(witnessTempl.incipit)) + g.add(f.createStatement(providedCHO, URIUtils.dm2eIncipit, f.createLiteral(witnessTempl.incipit))); + + if(StringUtils.isNotEmpty(witnessTempl.explicit)) + g.add(f.createStatement(providedCHO, URIUtils.dm2eExplicit, f.createLiteral(witnessTempl.explicit))); + + g.add(f.createStatement(providedCHO, URIUtils.dcLanguage, f.createLiteral("ar"))); + + //TODO: Places + + g.add(f.createStatement(providedCHO, URIUtils.dcIdentifier, f.createLiteral(witnessTempl.id.toString()))); + + //dm2eCallNumber + if(StringUtils.isNotEmpty(witnessTempl.codex)) + g.add(f.createStatement(providedCHO, URIUtils.dm2eCallNumber, f.createLiteral(witnessTempl.codex))); + + //g.add(f.createStatement(providedCHO, URIUtils.biboNumPages, f.createLiteral(r.meta.bib.numberOfPages))); + + //g.add(f.createStatement(providedCHO, URIUtils.biboNumVolumes, f.createLiteral(r.meta.bib.numberOfVolumes))); + + //g.add(f.createStatement(providedCHO, URIUtils.dcPublisher, f.createLiteral(publisher))); + + + + //<http://data.dm2e.eu/data/concept/mpiwg/test/520> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2004/02/skos/core#Concept> . + //<http://data.dm2e.eu/data/concept/mpiwg/test/520> <http://www.w3.org/2002/07/owl#sameAs> <http://dewey.info/class/520/about> . + //<http://data.dm2e.eu/data/item/mpiwg/test/MPIWG_WBGMR64C> <http://purl.org/dc/elements/1.1/subject> <http://data.dm2e.eu/data/concept/mpiwg/test/520> + + + if(StringUtils.isNotEmpty(witnessTempl.subject)){ + URI uriConcept = f.createURI("http://data.dm2e.eu/data/concept/mpiwg/authority_ismi/" + witnessTempl.subject); + g.add(f.createStatement(uriConcept, URIUtils.rdfType, URIUtils.skosConcept)); + g.add(f.createStatement(providedCHO, URIUtils.dcSubject, uriConcept)); + g.add(f.createStatement(uriConcept, URIUtils.skosPrefLabel, f.createLiteral(witnessTempl.subject, "en"))); + } + + + AddAgents.execute(g, f, providedCHO, witnessTempl, wrapper); + + //dm2e:writtenAt + + List<Entity> list = wrapper.getTargetsForSourceRelation(witnessTempl.titleId, "was_created_in", "PLACE", 1); + if(list.size() > 0){ + Entity place = list.get(0); + URI uriPlace = f.createURI(NameSpaces.edmPlace + witnessTempl.id + "/" + DM2EUtils.generateID() + "_" + DM2EUtils.encodeString(place.getOwnValue())); + g.add(f.createStatement(uriPlace, f.createURI("http://www.w3.org/2004/02/skos/core#prefLabel"), f.createLiteral(place.getOwnValue(), "en"))); + g.add(f.createStatement(providedCHO, DM2E.publishedAt, uriPlace)); + g.add(f.createStatement(uriPlace, URIUtils.rdfType, URIUtils.edmPlace)); + } + + + //TEXT.creation_date -> dcterms:issued + + Attribute attCreationDate = wrapper.getAttributeByName(witnessTempl.titleId , "creation_date"); + if(attCreationDate != null && StringUtils.isNotEmpty(attCreationDate.getOwnValue())){ + Calendar creationDate = new Calendar(attCreationDate.getOwnValue()); + + if(Calendar.STATE_KNOWN.equals(creationDate.getState())){ + + //"2000-01-01T00:00:00" + String begin = null; + String end = null; + URI timespanIssued = null; + + begin = creationDate.getFromGregorian().getYear() + "-" + + ((creationDate.getFromGregorian().getMonth() < 10) ? "0" + creationDate.getFromGregorian().getMonth() : creationDate.getFromGregorian().getMonth()) + "-" + + ((creationDate.getFromGregorian().getDayOfMonth() < 10) ? "0" + creationDate.getFromGregorian().getDayOfMonth() : creationDate.getFromGregorian().getDayOfMonth()) + "T00:00:00"; + + if(!Calendar.INPUT_FORM_DATE.equals(creationDate.getInputForm())){ + end = creationDate.getUntilGregorian().getYear() + "-" + + ((creationDate.getUntilGregorian().getMonth() < 10) ? "0" + creationDate.getUntilGregorian().getMonth() : creationDate.getUntilGregorian().getMonth()) + "-" + + ((creationDate.getUntilGregorian().getDayOfMonth() < 10) ? "0" + creationDate.getUntilGregorian().getDayOfMonth() : creationDate.getUntilGregorian().getDayOfMonth()) + "T23:59:59"; + + + } + if(StringUtils.isEmpty(end)){ + timespanIssued = f.createURI(NameSpaces.edmTimespan + begin.replace(":", "_") + "UG"); + }else{ + timespanIssued = f.createURI(NameSpaces.edmTimespan + begin.replace(":", "_") + "UG_" + end.replace(":", "_") + "UG"); + g.add(f.createStatement(timespanIssued, URIUtils.edmEnd, f.createLiteral(end, f.createURI("http://www.w3.org/2001/XMLSchema#dateTime")))); + g.add(f.createStatement(timespanIssued, URIUtils.cidocEndQual, f.createLiteral("uncertainty_granularity"))); + } + + g.add(f.createStatement(timespanIssued, URIUtils.rdfType, URIUtils.edmTimeSpan)); + //g.add(f.createStatement(timespanIssued, URIUtils.skosPrefLabel, f.createLiteral(dateString))); + g.add(f.createStatement(timespanIssued, URIUtils.edmBegin, f.createLiteral(begin, f.createURI("http://www.w3.org/2001/XMLSchema#dateTime")))); + g.add(f.createStatement(timespanIssued, URIUtils.cidocBeginQual, f.createLiteral("uncertainty_granularity"))); + g.add(f.createStatement(providedCHO, URIUtils.dctIssued, timespanIssued)); + } + } + + return providedCHO; + } + + public static URI getAggregation(WitnessTemplate witness, + WrapperService wrapper, Model g, ValueFactory f) throws Exception{ + //URI aggregation = f.createURI(NameSpaces.oreAggregation, "MPIWG:" + r.indexMetaId); + URI aggregation = f.createURI(NameSpaces.oreAggregation, witness.id.toString()); + + //edm:provider + URI provider = f.createURI("http://data.dm2e.eu/data/agent/mpiwg/" + NameSpaces.mpiwgCollection + "/DM2E"); + g.add(f.createStatement(aggregation, URIUtils.rdfType, f.createURI("http://www.openarchives.org/ore/terms/Aggregation"))); + g.add(f.createStatement(aggregation, URIUtils.edmProvider, provider)); + g.add(f.createStatement(provider, URIUtils.rdfType, f.createURI("http://xmlns.com/foaf/0.1/Organization"))); + g.add(f.createStatement(provider, URIUtils.skosPrefLabel, f.createLiteral("DM2E", "en"))); + g.add(f.createStatement(provider, URIUtils.skosAltLabel, f.createLiteral("Digitised Manuscripts to Europeana", "en"))); + + //data provider + URI dataProvider = f.createURI("http://data.dm2e.eu/data/agent/mpiwg/" + NameSpaces.mpiwgCollection + "/MPIWG"); + g.add(f.createStatement(aggregation, URIUtils.edmDataProvider, dataProvider)); + g.add(f.createStatement(dataProvider, URIUtils.skosPrefLabel, f.createLiteral("Max Planck Institute for the History of Science", "en"))); + g.add(f.createStatement(dataProvider, URIUtils.skosPrefLabel, f.createLiteral("Max-Planck-Institut für Wissenschaftsgeschichte", "de"))); + g.add(f.createStatement(dataProvider, URIUtils.rdfType, f.createURI("http://xmlns.com/foaf/0.1/Organization"))); + + //edm:rights + g.add(f.createStatement(aggregation, URIUtils.edmRights, f.createURI(DM2EConverter.RIGHTS))); + + //dm2e:displayLevel mandatory + g.add(f.createStatement(aggregation, URIUtils.dm2eDisplayLevel, f.createLiteral(true))); + + //dcterms:created + Entity witnessEnt = wrapper.getEntityById(witness.id); + Date created = new Date(witnessEnt.getModificationTime()); + + g.add(f.createStatement(aggregation, URIUtils.dctCreated, + f.createLiteral(DM2EConverter.timeFormat.format(created), + f.createURI("http://www.w3.org/2001/XMLSchema#dateTime")))); + + addIsShownAt(witness, aggregation, wrapper, g, f); + + return aggregation; + } + + private static URI addIsShownAt(WitnessTemplate witness, URI agg, + WrapperService wrapper, Model g, ValueFactory f) throws Exception{ + + URI ws = f.createURI( + "https://openmind-ismi-dev.mpiwg-berlin.mpg.de/om4-ismi/search/displayTitle.xhtml?witnessId=" + witness.id + "#witnesses"); + + g.add(f.createStatement(ws, f.createURI("http://purl.org/dc/elements/1.1/format"), f.createLiteral("text/html-named-content"))); + g.add(f.createStatement(ws, URIUtils.dcDescription, f.createLiteral("View of witness " + witness.title))); + + //edm:rights [any URL] mandatory + g.add(f.createStatement(ws, EDM.rights, f.createLiteral(DM2EConverter.RIGHTS))); + + g.add(f.createStatement(agg, EDM.isShownAt,ws)); + + g.add(f.createStatement(ws, URIUtils.rdfType, EDM.WebResource)); + + return ws; + } + + private static String getDescription(WitnessTemplate witnessTempl){ + //TODO it can be improved! + return "Manuscript " + witnessTempl.title + " is part of the codex " + witnessTempl.codex + "."; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/dm2e/NameSpaces.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,70 @@ +package de.mpiwg.itgroup.dm2e; + +public class NameSpaces { + + + //URL Schemes + public static String rootDM2E = "http://data.dm2e.eu/data/"; + // collection string right now configured in Testing + //public static String mpiwgCollection = "harriot"; + public static String mpiwgCollection = "ismi"; + + //skos:Concept + public static String skosConcept = rootDM2E + "concept/mpiwg/" + mpiwgCollection + "/"; + //edm:Agent + public static String edmAgent = rootDM2E + "agent/mpiwg/" + mpiwgCollection + "/"; + //edm:Event + public static String edmEvent = rootDM2E + "event/mpiwg/" + mpiwgCollection + "/"; + //edm:ProvidedCHO + public static String edmProvidedCHO = rootDM2E + "item/mpiwg/" + mpiwgCollection + "/"; + //edm:Place + public static String edmPlace = rootDM2E + "place/mpiwg/" + mpiwgCollection + "/" ; + //edm:TimeSpan + public static String edmTimespan = rootDM2E + "timespan/mpiwg/" + mpiwgCollection + "/"; + //ore:Aggregation + public static String oreAggregation = rootDM2E + "aggregation/mpiwg/" + mpiwgCollection + "/"; + + public static String webResource = rootDM2E + "webresource/mpiwg/" + mpiwgCollection + "/"; + + //specialized + public static String oldindexMetaNS = "http://www.mpiwg-berlin.mpg.de/indexMeta/"; + public static String dataProvider = rootDM2E + "agent/mpiwg/" + mpiwgCollection + "/Max%20Planck%20Institute%20For%20The%20History%20Of%20Science"; + public static String provider = rootDM2E + "agent/mpiwg/provider/DM2E"; + + + // namespaces + public static String owl = "http://www.w3.org/2002/07/owl#"; + public static String foaf = "http://xmlns.com/foaf/0.1/"; + public static String rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + public static String rdfs = "http://www.w3.org/2000/01/rdf-schema#"; + + public static String dc = "http://purl.org/dc/elements/1.1/"; + public static String dcterms = "http://purl.org/dc/terms/"; + public static String edm = "http://www.europeana.eu/schemas/edm/"; + public static String ore = "http://www.openarchives.org/ore/terms/"; + public static String skos = "http://www.w3.org/2004/02/skos/core#"; + public static String wgs84 = "http://www.w3.org/2003/01/geo/wgs84_pos#"; + public static String bibo = "http://purl.org/ontology/bibo/"; + public static String pro = "http://purl.org/spar/pro/"; + public static String dm2e10 = "http://onto.dm2e.eu/schemas/dm2e/"; + public static String dm2e = "http://onto.dm2e.eu/schemas/dm2e/"; + public static String korbo = "http://purl.org/net7/korbo/vocab#"; + + // adding all namespaces from owl file + public static String protege = "http://protege.stanford.edu/plugins/owl/protege#"; + public static String vivo = "http://vivoweb.org/ontology/core#"; + public static String swrla = "http://swrl.stanford.edu/ontologies/3.3/swrla.owl#"; + public static String swrlb = "http://www.w3.org/2003/11/swrlb#"; + public static String sqwrl = "http://sqwrl.stanford.edu/ontologies/built-ins/3.4/sqwrl.owl#"; + public static String xsd = "http://www.w3.org/2001/XMLSchema#"; + public static String DOLCELite = "http://www.loa-cnr.it/ontologies/DOLCE-Lite.owl#"; + public static String crm = "http://www.cidoc-crm.org/rdfs/cidoc_crm_v5.0.2_english_label.rdfs#"; + public static String wgs84_pos = "http://www.w3.org/2003/01/geo/wgs84_pos#"; + public static String xsp = "http://www.owl-ontologies.com/2005/08/07/xsp.owl#"; + public static String rdfsvoid = "http://rdfs.org/ns/void#"; + public static String rdaGr2 = "http://rdvocab.info/ElementsGr2/"; + public static String fabio = "http://purl.org/spar/fabio/"; + public static String swrl = "http://www.w3.org/2003/11/swrl#"; + public static String cidoc = "http://www.cidoc-crm.org/cidoc-crm/"; + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/dm2e/URIUtils.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,249 @@ +package de.mpiwg.itgroup.dm2e; + +import org.openrdf.model.URI; +import org.openrdf.model.ValueFactory; +import org.openrdf.model.impl.ValueFactoryImpl; + +public class URIUtils { + + static ValueFactory f; + + static public URI ProvidedCHO; + + //ore:Aggregation + static public URI edmAggregatedCHO; + static public URI edmProvider; + static public URI edmDataProvider; + static public URI edmRights; + static public URI edmHasView; + static public URI edmObject; + static public URI dm2eHasAnnotatableVersionAt; + static public URI dctCreated; + static public URI dctModified; + static public URI dm2eHasVersion; + static public URI dctCreator; + static public URI dm2eDisplayLevel; + static public URI dm2eLevelOfHierarchy; + + //edm:ProvidedCHO + static public URI edmType; + static public URI dcType; + static public URI dcTitle; + //static public URI dctTitle; + static public URI dm2eTitleTransliteration; + static public URI dm2eSubtitle; + static public URI dm2eSubtitleTransliteration; + static public URI dctAlternative; + static public URI dcDescription; + //static public URI dctDescription; + static public URI dcLanguage; + static public URI dctIssued; + static public URI dm2ePublishedAt; + static public URI dcIdentifier; + static public URI dm2eIsbn; + static public URI dm2eCallNumber; + static public URI edmCurrentLocation; + static public URI edmPlace; + //TimeSpan + static public URI edmTimeSpan; + static public URI edmBegin; + static public URI edmEnd; + static public URI cidocBeginQual; + static public URI cidocEndQual; + //static public URI edmRights; + static public URI dcSubject; + static public URI dctExtent; + static public URI biboNumPages; + static public URI biboNumVolumes; + static public URI biboNumber; + static public URI dctTableOfContents; + static public URI dctProvenance; + static public URI dcFormat; + static public URI edmIsDerivativeOf; + static public URI dctHasVersion; + static public URI dctHasPart; + static public URI dctIsPartOf; + static public URI dm2eIsPartOf; + static public URI dm2eLocatedIn; + static public URI dctReferences; + static public URI rdfType; + static public URI dm2eCondition; + static public URI dm2eWatermark; + static public URI dm2eSupport; + static public URI dm2eRestoration; + static public URI dm2eReferencedEdition; + static public URI dm2eReferencedPublication; + static public URI dm2eRelatedPublication; + static public URI dm2eLevelOfGenesis; + static public URI edmHasMet; + static public URI dm2eIncipit; + static public URI dm2eExplicit; + static public URI dm2eColophon; + static public URI dm2ePageDimension; + static public URI dm2eWrittenAreaDimensions; + static public URI dm2eDateOfRemark; + static public URI dm2eRefersTo; + + //personroles + + //static public URI dctCreator; + static public URI dcPublisher; + static public URI dm2eArtist; + static public URI dm2eAuthor; + static public URI dm2eComposer; + static public URI dm2eContributor; + static public URI dm2eCopyist; + static public URI dm2eCopyrightHolder; + static public URI dm2eEditor; + static public URI dm2eHonoree; + static public URI dm2eIllustrator; + static public URI dm2eLibrary; + static public URI dm2eMentionedPerson; + static public URI dm2eMisattributedPerson; + static public URI dm2ePainter; + static public URI dm2ePatron; + static public URI dm2ePortrayedPerson; + static public URI dm2ePortrayed; + static public URI dm2ePrinter; + static public URI dm2ePublisher; + static public URI dm2eRecipient; + static public URI dm2eSponsor; + static public URI dm2eStaff; + static public URI dm2eSubjectOf; + static public URI dm2eTranslator; + static public URI dm2eWriter; + + static public URI dcContributor; + static public URI biboEditor; + static public URI biboRecipient; + static public URI proIllustrator; + static public URI proAuthor; + static public URI proTranslator; + + static public URI skosPrefLabel; + static public URI skosAltLabel; + static public URI skosConcept; + + static{ + f = ValueFactoryImpl.getInstance(); + + //ore:Aggregation + edmAggregatedCHO = f.createURI(NameSpaces.edm + "aggregatedCHO"); + edmProvider = f.createURI(NameSpaces.edm + "provider"); + edmDataProvider = f.createURI(NameSpaces.edm + "dataProvider"); + edmRights = f.createURI(NameSpaces.edm + "rights"); + edmHasView = f.createURI(NameSpaces.edm + "hasView"); + edmObject = f.createURI(NameSpaces.edm + "object"); + + dm2eHasAnnotatableVersionAt = f.createURI(NameSpaces.dm2e + "hasAnnotatableVersionAt"); + dctCreated = f.createURI(NameSpaces.dcterms + "created"); + dctModified = f.createURI(NameSpaces.dcterms + "modified"); + dm2eHasVersion = f.createURI(NameSpaces.dm2e + "hasVersion"); + dctCreator = f.createURI(NameSpaces.dcterms + "creator"); + dm2eDisplayLevel = f.createURI(NameSpaces.dm2e + "displayLevel"); + dm2eLevelOfHierarchy = f.createURI(NameSpaces.dm2e + "levelOfHierarchy"); + + //edm:ProvidedCHO + edmType = f.createURI(NameSpaces.edm + "type"); + dcType = f.createURI(NameSpaces.dc + "type"); + dcTitle = f.createURI(NameSpaces.dc + "title"); + // dctTitle = f.createURI(NameSpaces.dcterms + "title"); + dm2eTitleTransliteration = f.createURI(NameSpaces.dm2e + "titleTransliteration"); + dm2eSubtitle = f.createURI(NameSpaces.dm2e + "subtitle"); + dm2eSubtitleTransliteration = f.createURI(NameSpaces.dm2e + "subtitleTransliteration"); + dctAlternative = f.createURI(NameSpaces.dcterms + "alternative"); + dcDescription = f.createURI(NameSpaces.dc + "description"); + //dctDescription = f.createURI(NameSpaces.dcterms + "description"); + dcLanguage = f.createURI(NameSpaces.dc + "language"); + dctIssued = f.createURI(NameSpaces.dcterms + "issued"); + dm2ePublishedAt = f.createURI(NameSpaces.dm2e + "publishedAt"); + dcIdentifier = f.createURI(NameSpaces.dc + "identifier"); + dm2eIsbn = f.createURI(NameSpaces.dm2e + "isbn"); + dm2eCallNumber = f.createURI(NameSpaces.dm2e + "callNumber"); + edmCurrentLocation = f.createURI(NameSpaces.edm + "currentLocation"); + edmPlace = f.createURI(NameSpaces.edm + "Place"); + //TimeSpan + edmTimeSpan = f.createURI(NameSpaces.edm + "timeSpan"); + edmBegin = f.createURI(NameSpaces.edm + "begin"); + edmEnd = f.createURI(NameSpaces.edm + "end"); + cidocBeginQual = f.createURI(NameSpaces.cidoc + "P79F.beginning_is_qualified_by"); + cidocEndQual = f.createURI(NameSpaces.cidoc + "P80F.end_is_qualified_by"); + //edmRights; + dcSubject = f.createURI(NameSpaces.dc + "subject"); + dctExtent = f.createURI(NameSpaces.dcterms + "extent"); + biboNumPages = f.createURI(NameSpaces.bibo + "numPages"); + biboNumVolumes = f.createURI(NameSpaces.bibo + "numVolumes"); + biboNumber = f.createURI(NameSpaces.bibo + "number"); + dctTableOfContents = f.createURI(NameSpaces.dcterms + "tableOfContents"); + dctProvenance = f.createURI(NameSpaces.dcterms + "provenance"); + dcFormat = f.createURI(NameSpaces.dc + "format"); + edmIsDerivativeOf = f.createURI(NameSpaces.edm + "isDerivativeOf"); + dctHasVersion = f.createURI(NameSpaces.dcterms + "hasVersion"); + dctHasPart = f.createURI(NameSpaces.dcterms + "hasPart"); + dctIsPartOf = f.createURI(NameSpaces.dcterms + "isPartOf"); +// dm2eIsPartOf = f.createURI(NameSpaces.dm2e + "isPartOf"); + dm2eLocatedIn = f.createURI(NameSpaces.dm2e + "locatedIn"); + dctReferences = f.createURI(NameSpaces.dcterms + "references"); + rdfType = f.createURI(NameSpaces.rdf + "type"); + dm2eCondition = f.createURI(NameSpaces.dm2e + "condition"); + dm2eWatermark = f.createURI(NameSpaces.dm2e + "watermark"); + dm2eSupport = f.createURI(NameSpaces.dm2e + "support"); + dm2eRestoration = f.createURI(NameSpaces.dm2e + "restoration"); + dm2eReferencedEdition = f.createURI(NameSpaces.dm2e + "referencedEdition"); + dm2eReferencedPublication = f.createURI(NameSpaces.dm2e + "referencedPublication"); + dm2eRelatedPublication = f.createURI(NameSpaces.dm2e + "relatedPublication"); + dm2eLevelOfGenesis = f.createURI(NameSpaces.dm2e + "levelOfGenesis"); + edmHasMet = f.createURI(NameSpaces.edm + "hasMet"); + dm2eIncipit = f.createURI(NameSpaces.dm2e + "incipit"); + dm2eExplicit = f.createURI(NameSpaces.dm2e + "explicit"); + dm2eExplicit = f.createURI(NameSpaces.dm2e + "explicit"); + dm2ePageDimension = f.createURI(NameSpaces.dm2e + "pageDimension"); + dm2eWrittenAreaDimensions = f.createURI(NameSpaces.dm2e + "writtenAreaDimensions"); + dm2eDateOfRemark = f.createURI(NameSpaces.dm2e + "dateOfRemark"); + dm2eRefersTo = f.createURI(NameSpaces.dm2e + "refersTo"); + + //personroles + + //dctCreator = f.createURI(NameSpaces.dc + ""); + dcPublisher = f.createURI(NameSpaces.dc + "publisher"); + dm2eArtist = f.createURI(NameSpaces.dm2e + "artist"); + dm2eAuthor = f.createURI(NameSpaces.dm2e + "author"); + dm2eComposer = f.createURI(NameSpaces.dm2e + "composer"); + dm2eContributor = f.createURI(NameSpaces.dm2e + "contributor"); + dm2eCopyist = f.createURI(NameSpaces.dm2e + "copyist"); + dm2eCopyrightHolder = f.createURI(NameSpaces.dm2e + "copyist"); + dm2eEditor = f.createURI(NameSpaces.dm2e + "editor"); + dm2eHonoree = f.createURI(NameSpaces.dm2e + "honoree"); + dm2eIllustrator = f.createURI(NameSpaces.dm2e + "illustrator"); + dm2eLibrary = f.createURI(NameSpaces.dm2e + "illustrator"); + dm2eMentionedPerson = f.createURI(NameSpaces.dm2e + "mentionedPerson"); + dm2eMisattributedPerson = f.createURI(NameSpaces.dm2e + "mentionedPerson"); + dm2ePainter = f.createURI(NameSpaces.dm2e + "painter"); + dm2ePatron = f.createURI(NameSpaces.dm2e + "patron"); + dm2ePortrayedPerson = f.createURI(NameSpaces.dm2e + "portrayedPerson"); + dm2ePortrayed = f.createURI(NameSpaces.dm2e + "portrayed"); + dm2ePrinter = f.createURI(NameSpaces.dm2e + "printer"); + dm2ePublisher = f.createURI(NameSpaces.dm2e + "printer"); + dm2eRecipient = f.createURI(NameSpaces.dm2e + "recipient"); + dm2eSponsor = f.createURI(NameSpaces.dm2e + "sponsor"); + dm2eStaff = f.createURI(NameSpaces.dm2e + "staff"); + dm2eSubjectOf = f.createURI(NameSpaces.dm2e + "subjectOf"); + dm2eTranslator = f.createURI(NameSpaces.dm2e + "translator"); + dm2eWriter = f.createURI(NameSpaces.dm2e + "writer"); + + proAuthor = f.createURI(NameSpaces.pro + "author"); + dcContributor = f.createURI(NameSpaces.dc + "contributor"); + biboEditor = f.createURI(NameSpaces.bibo + "editor"); + biboRecipient = f.createURI(NameSpaces.bibo + "recipient"); + proIllustrator = f.createURI(NameSpaces.pro + "illustrator"); + proTranslator = f.createURI(NameSpaces.pro + "translator"); + + skosPrefLabel = f.createURI(NameSpaces.skos + "prefLabel"); + skosAltLabel = f.createURI(NameSpaces.skos + "altLabel"); + skosConcept = f.createURI(NameSpaces.skos + "Concept"); + } + + + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/dm2e/utils/DM2EUtils.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,18 @@ +package de.mpiwg.itgroup.dm2e.utils; + +import java.net.URLEncoder; + +import org.apache.commons.lang.RandomStringUtils; + +public class DM2EUtils { + + public static String encodeString(String toURI) throws Exception { + toURI = toURI.replaceAll("/|:|<|>|,", "_"); + toURI = URLEncoder.encode(toURI, "UTF-8"); + return toURI.replace("+", "_"); + } + + public static String generateID(){ + return RandomStringUtils.randomAlphabetic(1) + RandomStringUtils.randomAlphanumeric(6); + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/dm2e/utils/EDM.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,94 @@ +package de.mpiwg.itgroup.dm2e.utils; + +import org.openrdf.model.URI; +import org.openrdf.model.ValueFactory; +import org.openrdf.model.impl.ValueFactoryImpl; + +public class EDM { + + static ValueFactory f; + + static public String edm; + + //classes + public static URI Agent; + public static URI EuropeanaAggregation; + public static URI EuropeanaObject; + public static URI Event; + public static URI InformationResource; + public static URI NonInformationResource; + public static URI PhysicalThing; + public static URI Place; + public static URI ProvidedCHO; + public static URI TimeSpan; + public static URI WebResource; + + //properties + public static URI aggregatedCHO; + public static URI currentLocation; + public static URI happenedAt; + public static URI hasMet; + public static URI hasType; + public static URI hasView; + public static URI incorporates; + public static URI isAnnotationOf; + public static URI isDerivativeOf; + public static URI isNextInSequence; + public static URI isRelatedTo; + public static URI isRepresentationOf; + public static URI isSimilarTo; + public static URI isSuccessorOf; + public static URI landingPage; + public static URI occurredAt; + public static URI realizes; + public static URI wasPresentAt; + + static public URI isShownBy; + static public URI isShownAt; + static public URI object; + public static URI rights; + + static{ + + f = ValueFactoryImpl.getInstance(); + + edm = "http://www.europeana.eu/schemas/edm/"; + + Agent = f.createURI(edm + "Agent"); + EuropeanaAggregation = f.createURI(edm + "EuropeanaAggregation"); + EuropeanaObject = f.createURI(edm + "EuropeanaObject"); + Event = f.createURI(edm + "Event"); + InformationResource = f.createURI(edm + "InformationResource"); + NonInformationResource = f.createURI(edm + "NonInformationResource"); + PhysicalThing = f.createURI(edm + "PhysicalThing"); + Place = f.createURI(edm + "Place"); + ProvidedCHO = f.createURI(edm + "ProvidedCHO"); + TimeSpan = f.createURI(edm + "TimeSpan"); + WebResource = f.createURI(edm + "WebResource"); + + + aggregatedCHO = f.createURI(edm + "aggregatedCHO"); + currentLocation = f.createURI(edm + "currentLocation"); + happenedAt = f.createURI(edm + "happenedAt"); + hasMet = f.createURI(edm + "hasMet"); + hasType = f.createURI(edm + "hasType"); + hasView = f.createURI(edm + "hasView"); + incorporates = f.createURI(edm + "incorporates"); + isAnnotationOf = f.createURI(edm + "isAnnotationOf"); + isDerivativeOf = f.createURI(edm + "isDerivativeOf"); + isNextInSequence = f.createURI(edm + "isNextInSequence"); + isRelatedTo = f.createURI(edm + "isRelatedTo"); + isRepresentationOf = f.createURI(edm + "isRepresentationOf"); + isSimilarTo = f.createURI(edm + "isSimilarTo"); + isSuccessorOf = f.createURI(edm + "isSuccessorOf"); + landingPage = f.createURI(edm + "landingPage"); + occurredAt = f.createURI(edm + "occurredAt"); + realizes = f.createURI(edm + "realizes"); + wasPresentAt = f.createURI(edm + "wasPresentAt"); + + isShownBy = f.createURI(edm + "isShownBy"); + isShownAt = f.createURI(edm + "isShownAt"); + object = f.createURI(edm + "object"); + rights = f.createURI(edm + "rights"); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/echo/jsp/ECHOViewer.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,86 @@ +package de.mpiwg.itgroup.echo.jsp; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class ECHOViewer { + + + private static String SCALER_WS = "http://digilib.mpiwg-berlin.mpg.de/digitallibrary/servlet/Scaler?fn=permanent/library/WWKYPR05/pageimg"; //&dw=1639&dh=376 + + private static String PAGES_WS = "http://digilib.mpiwg-berlin.mpg.de/digitallibrary/dirInfo-xml.jsp?fn=/permanent/library/UR271U6Y/pageimg"; + + private String currentId = "BVED1RUM"; + private int pageSize; + private int currentPage; + + private static List<String> scanList; + + static{ + String[] scansList0 = { + "BVED1RUM", + "M9XBU92T", + "RNEZE8Z6", + "2BPAV5AP", + "7T85HQNS", + "TRQNNGSR", + "S1C20QWU", + "8XWYTZ26", + "6UZB2ZF0", + "M0XAYXH0", + "2EBGM67W", + "NXDAZZYU", + "MWG2QDZ9", + "B47T3HY2", + "FM05UE82", + "UGTHY0RG", + "4UZFR41E", + "2AG56K0B", + "1T0Z5TU5", + "QQVPRVXX", + "RUK8AFQP", + "ERZHST5Y", + "5MB6HBYV", + "5AN0VGK8", + "0SWBP6BQ", + "CC2KDXXX", + "YB4U050C", + "WTC2BK80", + "KNA1AZYB", + "1M75N53E", + "WRQEXG1A", + "409E3DCG", + "XQH10RER", + "DX904FN7", + "GEWZ52P2", + "U6BC9X7F", + "VREYNH8W", + "QW00YZFR", + "4ZPFQTN0", + "6631A2R6" + }; + scanList = Arrays.asList(scansList0); + } + + + + + public int getPageSize() { + return pageSize; + } + + public void setPageSize(int pageSize) { + this.pageSize = pageSize; + } + + public int getCurrentPage() { + return currentPage; + } + + public void setCurrentPage(int currentPage) { + this.currentPage = currentPage; + } +} + +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/admin/AdminBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,185 @@ +package de.mpiwg.itgroup.ismi.admin; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.security.bo.User; +import org.mpiwg.itgroup.escidoc.bo.ESciDocItem; + + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; + +public class AdminBean extends AbstractISMIBean{ + + public static String Administrator = "Administrator"; + public static String Researcher = "Researcher"; + public static String Student = "Student"; + + private static List<SelectItem> roleList = new ArrayList<SelectItem>(); + static{ + roleList.add(new SelectItem(Administrator)); + roleList.add(new SelectItem(Researcher)); + roleList.add(new SelectItem(Student)); + } + + public AdminBean(){ + this.reset(); + } + + private User user; + private List<User> userList; + + private String userEmail; + private String userName; + + private String password1; + private String password2; + private boolean changePassword; + + private boolean showESciDocPanelControl = false; + + public void listenerOpenESciDocPanelControl(ActionEvent event){ + this.showESciDocPanelControl = true; + } + + public void listenerCloseESciDocPanelControl(ActionEvent event){ + this.showESciDocPanelControl = false; + } + + public boolean isShowESciDocPanelControl() { + return showESciDocPanelControl & getSessionBean().isAdmin(); + } + + public void reset(){ + this.user = null; + this.password1 = new String(); + this.password2 = new String(); + this.changePassword = false; + this.userEmail = new String(); + this.userName = new String(); + } + + public void actionCreateUser(ActionEvent event){ + this.user = new User(); + this.user.setRole(Researcher); + this.changePassword = true; + this.userList = new ArrayList<User>(); + } + + public void actionEditUser(ActionEvent event){ + this.user = (User)getRequestBean("item"); + this.changePassword = false; + this.userList = new ArrayList<User>(); + } + + public void actionRemoveUser(ActionEvent event){ + User user0 = (User)getRequestBean("item"); + getSecurityService().deleteUser(user0); + this.userList = getSecurityService().getAllUsers(); + } + + public void actionReset(ActionEvent event){ + reset(); + } + + public void actionGetAllUsers(ActionEvent event){ + this.userList = getSecurityService().getAllUsers(); + this.user = null; + + } + + public void actionSaveUser(ActionEvent event){ + boolean valid = true; + if(changePassword && (StringUtils.isEmpty(password1) || + StringUtils.isEmpty(password2) || + !password1.equals(password2))){ + valid = false; + addErrorMsg("The passwords are different or at least one is empty"); + } + + User otherUser = getSecurityService().getUserByEmail(user.getEmail()); + + //TODO check email + + if(!user.isPersistent() && otherUser != null){ + addErrorMsg("The email is the key and should be unique. A user already exists with this email."); + valid = false; + }else if(user.isPersistent() && otherUser != null && !otherUser.getId().equals(user.getId())){ + addErrorMsg("Other user is using this email."); + valid = false; + } + + if(valid){ + if(!user.isPersistent()){ + user.setPassword(password1); + } + getSecurityService().saveUser(user); + this.changePassword = false; + this.user = null; + this.userList = getSecurityService().getAllUsers(); + } + + } + + + public User getUser() { + return user; + } + public void setUser(User user) { + this.user = user; + } + public List<User> getUserList() { + return userList; + } + public void setUserList(List<User> userList) { + this.userList = userList; + } + + public List<SelectItem> getRoleList(){ + return roleList; + } + + public String getPassword1() { + return password1; + } + + public void setPassword1(String password1) { + this.password1 = password1; + } + + public String getPassword2() { + return password2; + } + + public void setPassword2(String password2) { + this.password2 = password2; + } + + public boolean isChangePassword() { + return changePassword; + } + + public void setChangePassword(boolean changePassword) { + this.changePassword = changePassword; + } + + public String getUserEmail() { + return userEmail; + } + + public void setUserEmail(String userEmail) { + this.userEmail = userEmail; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/auxObjects/AbstractListenerObject.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,182 @@ +package de.mpiwg.itgroup.ismi.auxObjects; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractBean; +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; +import de.mpiwg.itgroup.ismi.util.guiComponents.StatusImage; + +public abstract class AbstractListenerObject extends AbstractBean{ + + private static final long serialVersionUID = -7874914085766225119L; + private static int MAX_SUGGEST = 25; + + public List<SelectItem> suggestedItems = new ArrayList<SelectItem>(); + public transient StatusImage statusImage = new StatusImage(); + public Attribute attribute = new Attribute(); + public Entity entity = new Entity(); + public String entityInfo; + + protected void changeListener( + ValueChangeEvent event, + String suggestType, + String suggestAttributeName) { + + changeListener( + event, + suggestType, + suggestAttributeName, + null, + null); + } + + protected void changeListener( + ValueChangeEvent event, + String suggestType, + String suggestAttributeName, + String restrictingAttributeName, + String restrictingAttributeValue) { + + try { + if (event.getNewValue() == null) { + return; + }else if(StringUtils.isEmpty(event.getNewValue().toString()) && (event.getOldValue() == null || StringUtils.isEmpty(event.getOldValue().toString()))){ + //if the old and new value are empty, then return + return; + } + if (event.getNewValue().equals(event.getOldValue())) { + return; + } + + String ownvalue = (String) event.getNewValue(); + + if(StringUtils.isEmpty(ownvalue)) + statusImage.setStatus(StatusImage.STATUS_UNSET); + else + statusImage.setStatus(StatusImage.STATUS_FALSE); + + this.entity = null; + // setze erst mal den Eigenwert auf das eingebene. + Attribute at = new Attribute(); + at.setOwnValue(ownvalue); + attribute = at; + for (SelectItem item : this.suggestedItems) { + if (StringUtils.isNotEmpty(item.getLabel()) && + item.getLabel().equals(ownvalue)) { + //System.out.println("item.getValue()= " + item.getValue()); + this.attribute = (Attribute) item.getValue(); + Entity element = getWrapper().getEntityById( + this.attribute.getSourceId()); + + if (element != null) { + if(element.isLightweight()){ + element = getWrapper().getEntityByIdWithContent(element.getId()); + } + entity = element; + statusImage.setStatus(StatusImage.STATUS_OK); + } + break; + } + + } + + if (restrictingAttributeName == null) { + suggestedItems = this.updateSuggestedItems(event, + suggestType, suggestAttributeName); + } else { + suggestedItems = this.updateSuggestedItems(suggestType, + suggestAttributeName, event.getNewValue().toString(), + restrictingAttributeName, restrictingAttributeValue); + } + + } catch (Exception e) { + e.printStackTrace(); + } + return; + } + + protected List<SelectItem> updateSuggestedItems(String objClass, + String firstName, String firstValue, String secondName, + String secondValue) { + + List<Attribute> attList = getWrapper(). + searchAttribute(firstName, firstValue, secondName, secondValue, objClass, MAX_SUGGEST); + + List<SelectItem> suggestedItems = new ArrayList<SelectItem>(); + if (attList == null) + return suggestedItems; + + for (Attribute att : attList) { + SelectItem item = new SelectItem(att, att.getOwnValue() + " [" + att.getSourceId() + "]"); + suggestedItems.add(item); + } + return suggestedItems; + } + + protected List<SelectItem> updateSuggestedItems(ValueChangeEvent event, + String objClass, String attName) { + return updateSuggestedItems((String) event.getNewValue(), objClass, + attName); + } + + protected List<SelectItem> updateSuggestedItems(String searchWord, + String objClass, String attName) { + + List<Attribute> attList = getWrapper().getAttributesByDefByAttName(objClass, attName, searchWord.toString(), MAX_SUGGEST); + + List<SelectItem> suggestedItems = new ArrayList<SelectItem>(); + if (attList == null) + return suggestedItems; + + for (Attribute att : attList) { + SelectItem item = new SelectItem(att, att.getOwnValue() + " [" + att.getSourceId() + "]", + "description: " + att); + suggestedItems.add(item); + } + return suggestedItems; + } + + public void setEntity(Entity ent) { + this.entity = ent; + if(ent != null && ent.isPersistent()){ + if(this.entity.isLightweight()){ + this.entity = getWrapper().getEntityByIdWithContent(this.entity.getId()); + } + this.setStatus(StatusImage.STATUS_OK); + this.entityInfo = "ID = " + this.entity.getId(); + /* + if(classObj.equals("PERSON")){ + Attribute attArabicName = getTargetAttribute(ent, "name"); + if(attArabicName != null){ + this.authorInfo += ", Arabic Name = " + attArabicName.getOwnValue(); + this.textAuthorName = attArabicName.getValue(); + } + + if(this.authorLo.attribute != null){ + this.textAuthorNameTranslit = this.authorLo.attribute.getValue(); + } + } + */ + }else{ + this.setStatus(StatusImage.STATUS_UNSET); + } + } + + public void setStatus(String newStatus){ + statusImage.setStatus(newStatus); + } + + protected WrapperService getWrapper() { + ApplicationBean app = (ApplicationBean) getApplicationBean("ApplicationBean1"); + return app.getWrapper(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/auxObjects/AllCodices.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,41 @@ +//Codex Object gibt vorschlaege fue codices fuer die eingabe und das editieren. +package de.mpiwg.itgroup.ismi.auxObjects; + +import java.util.List; + +import javax.faces.model.SelectItem; + +public class AllCodices { + + private List<SelectItem> countries; + private List<SelectItem> cities; + private List<SelectItem> repositories; + private List<SelectItem> collections; + + public List<SelectItem> getCountries() { + return countries; + } + public void setCountries(List<SelectItem> countries) { + this.countries = countries; + } + public List<SelectItem> getCities() { + return cities; + } + public void setCities(List<SelectItem> cities) { + this.cities = cities; + } + public List<SelectItem> getRepositories() { + return repositories; + } + public void setRepositories(List<SelectItem> repositories) { + this.repositories = repositories; + } + public List<SelectItem> getCollections() { + return collections; + } + public void setCollections(List<SelectItem> collections) { + this.collections = collections; + } + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/auxObjects/DisplayEntity.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,45 @@ +package de.mpiwg.itgroup.ismi.auxObjects; + +//import org.mpi.openmind.repository.bo.Entity; + +import org.mpi.openmind.repository.bo.Entity; + + +/** + * @author dwinter + * Hilfsklasse fuer die Ausgabe von Suchresultaten. In der Regel sollte der + * Eigenwert eines Objektes angezeigt, werden dieser ist jedoch manchmal leer. + * #TODO: Eine entsprechenden Methode sollte in Entity selbst implementiert werden. + */ +public class DisplayEntity { + + private Entity ent; + + public DisplayEntity(Entity entity) { + ent=entity; + } + + public String getDisplayValue(){ + + if (!ent.getOwnValue().equals("")) + return ent.getOwnValue(); + + /*[upgrade] + if (ent.getObjectClass().equals("PERSON")) + return ent.getAttribute("name_translit").getValue(); + + if (ent.getObjectClass().equals("TEXT")) + return ent.getAttribute("title_translit").getValue(); + */ + return ""; + } + public void setEnt(Entity ent) { + this.ent = ent; + } + + public Entity getEnt() { + return ent; + } + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/auxObjects/ListenerObject.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,234 @@ +package de.mpiwg.itgroup.ismi.auxObjects; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; +import de.mpiwg.itgroup.ismi.util.guiComponents.StatusImage; + +public class ListenerObject extends AbstractListenerObject{ + private static final long serialVersionUID = 9156066826135642525L; + + public String classObj; + public String attName; + public String term; + private boolean renderInfo = false; + + + public ListenerObject(){} + + public ListenerObject(String classObj, String attName){ + this.classObj = classObj; + this.attName = attName; + } + + /** + * When the term is changed in the inputtext, + * this method will be called to change teh suggestion list. + * @param event + */ + public void valueChangeMethod(ValueChangeEvent event) { + this.entityInfo = null; + changeListener(event, classObj, attName); + if(classObj.equals("PERSON")){ + /* + if(authorLo != null && authorLo.entity != null && authorLo.entity.isPersistent()){ + this.authorInfo = "ID = " + authorLo.getEntity().getId(); + Attribute attArabicName = getTargetAttribute(authorLo.entity, "name_translit"); + if(attArabicName != null) + this.authorInfo += ", Arabic Name = " + attArabicName.getOwnValue(); + } + */ + } + } + + public void actionListenerSelect(ActionEvent event){ + + this.suggestedItems = new ArrayList<SelectItem>(); + SelectItem selectItem = (SelectItem) getRequestBean("item"); + if(selectItem != null){ + Attribute att = (Attribute)selectItem.getValue(); + + Entity ent = getWrapper().getEntityById(att.getSourceId()); + + if(ent != null){ + this.setEntityAndAttribute0(ent); + } + } + } + + public void onClick(){ + if(!this.equalsTermEntity()){ + this.suggestedItems = new ArrayList<SelectItem>(); + this.statusImage = new StatusImage(); + this.attribute = new Attribute(); + this.entity = new Entity(); + } + } + + public void reset(){ + this.suggestedItems = new ArrayList<SelectItem>(); + this.statusImage = new StatusImage(); + this.attribute = new Attribute(); + this.entity = new Entity(); + this.term = null; + } + + public String getDisplayUrl(){ + Entity ent = getEntity(); + if(ent.isPersistent()){ + if(ent.getObjectClass().equals("PERSON")){ + return AbstractISMIBean.generateDisplayUrl(ent, null, null, getAppBean().getRoot()); + } + else if(ent.getObjectClass().equals("TEXT")){ + return AbstractISMIBean.generateDisplayUrl(null, ent, null, getAppBean().getRoot()); + }else if(ent.getObjectClass().equals("WITNESS")){ + return AbstractISMIBean.generateDisplayUrl(null, null, ent, getAppBean().getRoot()); + } + } + return null; + } + + public ListenerObject(List<SelectItem> suggestedItemsNew, + Attribute attributeNew, Entity entityNew) { + suggestedItems = suggestedItemsNew; + attribute = attributeNew; + entity = entityNew; + } + + public List<SelectItem> getSuggestedItems() { + return suggestedItems; + } + + public void setSuggestedItems(List<SelectItem> suggestedItems) { + this.suggestedItems = suggestedItems; + } + + public Attribute getAttribute() { + return attribute; + } + + public void setAttribute(Attribute attribute) { + this.attribute = attribute; + } + + public Entity getEntity() { + if (entity==null) + return new Entity(); + return entity; + } + + public StatusImage getStatusImage() { + return statusImage; + } + + public void setStatusImage(StatusImage statusImage) { + this.statusImage = statusImage; + } + + public void invalidate(){ + if (attribute==null || attribute.getOwnValue().equals("")) + statusImage.setStatus("unset"); + else + statusImage.setStatus("false"); + } + public String getStatus(){ + return statusImage.getStatus(); + } + + public void setEntityAndAttribute0(Entity ent){ + this.setEntity(ent); + if(ent != null && ent.isPersistent()){ + this.attribute = getWrapper().getAttributeByName(ent.getId(), this.attName); + if(this.attribute != null && StringUtils.isNotEmpty(this.attribute.getOwnValue())){ + term = attribute.getOwnValue() + " [" + entity.getId() + "]"; + }else{ + term = this.entity.getOwnValue() + "[" + entity.getId() + "]"; + } + } + } + + public void setEntityAndAttribute(Entity ent, String attName){ + this.attName = attName; + this.setEntityAndAttribute0(ent); + } + + public boolean equalsTermEntity(){ + if(StringUtils.isEmpty(term)){ + return false; + } + if(attribute != null){ + return StringUtils.equals( + attribute.getOwnValue() + " [" + attribute.getSourceId() + "]", term); + }else if(entity != null){ + return StringUtils.equals(entity.getOwnValue() + "[" + entity.getId() + "]", term); + } + return false; + } + + @Override + public String toString(){ + String s = new String(); + s += "LO: " + this.statusImage.getStatus(); + s += (this.entity != null) ? "[" + entity.getObjectClass() + ": " + entity.getOwnValue() + "] " : ""; + s += (this.attribute != null) ? "[" + attribute.getName() + ": " + attribute.getValue() + "]" : ""; + return s; + } + + public String getTerm() { + if(this.entity != null && entity.isPersistent()){ + if(attribute != null && StringUtils.isNotEmpty(attribute.getOwnValue())){ + term = attribute.getOwnValue() + " [" + entity.getId() + "]"; + }else{ + term = this.entity.getOwnValue() + "[" + entity.getId() + "]"; + } + } + return term; + } + + public void setTerm(String term) { + this.term = term; + } + + public String getEntityInfo() { + return entityInfo; + } + + public void setEntityInfo(String entityInfo) { + this.entityInfo = entityInfo; + } + + public String getClassObj() { + return classObj; + } + + public void setClassObj(String classObj) { + this.classObj = classObj; + } + + public String getAttName() { + return attName; + } + + public void setAttName(String attName) { + this.attName = attName; + } + + public boolean isRenderInfo() { + if(entity == null || !entity.isPersistent()) + return false; + return renderInfo; + } + + public void setRenderInfo(boolean renderInfo) { + this.renderInfo = renderInfo; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/auxObjects/ResultSet.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,96 @@ +package de.mpiwg.itgroup.ismi.auxObjects; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; + +//[upgrade]import org.mpi.openmind.repository.bo.Entity; + +/** + * @author jurzua + * + * change [25.06.2010-jurzua] replace results and attributes with a tuple entity-att + * + * TODO analyze if the attribute is necessary... I think the description should be enough. + * + */ +public class ResultSet implements Serializable{ + + private static final long serialVersionUID = -6799519951054874744L; + + private String name; + private List<Entity> results = new ArrayList<Entity>(); + private Map<Long, Attribute> attMap = new HashMap<Long, Attribute>(); + private Map<Long, String> descriptionMap = new HashMap<Long, String>(); + + public void setTuple(Entity ent, Attribute att){ + if(!this.results.contains(ent)){ + this.results.add(ent); + } + this.attMap.put(ent.getId(), att); + } + + public void setDescription(Long id, String desc){ + this.descriptionMap.put(id, desc); + } + public void setDescription(Entity ent, String desc){ + this.descriptionMap.put(ent.getId(), desc); + } + + public ResultSet(String ot) { + name=ot; + } + + /** + * @return Results set als Array of DisplayEntity. + * Array is needed because the DataTable-Object of ICEFaces expects arrays and not Lists. + */ + public DisplayEntity[] getResultsArray() { + DisplayEntity[] retArray = new DisplayEntity[results.size()]; + + int i = 0; + for(Entity ent : results){ + retArray[i] = new DisplayEntity(ent); + i++; + } + + return retArray; + } + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List<Entity> getResults() { + return results; + } + + public void setResults(List<Entity> results) { + this.results = results; + } + + public Map<Long, Attribute> getAttMap() { + return attMap; + } + + public void setAttMap(Map<Long, Attribute> attMap) { + this.attMap = attMap; + } + + public Map<Long, String> getDescriptionMap() { + return descriptionMap; + } + + public void setDescriptionMap(Map<Long, String> descriptionMap) { + this.descriptionMap = descriptionMap; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/auxObjects/SelectItem0.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,95 @@ +package de.mpiwg.itgroup.ismi.auxObjects; + +import java.util.List; + +import javax.faces.model.SelectItem; + +public class SelectItem0 extends SelectItem{ + + private static final long serialVersionUID = -3590260852460547911L; + + private boolean selected = false; + private static Short needVerification = 0; + private static Short verificatedByCatalogue = 1; + private static Short verificatedByWitness = 2; + private Short verification = needVerification; + private boolean isWitness = false; + + @Override + public String toString(){ + return "SelectItem0 [" + selected + "] " + getLabel(); + } + + public SelectItem0(Object value, String label){ + super(value, label); + } + + public SelectItem0(Object value, String label, boolean isWitness){ + super(value, label); + this.isWitness = isWitness; + } + + public void select(){ + this.selected = true; + } + + public void deselect(){ + this.selected = false; + } + + public void needVerification(){ + this.verification = needVerification; + } + + public void verificatedByCatalogue(){ + this.verification = verificatedByCatalogue; + } + + public void verificatedByWitness(){ + this.verification = verificatedByWitness; + + } + + public static List<SelectItem0> valueChange(List<SelectItem0> list, Long id){ + for(SelectItem0 item : list){ + try { + Long itemId = (Long)item.getValue(); + if(itemId.equals(id)){ + item.select(); + }else{ + item.deselect(); + } + } catch (Exception e) { + e.printStackTrace(); + item.deselect(); + } + + } + return list; + } + + public String getStyle() { + + if(isWitness){ + if(selected){ + return "background-color: #B8B8B8 ;"; + }else{ + if(verification.equals(needVerification)){ + return "background-color: #FF9999;"; + }else if(verification.equals(verificatedByCatalogue)){ + return "background-color: #CCCCCC;"; + }else if(verification.equals(verificatedByWitness)){ + return null; + } + } + }else{ + if(selected){ + return "background-color: #B8B8B8 ;"; + } + } + + return null; + } + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/auxObjects/lo/EventTextLO.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,32 @@ +package de.mpiwg.itgroup.ismi.auxObjects.lo; + +import java.util.ArrayList; + +import javax.faces.event.ActionEvent; +import javax.faces.model.SelectItem; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.event.beans.AbstractEvent; + +public class EventTextLO extends ListenerObject { + private static final long serialVersionUID = -2307053338601250211L; + + private AbstractEvent event; + + public EventTextLO(String classObj, String attName, AbstractEvent event){ + super(classObj, attName); + this.event = event; + } + + @Override + public void actionListenerSelect(ActionEvent e){ + super.actionListenerSelect(e); + event.setWitness(null); + if(event.getTextLo().entity != null && event.getTextLo().entity.isPersistent()){ + event.refreshWitnesses(event.getTextLo().entity); + }else{ + event.setWitnessList(new ArrayList<SelectItem>()); + } + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/auxObjects/lo/WitnessAuthorLO.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,25 @@ +package de.mpiwg.itgroup.ismi.auxObjects.lo; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.entry.beans.CurrentWitnessBean; + +public class WitnessAuthorLO extends ListenerObject { + private static final long serialVersionUID = -6143808296200456713L; + + private CurrentWitnessBean witnessBean; + + public WitnessAuthorLO(String classObj, String attName, CurrentWitnessBean witnessBean){ + super(classObj, attName); + this.witnessBean = witnessBean; + } + + + @Override + public void actionListenerSelect(ActionEvent event){ + super.actionListenerSelect(event); + this.witnessBean.updateAuthor(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/auxObjects/lo/WitnessCityLO.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,44 @@ +package de.mpiwg.itgroup.ismi.auxObjects.lo; + +import java.util.ArrayList; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.entry.beans.CodexEditorTemplate; +import de.mpiwg.itgroup.ismi.entry.beans.CurrentWitnessBean; + +public class WitnessCityLO extends ListenerObject{ + + private static final long serialVersionUID = -1576005707417850556L; + + private CodexEditorTemplate witnessBean; + + public WitnessCityLO(String classObj, String attName, CodexEditorTemplate witnessBean){ + super(classObj, attName); + this.witnessBean = witnessBean; + } + + @Override + public void actionListenerSelect(ActionEvent event){ + super.actionListenerSelect(event); + + this.witnessBean.setRepositoriesInCurrentCity(new ArrayList<SelectItem>()); + + if (this.entity!=null && this.entity.isPersistent()){ + this.witnessBean.setCity(this.entity); + } + this.witnessBean.checkConsistencyFromCountryToCodex(); + + } + + @Override + public void valueChangeMethod(ValueChangeEvent event) { + this.entityInfo = null; + changeListener(event, classObj, attName, "type", "city"); + + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/auxObjects/lo/WitnessCollectionLO.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,36 @@ +package de.mpiwg.itgroup.ismi.auxObjects.lo; + +import java.util.ArrayList; + +import javax.faces.event.ActionEvent; +import javax.faces.model.SelectItem; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.entry.beans.CodexEditorTemplate; +import de.mpiwg.itgroup.ismi.entry.beans.CurrentWitnessBean; + +public class WitnessCollectionLO extends ListenerObject{ + private static final long serialVersionUID = -289890572369861118L; + + private CodexEditorTemplate witnessBean; + + public WitnessCollectionLO(String classObj, String attName, CodexEditorTemplate witnessBean){ + super(classObj, attName); + this.witnessBean = witnessBean; + } + + + @Override + public void actionListenerSelect(ActionEvent event){ + super.actionListenerSelect(event); + + this.witnessBean.setShelfMarksInCurrentCollection(new ArrayList<SelectItem>()); + + if(this.entity != null && this.entity.isPersistent()){ + this.witnessBean.setCollection(this.entity); + } + + this.witnessBean.checkConsistencyFromCountryToCodex(); + + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/auxObjects/lo/WitnessCountryLO.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,44 @@ +package de.mpiwg.itgroup.ismi.auxObjects.lo; + +import java.util.ArrayList; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.entry.beans.CodexEditorTemplate; +import de.mpiwg.itgroup.ismi.entry.beans.CurrentWitnessBean; + +public class WitnessCountryLO extends ListenerObject{ + + private static final long serialVersionUID = 7100404791285987664L; + + private CodexEditorTemplate witnessBean; + + public WitnessCountryLO(String classObj, String attName, CodexEditorTemplate witnessBean){ + super(classObj, attName); + this.witnessBean = witnessBean; + } + + + @Override + public void actionListenerSelect(ActionEvent event){ + super.actionListenerSelect(event); + + this.witnessBean.setCitiesInCurrentCountry(new ArrayList<SelectItem>()); + + if (this.entity!=null && this.entity.isPersistent()){ + this.witnessBean.setCountry(this.entity); + } + this.witnessBean.checkConsistencyFromCountryToCodex(); + } + + @Override + public void valueChangeMethod(ValueChangeEvent event) { + this.entityInfo = null; + changeListener(event, classObj, attName, "type", "region"); + + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/auxObjects/lo/WitnessRepositoryLO.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,36 @@ +package de.mpiwg.itgroup.ismi.auxObjects.lo; + +import java.util.ArrayList; + +import javax.faces.event.ActionEvent; +import javax.faces.model.SelectItem; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.entry.beans.CodexEditorTemplate; +import de.mpiwg.itgroup.ismi.entry.beans.CurrentWitnessBean; + +public class WitnessRepositoryLO extends ListenerObject{ + + private static final long serialVersionUID = 8313432163139959772L; + + private CodexEditorTemplate witnessBean; + + public WitnessRepositoryLO(String classObj, String attName, CodexEditorTemplate witnessBean){ + super(classObj, attName); + this.witnessBean = witnessBean; + } + + + @Override + public void actionListenerSelect(ActionEvent event){ + super.actionListenerSelect(event); + + this.witnessBean.setCollectionsInCurrentRepository(new ArrayList<SelectItem>()); + this.witnessBean.setShelfMarksInCurrentCollection(new ArrayList<SelectItem>()); + + if (this.entity!= null && this.entity.isPersistent()){ + this.witnessBean.setRepository(this.entity); + } + this.witnessBean.checkConsistencyFromCountryToCodex(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/auxObjects/lo/WitnessTextLO.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,26 @@ +package de.mpiwg.itgroup.ismi.auxObjects.lo; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.entry.beans.CurrentWitnessBean; + +public class WitnessTextLO extends ListenerObject { + + private static final long serialVersionUID = -5739879935712908603L; + + private CurrentWitnessBean witnessBean; + + public WitnessTextLO(String classObj, String attName, CurrentWitnessBean witnessBean){ + super(classObj, attName); + this.witnessBean = witnessBean; + } + + + @Override + public void actionListenerSelect(ActionEvent event){ + super.actionListenerSelect(event); + this.witnessBean.updateTitle(); + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/browse/AbstractBrowse.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,15 @@ +package de.mpiwg.itgroup.ismi.browse; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; + +public class AbstractBrowse extends AbstractISMIBean { + private static final long serialVersionUID = -7932709184736905861L; + + public static String SELECTED_ENTITY = "selected_entity"; + public static String GOTO_ENTITY_DETAILS = "entity_details"; + public static String GOTO_ENTITY_REPOSITORY = "entity_repository"; + + public static String SESSION_BEAN_ENTITY_DETAILS = "EntityDetails"; + public static String SESSION_BEAN_SESSION = "Session"; + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/browse/AbstractEntityRepositoryBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,546 @@ +package de.mpiwg.itgroup.ismi.browse; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.services.utils.AttributeFilter; + +import de.mpiwg.itgroup.ismi.util.guiComponents.DataPaginator; + +public class AbstractEntityRepositoryBean extends AbstractBrowse { + + private static final long serialVersionUID = 3154642100627969159L; + + private static Logger logger = Logger.getLogger(AbstractEntityRepositoryBean.class); + + public static String MODE_ADVANCED = "advanced"; + public static String MODE_ALL = "all"; + public static String MODE_NONE = "none"; + + + private String objectClass = null; + private List<Entity> entities = new ArrayList<Entity>(); + private List<Entity> currentEntities = new ArrayList<Entity>(); + + private List<SelectItem> definitions = new ArrayList<SelectItem>(); + + private transient DataPaginator advancedPaginator = new DataPaginator(); + + private String ocTerm; + private String currentTab; + + private String textFullTitle; + private String textFullTitleTranslit; + private String textShortTitle; + + private String personName; + private String personNameTranslit; + + private String codexIdentifier; + + private String collectionName; + + private String placeName; + + private String aliasAlias; + + private String repositoryName; + + private String witnessFullTitle; + private String witnessFullTitleTranslit; + private String witnessAhlwardtNo; + + private boolean advancedSearch = false; + private String resultMode = MODE_NONE; + private String resultSummaryMsg; + + private String subjectType; + private List<SelectItem> suggestedSubjectTypes = new ArrayList<SelectItem>(); + + private String page; + private String pageMsg; + + public static String main_subject = "main_subject"; + public static String sub_subject = "sub_subject"; + + public AbstractEntityRepositoryBean(){ + suggestedSubjectTypes.add(new SelectItem(null, "-- choose --")); + suggestedSubjectTypes.add(new SelectItem(main_subject, main_subject)); + suggestedSubjectTypes.add(new SelectItem(sub_subject, sub_subject)); + this.updateDefinitions(getWrapper().getLWDefinitions()); + } + + private void updateAdvancedEntities() { + if (StringUtils.isNotEmpty(getObjectClass())) { + this.advancedPaginator.initCount(); + int startRecord = this.advancedPaginator.getCurrentPage() + * this.advancedPaginator.getItemsPerPage(); + if((this.advancedPaginator.getCurrentPage() + 1) == this.advancedPaginator.getNumberOfPages()){ + int mod = this.entities.size() % advancedPaginator.getItemsPerPage(); + if(mod == 0){ + this.currentEntities = entities.subList(startRecord, startRecord + this.advancedPaginator.getItemsPerPage()); + }else{ + this.currentEntities = entities.subList(startRecord, startRecord + mod); + } + + }else{ + this.currentEntities = entities.subList(startRecord, startRecord + this.advancedPaginator.getItemsPerPage()); + } + + } else + this.currentEntities = new ArrayList<Entity>(); + } + + public String advancedFirst() { + this.advancedPaginator.first(); + this.updateAdvancedEntities(); + return GOTO_ENTITY_REPOSITORY; + } + + public String advancedLast() { + this.advancedPaginator.last(); + this.updateAdvancedEntities(); + return GOTO_ENTITY_REPOSITORY; + } + + public String advancedFastForward() { + this.advancedPaginator.fastForward(); + this.updateAdvancedEntities(); + return GOTO_ENTITY_REPOSITORY; + } + + public String advancedFastRewind() { + this.advancedPaginator.fastRewind(); + this.updateAdvancedEntities(); + return GOTO_ENTITY_REPOSITORY; + } + + public String advancedPrevious() { + this.advancedPaginator.previous(); + this.updateAdvancedEntities(); + return GOTO_ENTITY_REPOSITORY; + } + + public String advancedNext() { + this.advancedPaginator.next(); + this.updateAdvancedEntities(); + return GOTO_ENTITY_REPOSITORY; + } + + public void reset(){ + this.entities = new ArrayList<Entity>(); + this.currentEntities = new ArrayList<Entity>(); + this.resultSummaryMsg = new String(); + } + + public void actionGoToPageAdvancedResult(ActionEvent event){ + this.pageMsg = ""; + try{ + Integer page = new Integer(getPage()); + this.advancedPaginator.goToPage(page - 1); + this.updateAdvancedEntities(); + }catch(Exception e){ + this.pageMsg = "page is invalid!"; + } + } + + public DataPaginator getAdvancedPaginator() { + return advancedPaginator; + } + + public void setAdvancedPaginator(DataPaginator advancedPaginator) { + this.advancedPaginator = advancedPaginator; + } + + public void updateDefinitions(List<Entity> defs) { + this.definitions = new ArrayList<SelectItem>(); + SelectItem option = null; + for (Entity def : defs) { + if (def.getOwnValue() != null) { + option = new SelectItem(def.getOwnValue()); + this.definitions.add(option); + } + } + this.setEntities(new ArrayList<Entity>()); + if (defs.size() > 0) { + this.objectClass = defs.get(0).getOwnValue(); + } + } + + public void actionDisplayAdvancedSearch(ActionEvent event) { + this.advancedSearch = true; + } + + public void actionHideAdvancedSearch(ActionEvent event) { + this.advancedSearch = false; + } + + public void actionChangeDefinition(ValueChangeEvent event) { + this.objectClass = (String) event.getNewValue(); + } + + public void searchByOwnvalue(){ + this.resultMode = MODE_ADVANCED; + this.setPage(""); + this.currentEntities = new ArrayList<Entity>(); + this.entities = getWrapper().searchEntityByOwnValue(objectClass, ocTerm); + this.resultSummaryMsg = ""; + + if(this.entities.size() > 0){ + + this.advancedPaginator.setCurrentPage(0); + int entitiesCount = this.entities.size(); + this.advancedPaginator.resetNumberOfPages(entitiesCount); + this.updateAdvancedEntities(); + }else { + this.resultSummaryMsg = "No items were found!"; + } + } + + + public void searchByAttributes() throws Exception{ + this.resultMode = MODE_ADVANCED; + this.setPage(""); + this.entities = new ArrayList<Entity>(); + this.currentEntities = new ArrayList<Entity>(); + + List<AttributeFilter> filterList = new ArrayList<AttributeFilter>(); + + this.resultSummaryMsg = ""; + Map<Entity, Attribute> resultMap = new HashMap<Entity, Attribute>(); + if (this.objectClass.equals(TEXT)) { + if (StringUtils.isNotEmpty(textFullTitle)) { + filterList.add(new AttributeFilter("full_title", + this.textFullTitle, TEXT)); + } + if (StringUtils.isNotEmpty(textFullTitleTranslit)) { + filterList.add(new AttributeFilter("full_title_translit", + textFullTitleTranslit, TEXT)); + } + if (StringUtils.isNotEmpty(textShortTitle)) { + List<Entity> l = getWrapper().searchEntityByAttributeOfTarRelation(TEXT, "is_prime_alias_title_of", ALIAS, "alias", textShortTitle, 20); + for(Entity e : l){ + this.entities.add(e); + } + } + } else if (this.objectClass.equals(WITNESS)) { + //witnessAhlwardtNo + if(StringUtils.isNotEmpty(this.witnessAhlwardtNo)){ + filterList.add(new AttributeFilter("ahlwardt_no", this.witnessAhlwardtNo, + WITNESS)); + } + } else if (this.objectClass.equals(SUBJECT)) { + if(StringUtils.isNotEmpty(this.subjectType)){ + filterList.add(new AttributeFilter("type", this.subjectType, + SUBJECT)); + } + } else if (this.objectClass.equals(ALIAS)) { + if(StringUtils.isNotEmpty(this.aliasAlias)){ + filterList.add(new AttributeFilter("alias", this.aliasAlias, + ALIAS)); + } + } else if (this.objectClass.equals(COLLECTION)) { + if(StringUtils.isNotEmpty(this.collectionName)){ + filterList.add(new AttributeFilter("name", this.collectionName, + COLLECTION)); + } + } else if (this.objectClass.equals(REPOSITORY)) { + if(StringUtils.isNotEmpty(this.repositoryName)){ + filterList.add(new AttributeFilter("name", this.repositoryName, + REPOSITORY)); + } + } else if (this.objectClass.equals(PLACE)) { + if(StringUtils.isNotEmpty(this.placeName)){ + filterList.add(new AttributeFilter("name", this.placeName, + PLACE)); + } + } else if (this.objectClass.equals(CODEX)) { + if(StringUtils.isNotEmpty(this.codexIdentifier)){ + filterList.add(new AttributeFilter("identifier", this.codexIdentifier, + CODEX)); + } + + } else if (this.objectClass.equals(PERSON)) { + if (StringUtils.isNotEmpty(this.personName)) { + filterList.add(new AttributeFilter("name", this.personName, + PERSON)); + } + if (StringUtils.isNotEmpty(this.personNameTranslit)) { + filterList.add(new AttributeFilter("name_translit", + this.personNameTranslit, PERSON)); + } + } + if (filterList.size() > 0) { + resultMap = getWrapper().searchEntityByAttributeFilter( + filterList, 500); + for (Entity ent : resultMap.keySet()) { + this.entities.add(ent); + } + Collections.sort(entities); + } + + if (resultMap.size() > 0) { + this.resultSummaryMsg = resultMap.size() + " items were found!"; + this.advancedPaginator.setCurrentPage(0); + int entitiesCount = this.entities.size(); + this.advancedPaginator.resetNumberOfPages(entitiesCount); + this.updateAdvancedEntities(); + } else { + this.resultSummaryMsg = "No items were found!"; + } + } + + public boolean isRenderedSearch(){ + if(StringUtils.isNotEmpty(this.objectClass) && ( + objectClass.equals(SUBJECT) || + objectClass.equals(REPOSITORY) || + objectClass.equals(ALIAS) || + objectClass.equals(COLLECTION) || + objectClass.equals(TEXT) || + objectClass.equals(PERSON) || + objectClass.equals(CODEX) || + objectClass.equals(WITNESS) || + objectClass.equals(PLACE))){ + return true; + } + return false; + } + + public String actionSearchByAttributes() { + try { + this.searchByAttributes(); + } catch (Exception e) { + printInternalError(e); + logger.error(e.getMessage(), e); + } + + return GOTO_ENTITY_REPOSITORY; + } + + public String actionSearchByOwnvalue(){ + try { + this.searchByOwnvalue(); + } catch (Exception e) { + printInternalError(e); + logger.error(e.getMessage(), e); + } + + return GOTO_ENTITY_REPOSITORY; + } + + public boolean isAdvancedSearch() { + return advancedSearch; + } + + public void setAdvancedSearch(boolean advancedSearch) { + this.advancedSearch = advancedSearch; + } + + public String getTextFullTitle() { + return textFullTitle; + } + + public void setTextFullTitle(String textFullTitle) { + this.textFullTitle = textFullTitle; + } + + public String getTextFullTitleTranslit() { + return textFullTitleTranslit; + } + + public void setTextFullTitleTranslit(String textFullTitleTranslit) { + this.textFullTitleTranslit = textFullTitleTranslit; + } + + public String getTextShortTitle() { + return textShortTitle; + } + + public void setTextShortTitle(String textShortTitle) { + this.textShortTitle = textShortTitle; + } + + public String getPersonName() { + return personName; + } + + public void setPersonName(String personName) { + this.personName = personName; + } + + public String getPersonNameTranslit() { + return personNameTranslit; + } + + public void setPersonNameTranslit(String personNameTranslit) { + this.personNameTranslit = personNameTranslit; + } + + public String getObjectClass() { + return objectClass; + } + + public void setObjectClass(String objectClass) { + this.objectClass = objectClass; + } + + public List<Entity> getEntities() { + return this.entities; + } + + public void setEntities(List<Entity> entities) { + this.entities = entities; + } + + public List<SelectItem> getDefinitions() { + return definitions; + } + + public void setDefinitions(List<SelectItem> definitions) { + this.definitions = definitions; + } + + public String getResultMode() { + return resultMode; + } + + public void setResultMode(String resultMode) { + this.resultMode = resultMode; + } + + public String getResultSummaryMsg() { + return resultSummaryMsg; + } + + public void setResultSummaryMsg(String resultSummaryMsg) { + this.resultSummaryMsg = resultSummaryMsg; + } + + public String getPage() { + return page; + } + + public void setPage(String page) { + this.page = page; + } + + public String getPageMsg() { + return pageMsg; + } + + public void setPageMsg(String pageMsg) { + this.pageMsg = pageMsg; + } + public String getCodexIdentifier() { + return codexIdentifier; + } + public void setCodexIdentifier(String codexIdentifier) { + this.codexIdentifier = codexIdentifier; + } + public String getPlaceName() { + return placeName; + } + public void setPlaceName(String placeName) { + this.placeName = placeName; + } + + public String getCollectionName() { + return collectionName; + } + + public void setCollectionName(String collectionName) { + this.collectionName = collectionName; + } + + public String getAliasAlias() { + return aliasAlias; + } + + public void setAliasAlias(String aliasAlias) { + this.aliasAlias = aliasAlias; + } + + public String getRepositoryName() { + return repositoryName; + } + + public void setRepositoryName(String repositoryName) { + this.repositoryName = repositoryName; + } + + public String getSubjectType() { + return subjectType; + } + + public void setSubjectType(String subjectType) { + this.subjectType = subjectType; + } + + public List<SelectItem> getSuggestedSubjectTypes() { + return suggestedSubjectTypes; + } + + public void setSuggestedSubjectTypes(List<SelectItem> suggestedTypes) { + this.suggestedSubjectTypes = suggestedTypes; + } + public List<Entity> getCurrentEntities() { + return currentEntities; + } + + public void setCurrentEntities(List<Entity> currentEntities) { + this.currentEntities = currentEntities; + } + + public String getWitnessFullTitle() { + return witnessFullTitle; + } + + public void setWitnessFullTitle(String witnessFullTitle) { + this.witnessFullTitle = witnessFullTitle; + } + + public String getWitnessFullTitleTranslit() { + return witnessFullTitleTranslit; + } + + public void setWitnessFullTitleTranslit(String witnessFullTitleTranslit) { + this.witnessFullTitleTranslit = witnessFullTitleTranslit; + } + + public String getWitnessAhlwardtNo() { + return witnessAhlwardtNo; + } + + public void setWitnessAhlwardtNo(String witnessAhlwardtNo) { + this.witnessAhlwardtNo = witnessAhlwardtNo; + } + + public String getOcTerm() { + return ocTerm; + } + + public void setOcTerm(String ocTerm) { + this.ocTerm = ocTerm; + } + + public String getCurrentTab() { + return currentTab; + } + + public void setCurrentTab(String currentTab) { + this.currentTab = currentTab; + } + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/browse/EntityDetailsBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,329 @@ +package de.mpiwg.itgroup.ismi.browse; + +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.Node; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.entry.beans.SessionBean; +import de.mpiwg.itgroup.ismi.event.beans.CopyEvent; +import de.mpiwg.itgroup.ismi.event.beans.StudyEvent; +import de.mpiwg.itgroup.ismi.event.beans.TransferEvent; + +public class EntityDetailsBean extends AbstractBrowse{ + + private static final long serialVersionUID = 1374652791403248103L; + + private static Logger logger = Logger.getLogger(EntityDetailsBean.class); + + private Entity entity; + private String currentEntityId; + + private List<Attribute> attributeList = new ArrayList<Attribute>(); + private List<String> sourceRelationNames = new ArrayList<String>(); + private List<String> targetRelationNames = new ArrayList<String>(); + + private Map<String, Long> sourceRelationCount = new HashMap<String, Long>(); + private Map<String, Long> targetRelationCount = new HashMap<String, Long>(); + + private Map<String, List<Relation>> sourceRelations = new HashMap<String, List<Relation>>(); + private Map<String, List<Relation>> targetRelations = new HashMap<String, List<Relation>>(); + + private List<Entity> previousVersionsList = new ArrayList<Entity>(); + private Entity selectedPreviousVersion = null; + private boolean previousVersionDetailsVisible = false; + + + public EntityDetailsBean() { + } + + public void listenerHideDetailsPopup(ActionEvent event){ + setPreviousVersionDetailsVisible(false); + } + + public void listenerHidePreviousVersions(ActionEvent event){ + setPreviousVersionsList(new ArrayList<Entity>()); + setSelectedPreviousVersion(null); + } + + public void listenerUndoUntilThisVersion(ActionEvent event) throws Exception{ + this.selectedPreviousVersion = (Entity)getRequestBean("previousVersion"); + if(this.selectedPreviousVersion != null){ + + //checking whether the relation reference to existing entities, + //If the entity referenced does not exist more, the relation will not be considered. + + //Checking source's relation + List<Relation> relToDelete = new ArrayList<Relation>(); + for(Relation rel : selectedPreviousVersion.getSourceRelations()){ + if(getWrapper().getEntityById(rel.getTargetId()) == null){ + relToDelete.add(rel); + } + } + for(Relation rel : relToDelete){ + selectedPreviousVersion.getSourceRelations().remove(rel); + } + + //Checking target's relations + relToDelete = new ArrayList<Relation>(); + for(Relation rel : selectedPreviousVersion.getTargetRelations()){ + if(getWrapper().getEntityById(rel.getSourceId()) == null){ + relToDelete.add(rel); + } + } + for(Relation rel : relToDelete){ + selectedPreviousVersion.getTargetRelations().remove(rel); + } + + selectedPreviousVersion.setVersion(this.entity.getVersion()); + selectedPreviousVersion.setSystemStatus(Node.SYS_STATUS_CURRENT_VERSION); + + getWrapper().saveEntity(selectedPreviousVersion, getUserName()); + + } + } + + + + public void listenerGetPreviousVersions(ActionEvent event){ + this.previousVersionsList = getWrapper().getPreviousEntitiesById(getEntity().getId()); + if(previousVersionsList.size() == 0){ + addGeneralMsg("It had not been found previous versions for this entity."); + } + } + + public void listenerShowPreviousVersionDetails(ActionEvent event){ + this.selectedPreviousVersion = (Entity)getRequestBean("previousVersion"); + setPreviousVersionDetailsVisible(true); + System.out.println(this.selectedPreviousVersion); + } + + + + public void listenerShowEntity(ActionEvent event) { + try { + Long.parseLong(currentEntityId); + redirect("/browse/entityDetails.xhtml", "?eid=" + currentEntityId); + + } catch (Exception e) { + addErrorMsg("ID is not valid: " + this.currentEntityId); + } + } + + public void setEntity(Entity entity) { + this.entity = entity; + if(entity != null){ + + this.currentEntityId = entity.getId().toString(); + + this.selectedPreviousVersion = null; + this.previousVersionsList = new ArrayList<Entity>(); + //this.definition = getWrapper().getDefinition(entity.getObjectClass()); + this.attributeList = getWrapper().getAttributeByEntId(entity.getId()); + this.sourceRelations = new HashMap<String, List<Relation>>(); + this.targetRelations = new HashMap<String, List<Relation>>(); + this.sourceRelationNames = new ArrayList<String>(); + this.targetRelationNames = new ArrayList<String>(); + this.sourceRelationCount = new HashMap<String, Long>(); + this.targetRelationCount = new HashMap<String, Long>(); + + + System.out.println("****************"); + List<Relation> srcRels = getWrapper().getDefSourceRelations(this.entity.getObjectClass()); + for(Relation rel : srcRels){ + if(rel.getOwnValue().equals("has_autor_misattribution")){ + System.out.println("src - " + rel.getOwnValue()); + } + if(!this.sourceRelationNames.contains(rel.getOwnValue())){ + this.sourceRelationNames.add(rel.getOwnValue()); + this.sourceRelationCount.put(rel.getOwnValue(), getWrapper().getSourceRelationsCount(entity, rel.getOwnValue(), null)); + } + } + List<Relation> tarRels = getWrapper().getDefTargetRelations(this.entity.getObjectClass()); + for(Relation rel : tarRels){ + if(!this.targetRelationNames.contains(rel.getOwnValue())){ + this.targetRelationNames.add(rel.getOwnValue()); + this.targetRelationCount.put(rel.getOwnValue(), getWrapper().getTargetRelationsCount(entity, rel.getOwnValue(), null)); + } + + } + } + } + + public void listenerShowTargetRelations(ActionEvent event){ + String tarName = (String) getRequestBean("tarName"); + this.targetRelations.put(tarName, getWrapper().getTargetRelations(this.entity, tarName, null, -1)); + } + + public String listenerDeleteEntity(){ + try { + getWrapper().removeCurrentVersionEntity(this.entity); + EntityRepositoryBean bean = (EntityRepositoryBean)getSessionBean("EntityRepository"); + if(bean != null){ + bean.reset(); + } + addGeneralMsg("The entity has been removed."); + } catch (Exception e) { + printInternalError(e); + logger.error(e.getMessage() + " Removing" + entity, e); + e.printStackTrace(); + } + + return GOTO_ENTITY_REPOSITORY; + } + + public void listenerShowSourceRelations(ActionEvent event){ + try { + String srcName = (String) getRequestBean("srcName"); + this.sourceRelations.put(srcName, getWrapper().getSourceRelations(this.entity, srcName, null, -1)); + } catch (Exception e) { + printInternalError(e); + logger.error(e.getMessage(), e); + } + } + public Entity getEntity() { + return entity; + } + + + + /** + * This method calls the SessionBean and put in it the current entity to be + * modified. + * + * @return + */ + public String actionEdit() { + try { + // getting de.mpiwg.itgroup.ismi.entry.beans.SessionBean + getSessionBean().editEntity(this.entity); + + } catch (Exception e) { + e.printStackTrace(); + } + if(entity.getObjectClass().equals(StudyEvent.OC) || + entity.getObjectClass().equals(CopyEvent.OC) || + entity.getObjectClass().equals(TransferEvent.OC)){ + return SessionBean.PAGE_EVENT_FORM; + }else{ + return SessionBean.PAGE_ENTRY; + } + } + + /** + * <p> + * Show the details page for the current entity. + * </p> + */ + public String showTarget() { + Relation relation = (Relation) getRequestBean("srcRelation"); + setEntity(relation.getTarget()); + return GOTO_ENTITY_DETAILS; + } + + public String showSource() { + Relation relation = (Relation) getRequestBean("tarRelation"); + setEntity(relation.getSource()); + return GOTO_ENTITY_DETAILS; + } + + public Entity getEntityById(Long id) { + //juc return getOntology().getEntityById(id); + return getWrapper().getEntityById(id); + } + + public String getCurrentEntityId() { + return currentEntityId; + } + + public void setCurrentEntityId(String cid) { + this.currentEntityId = cid; + } + + public List<Attribute> getAttributeList() { + return attributeList; + } + + public void setAttributeList(List<Attribute> attributeList) { + this.attributeList = attributeList; + } + public List<String> getSourceRelationNames() { + return sourceRelationNames; + } + + public void setSourceRelationNames(List<String> sourceRelationNames) { + this.sourceRelationNames = sourceRelationNames; + } + + public List<String> getTargetRelationNames() { + return targetRelationNames; + } + + public void setTargetRelationNames(List<String> targetRelationNames) { + this.targetRelationNames = targetRelationNames; + } + + public Map<String, Long> getSourceRelationCount() { + return sourceRelationCount; + } + + public void setSourceRelationCount(Map<String, Long> sourceRelationCount) { + this.sourceRelationCount = sourceRelationCount; + } + + public Map<String, Long> getTargetRelationCount() { + return targetRelationCount; + } + + public void setTargetRelationCount(Map<String, Long> targetRelationCount) { + this.targetRelationCount = targetRelationCount; + } + + public Map<String, List<Relation>> getSourceRelations() { + return sourceRelations; + } + + public void setSourceRelations(Map<String, List<Relation>> sourceRelations) { + this.sourceRelations = sourceRelations; + } + + public Map<String, List<Relation>> getTargetRelations() { + return targetRelations; + } + + public void setTargetRelations(Map<String, List<Relation>> targetRelations) { + this.targetRelations = targetRelations; + } + + public List<Entity> getPreviousVersionsList() { + return previousVersionsList; + } + + public void setPreviousVersionsList(List<Entity> previousVersionsList) { + this.previousVersionsList = previousVersionsList; + } + + public Entity getSelectedPreviousVersion() { + return selectedPreviousVersion; + } + + public void setSelectedPreviousVersion(Entity selectedPreviousVersion) { + this.selectedPreviousVersion = selectedPreviousVersion; + } + public boolean isPreviousVersionDetailsVisible() { + return previousVersionDetailsVisible; + } + + public void setPreviousVersionDetailsVisible( + boolean previousVersionDetailsVisible) { + this.previousVersionDetailsVisible = previousVersionDetailsVisible; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/browse/EntityRepositoryBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,154 @@ +package de.mpiwg.itgroup.ismi.browse; + +import java.util.ArrayList; + +import javax.faces.event.ActionEvent; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.entry.beans.SessionBean; +import de.mpiwg.itgroup.ismi.event.beans.CopyEvent; +import de.mpiwg.itgroup.ismi.event.beans.StudyEvent; +import de.mpiwg.itgroup.ismi.event.beans.TransferEvent; +import de.mpiwg.itgroup.ismi.util.guiComponents.DataPaginator; + +public class EntityRepositoryBean extends AbstractEntityRepositoryBean { + private static final long serialVersionUID = -2380877853539157567L; + + private transient DataPaginator paginator = new DataPaginator(); + + public EntityRepositoryBean(){ + super(); + } + + @Override + public void reset(){ + super.reset(); + this.paginator = new DataPaginator(); + } + + + private void updateEntities() { + if (StringUtils.isNotEmpty(getObjectClass())) { + this.paginator.initCount(); + int startRecord = this.paginator.getCurrentPage() + * this.paginator.getItemsPerPage(); + + if(this.paginator.getNumberOfPages() == 0){ + this.setEntities(new ArrayList<Entity>()); + }else{ + int mod = getWrapper().getEntitiesCount(getObjectClass()) % paginator.getItemsPerPage(); + if((paginator.getCurrentPage() + 1) == paginator.getNumberOfPages() && mod != 0){ + this.setEntities( + getWrapper().getEntityByDefSubList(getObjectClass(), startRecord, startRecord + mod) + ); + }else{ + this.setEntities( + getWrapper().getEntityByDefSubList(getObjectClass(), startRecord, startRecord + paginator.getItemsPerPage()) + ); + } + } + } else { + this.setEntities(new ArrayList<Entity>()); + } + } + + public String first() { + this.paginator.first(); + this.updateEntities(); + return GOTO_ENTITY_REPOSITORY; + } + + public String last() { + this.paginator.last(); + this.updateEntities(); + return GOTO_ENTITY_REPOSITORY; + } + + public String fastForward() { + this.paginator.fastForward(); + this.updateEntities(); + return GOTO_ENTITY_REPOSITORY; + } + + public String fastRewind() { + this.paginator.fastRewind(); + this.updateEntities(); + return GOTO_ENTITY_REPOSITORY; + } + + public String previous() { + this.paginator.previous(); + this.updateEntities(); + return GOTO_ENTITY_REPOSITORY; + } + + public String next() { + this.paginator.next(); + this.updateEntities(); + return GOTO_ENTITY_REPOSITORY; + } + + public void listenerGoToPage(ActionEvent event) { + try { + this.setPageMsg(""); + Integer intPage = new Integer(this.getPage()); + if (intPage != null) { + intPage--; + this.paginator.goToPage(intPage); + this.updateEntities(); + + } + } catch (Exception e) { + this.setPageMsg("page is invalid!"); + } + } + + public String actionShowAll() { + + this.setResultMode(MODE_ALL); + this.setResultSummaryMsg(""); + this.setPage(""); + this.paginator.setCurrentPage(0); + int entitiesCount = getWrapper().getEntitiesCount(getObjectClass()); + this.paginator.resetNumberOfPages(entitiesCount); + this.updateEntities(); + + setResultSummaryMsg(entitiesCount + " items were found!"); + + return GOTO_ENTITY_REPOSITORY; + } + + + + public String details() { + Entity selectedEntity = (Entity) getRequestBean("entity"); + EntityDetailsBean bean = (EntityDetailsBean) getRequestBean(SESSION_BEAN_ENTITY_DETAILS); + bean.setEntity(selectedEntity); + + return GOTO_ENTITY_DETAILS; + } + + public String actionEdit() { + Entity entity = (Entity) getRequestBean("entity"); + getSessionBean().editEntity(entity); + //return SessionBean.PAGE_ENTRY; + + if(entity.getObjectClass().equals(StudyEvent.OC) || + entity.getObjectClass().equals(CopyEvent.OC) || + entity.getObjectClass().equals(TransferEvent.OC)){ + return SessionBean.PAGE_EVENT_FORM; + }else{ + return SessionBean.PAGE_ENTRY; + } + } + + public DataPaginator getPaginator() { + return paginator; + } + + public void setPaginator(DataPaginator paginator) { + this.paginator = paginator; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/defs/AbstractDefinitionForm.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,169 @@ +package de.mpiwg.itgroup.ismi.defs; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.faces.model.SelectItem; + +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractBean; +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; +import de.mpiwg.itgroup.ismi.utils.SelectableObject; + +public class AbstractDefinitionForm extends AbstractBean implements Serializable{ + protected static final long serialVersionUID = 1L; + + protected List<Entity> defList; + protected List<SelectItem> defSelectList; + + protected Entity selectedLWDefinition; + protected Entity tmpLWDefinition; + protected List<SelectableObject<Attribute>> attList; + protected List<SelectableObject<Relation>> srcRelList; + protected List<SelectableObject<Relation>> tarRelList; + + protected Attribute selectedAttribute; + + protected Relation selectedRelation; + protected List<SelectableObject<Attribute>> selectedRelationAttributes; + + protected List<SelectableObject<String>> possibleValuesList = null; + + protected boolean isSourceRelation = false; + + private static List<SelectItem> contentTypeList = new ArrayList<SelectItem>(); + + static{ + contentTypeList.add(new SelectItem("", "-- select one --")); + contentTypeList.add(new SelectItem("arabic")); + contentTypeList.add(new SelectItem("date")); + contentTypeList.add(new SelectItem("escidoc-objid")); + contentTypeList.add(new SelectItem("link")); + contentTypeList.add(new SelectItem("json")); + contentTypeList.add(new SelectItem("text")); + contentTypeList.add(new SelectItem("boolean")); + contentTypeList.add(new SelectItem("xml")); + contentTypeList.add(new SelectItem("geoname-id")); + } + + public List<SelectItem> getContentTypeList(){ + return contentTypeList; + } + + public boolean isSourceRelation() { + return isSourceRelation; + } + + public List<Entity> getDefList() { + return defList; + } + + public void setDefList(List<Entity> defList) { + this.defList = defList; + } + + public List<SelectItem> getDefSelectList() { + return defSelectList; + } + + public void setDefSelectList(List<SelectItem> defSelectList) { + this.defSelectList = defSelectList; + } + + public Entity getSelectedLWDefinition() { + return selectedLWDefinition; + } + + public void setSelectedLWDefinition(Entity selectedLWDefinition) { + this.selectedLWDefinition = selectedLWDefinition; + } + + public List<SelectableObject<Attribute>> getAttList() { + return attList; + } + + public void setAttList(List<SelectableObject<Attribute>> attList) { + this.attList = attList; + } + + public List<SelectableObject<Relation>> getSrcRelList() { + return srcRelList; + } + + public void setSrcRelList(List<SelectableObject<Relation>> srcRelList) { + this.srcRelList = srcRelList; + } + + public List<SelectableObject<Relation>> getTarRelList() { + return tarRelList; + } + + public void setTarRelList(List<SelectableObject<Relation>> tarRelList) { + this.tarRelList = tarRelList; + } + + public Attribute getSelectedAttribute() { + return selectedAttribute; + } + + public void setSelectedAttribute(Attribute selectedAttribute) { + this.selectedAttribute = selectedAttribute; + } + + public Relation getSelectedRelation() { + return selectedRelation; + } + + public void setSelectedRelation(Relation selectedRelation) { + this.selectedRelation = selectedRelation; + } + + public List<SelectableObject<String>> getPossibleValuesList() { + return possibleValuesList; + } + + public void setPossibleValuesList(List<SelectableObject<String>> possibleValuesList) { + this.possibleValuesList = possibleValuesList; + } + + public List<SelectableObject<Attribute>> getSelectedRelationAttributes() { + return selectedRelationAttributes; + } + + public void setSelectedRelationAttributes( + List<SelectableObject<Attribute>> selectedRelationAttributes) { + this.selectedRelationAttributes = selectedRelationAttributes; + } + + protected static String convertAttOrRelOW(String s){ + s = s.toLowerCase(); + s = s.replace(" ", "_"); + return s; + } + + protected static String convertDefOW(String s){ + s = s.toUpperCase(); + s = s.replace(" ", "_"); + return s; + } + + protected static List<Attribute> cloneAttributeList(List<Attribute> list){ + List<Attribute> nList = new ArrayList<Attribute>(); + for(Attribute att : list){ + nList.add((Attribute)att.clone()); + } + return nList; + } + + public Entity getTmpLWDefinition() { + return tmpLWDefinition; + } + + public void setTmpLWDefinition(Entity tmpLWDefinition) { + this.tmpLWDefinition = tmpLWDefinition; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/defs/DefinitionForm.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,446 @@ +package de.mpiwg.itgroup.ismi.defs; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +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.Node; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.browse.EntityRepositoryBean; +import de.mpiwg.itgroup.ismi.utils.SelectableObject; + +public class DefinitionForm extends AbstractDefinitionForm implements + Serializable { + private static final long serialVersionUID = 1L; + + private static Logger logger = Logger.getLogger(DefinitionForm.class); + + public void createDefinition(ActionEvent event) { + this.tmpLWDefinition = new Entity(Node.TYPE_TBOX, Node.TYPE_TBOX, false); + } + + public void cancelCreationDefinition(ActionEvent event) { + this.tmpLWDefinition = null; + this.selectedLWDefinition = null; + } + + public void saveLWDefinition(ActionEvent event) { + try { + if (tmpLWDefinition != null + && StringUtils.isNotBlank(tmpLWDefinition.getOwnValue())) { + + String ov = tmpLWDefinition.getOwnValue(); + tmpLWDefinition.setOwnValue(convertDefOW(ov)); + + this.selectedLWDefinition = this.getWrapper().saveLWDefinition( + tmpLWDefinition, getSessionBean().getUsername()); + this.tmpLWDefinition = null; + this.loadDefinition(); + } + } catch (Exception e) { + e.printStackTrace(); + logger.error(e.getMessage(), e); + this.printInternalError(e); + } + + } + + public DefinitionForm() { + this.loadDefinitions(); + } + + public void listenerCancelEdition(ActionEvent event) { + this.loadDefinitions(); + } + + public void loadDefinitions() { + this.defList = getWrapper().getLWDefinitions(); + this.defSelectList = new ArrayList<SelectItem>(); + + this.selectedLWDefinition = null; + for (Entity def : this.defList) { + this.defSelectList.add(new SelectItem(def.getId(), def + .getOwnValue())); + } + EntityRepositoryBean bean = (EntityRepositoryBean) getSessionBean("EntityRepository"); + if (bean != null) { + bean.updateDefinitions(this.defList); + } + } + + public void loadDefinition() { + this.attList = new ArrayList<SelectableObject<Attribute>>(); + for (Attribute att : getWrapper().getDefAttributes( + this.selectedLWDefinition.getOwnValue())) { + this.attList.add(new SelectableObject<Attribute>(att)); + } + this.srcRelList = new ArrayList<SelectableObject<Relation>>(); + for (Relation rel : getWrapper().getDefSourceRelations( + this.selectedLWDefinition.getOwnValue())) { + rel.setSource(selectedLWDefinition); + rel.setTarget(getWrapper().getDefinitionById(rel.getTargetId())); + srcRelList.add(new SelectableObject<Relation>(rel)); + } + this.tarRelList = new ArrayList<SelectableObject<Relation>>(); + for (Relation rel : getWrapper().getDefTargetRelations( + this.selectedLWDefinition.getOwnValue())) { + rel.setSource(getWrapper().getDefinitionById(rel.getSourceId())); + rel.setTarget(selectedLWDefinition); + tarRelList.add(new SelectableObject<Relation>(rel)); + } + } + + public void listenerShowDefinition(ActionEvent event) { + this.selectedLWDefinition = (Entity) getRequestBean("def"); + if (this.selectedLWDefinition != null) { + this.loadDefinition(); + } else { + addGeneralMsg("The definition could not be loaded."); + } + } + + // ********************* Possible Values for attributes*********** + public void listenerAddPossibleValue(ActionEvent event) { + this.possibleValuesList.add(new SelectableObject<String>(new String())); + } + + public void listenerDeletePossibleValues(ActionEvent event) { + List<SelectableObject<String>> toDelete = new ArrayList<SelectableObject<String>>(); + for (SelectableObject<String> so : this.possibleValuesList) { + if (so.isSelected()) { + toDelete.add(so); + } + } + for (SelectableObject<String> so : toDelete) { + this.possibleValuesList.remove(so); + } + } + + // *************************************************************** + + // **************************** Relations ************************ + public void listenerDeleteSourceRelations(ActionEvent event) { + try { + List<SelectableObject<Relation>> toDelete = new ArrayList<SelectableObject<Relation>>(); + for (SelectableObject<Relation> so : this.srcRelList) { + if (so.isSelected()) { + toDelete.add(so); + } + } + for (SelectableObject<Relation> so : toDelete) { + this.getWrapper().removeDefRelation((Relation) so.getObj()); + } + this.loadDefinition(); + } catch (Exception e) { + e.printStackTrace(); + logger.error(e.getMessage(), e); + this.printInternalError(e); + } + } + + public void listenerDeleteTargetRelations(ActionEvent event) { + try { + List<SelectableObject<Relation>> toDelete = new ArrayList<SelectableObject<Relation>>(); + for (SelectableObject<Relation> so : this.tarRelList) { + if (so.isSelected()) { + toDelete.add(so); + } + } + for (SelectableObject<Relation> so : toDelete) { + this.getWrapper().removeDefRelation((Relation) so.getObj()); + } + this.loadDefinition(); + } catch (Exception e) { + e.printStackTrace(); + logger.error(e.getMessage(), e); + this.printInternalError(e); + } + } + + public void listenerEditSourceRelation(ActionEvent event) { + SelectableObject<Relation> so = (SelectableObject<Relation>) getRequestBean("relObj"); + if (so != null && so.getObj() != null + && so.getObj() instanceof Relation) { + Relation rel = so.getObj(); + this.selectedRelation = (Relation) rel.clone(); + + this.selectedRelationAttributes = new ArrayList<SelectableObject<Attribute>>(); + for (Attribute att : getWrapper().getDefRelationAttributes( + rel.getId())) { + this.selectedRelationAttributes + .add(new SelectableObject<Attribute>(att)); + } + } + this.isSourceRelation = true; + } + + public void listenerEditTargetRelation(ActionEvent event) { + SelectableObject<Relation> so = (SelectableObject<Relation>) getRequestBean("relObj"); + if (so != null && so.getObj() != null + && so.getObj() instanceof Relation) { + Relation rel = so.getObj(); + this.selectedRelation = (Relation) rel.clone(); + } + this.isSourceRelation = false; + } + + public void listenerCancelEditionOfRelation(ActionEvent event) { + this.selectedRelation = null; + } + + public void listenerSaveRelation(ActionEvent event) { + try { + if (!this.isRelationUnique(selectedRelation)) { + addGeneralMsg("The relation could not be saved. There is already a relation with same source, target and label."); + return; + } + if (!this.isOKRelationAttributes()) { + addGeneralMsg("The relation could not be saved. There are some attributes for this relation with same name or with empty name."); + return; + } + + this.selectedRelation.setSourceModif(this.selectedLWDefinition + .getModificationTime()); + this.selectedRelation + .setSourceObjectClass(this.selectedLWDefinition + .getObjectClass()); + this.getWrapper().saveDefRelation(selectedRelation, getSessionBean().getUsername()); + for (SelectableObject<Attribute> so : this.selectedRelationAttributes) { + Attribute att = so.getObj(); + att.setSourceId(this.selectedRelation.getId()); + att.setSourceModif(this.selectedRelation.getModificationTime()); + att.setSourceObjectClass(this.selectedRelation.getObjectClass()); + this.getWrapper().saveDefAttribute(att, getSessionBean().getUsername()); + } + this.selectedRelation = null; + this.loadDefinition(); + } catch (Exception e) { + e.printStackTrace(); + logger.error(e.getMessage(), e); + this.printInternalError(e); + } + } + + public void listenerCreateSourceRelation(ActionEvent event) { + this.selectedRelation = new Relation(); + this.selectedRelation.setSource(selectedLWDefinition); + this.isSourceRelation = true; + this.selectedRelationAttributes = new ArrayList<SelectableObject<Attribute>>(); + } + + public void listenerCreateTargetRelation(ActionEvent event) { + this.selectedRelation = new Relation(); + this.selectedRelation.setTarget(selectedLWDefinition); + this.isSourceRelation = false; + this.selectedRelationAttributes = new ArrayList<SelectableObject<Attribute>>(); + } + + // ******************** Attributes for relation ***************** + + public void listenerCreateAttributeForRelation(ActionEvent event) { + Attribute att = new Attribute(Node.TYPE_TBOX, "text", ""); + att.setSourceId(this.selectedRelation.getId()); + att.setSourceObjectClass(Node.TYPE_TBOX); + att.setSourceModif(this.selectedRelation.getModificationTime()); + att.setSystemStatus(Node.SYS_STATUS_CURRENT_VERSION); + if (selectedRelationAttributes == null) { + this.selectedRelationAttributes = new ArrayList<SelectableObject<Attribute>>(); + } + this.selectedRelationAttributes + .add(new SelectableObject<Attribute>(att)); + } + + public void listenerDeleteAttributesForRelation(ActionEvent event) { + try { + List<SelectableObject<Attribute>> toDelete = new ArrayList<SelectableObject<Attribute>>(); + for (SelectableObject<Attribute> so : this.selectedRelationAttributes) { + if (so.isSelected()) { + toDelete.add(so); + } + } + for (SelectableObject<Attribute> so : toDelete) { + this.selectedRelationAttributes.remove(so); + Attribute att = (Attribute) so.getObj(); + if (att.getId() != null) { + this.getWrapper().removeDefAttribute(att); + } + } + } catch (Exception e) { + e.printStackTrace(); + logger.error(e.getMessage(), e); + this.printInternalError(e); + } + + } + + // *************************************************************** + // **************************** Attributes *********************** + + public void listenerCreateAttribute(ActionEvent event) { + this.selectedAttribute = new Attribute(Node.TYPE_TBOX, "text", ""); + this.selectedAttribute.setSourceId(this.selectedLWDefinition.getId()); + this.selectedAttribute.setSourceObjectClass(Node.TYPE_TBOX); + this.selectedAttribute.setSourceModif(this.selectedLWDefinition + .getModificationTime()); + this.selectedAttribute.setSystemStatus(Node.SYS_STATUS_CURRENT_VERSION); + + this.possibleValuesList = new ArrayList<SelectableObject<String>>(); + if (possibleValuesList.size() == 0) { + this.possibleValuesList.add(new SelectableObject<String>( + new String())); + } + } + + public void listenerEditAttribute(ActionEvent event) { + SelectableObject<Attribute> so = (SelectableObject<Attribute>) getRequestBean("attObj"); + if (so != null && so.getObj() != null + && so.getObj() instanceof Attribute) { + Attribute att = (Attribute) so.getObj(); + this.selectedAttribute = (Attribute) att.clone(); + + this.possibleValuesList = new ArrayList<SelectableObject<String>>(); + for (String possibleValue : selectedAttribute + .getPossibleValuesList()) { + this.possibleValuesList.add(new SelectableObject<String>( + possibleValue)); + } + if (possibleValuesList.size() == 0) { + this.possibleValuesList.add(new SelectableObject<String>( + new String())); + } + } + } + + public void listenerSaveAttribute(ActionEvent event) { + try { + this.selectedAttribute + .setOwnValue(convertAttOrRelOW(selectedAttribute + .getOwnValue())); + + if (StringUtils.isBlank(selectedAttribute.getOwnValue())) { + addGeneralMsg("The attribute could not be saved." + + " The attribute must have a name."); + return; + } + + if (!isAttributeNameUnique(selectedAttribute)) { + addGeneralMsg("The attribute could not be saved." + + " There is already a attribute with the same name."); + return; + } + this.savePossibleValues(); + getWrapper().saveDefAttribute(selectedAttribute, getSessionBean().getUsername()); + this.selectedAttribute = null; + this.loadDefinition(); + } catch (Exception e) { + e.printStackTrace(); + logger.error(e.getMessage(), e); + this.printInternalError(e); + } + } + + private void savePossibleValues() { + List<String> list = new ArrayList<String>(); + for (SelectableObject<String> so : this.possibleValuesList) { + String value = so.getObj(); + if (StringUtils.isNotBlank(value)) { + if (list.contains(value)) { + addGeneralMsg("There are two or more values equals."); + return; + } else { + list.add(value); + } + } + } + + Collections.sort(list); + this.selectedAttribute.setPossibleValuesList(list); + } + + private boolean isRelationUnique(Relation editingRel) { + for (SelectableObject<Relation> so : this.srcRelList) { + Relation rel = so.getObj(); + if (!rel.getId().equals(editingRel.getId()) + && rel.getSourceId().equals(editingRel.getSourceId()) + && rel.getTargetId().equals(editingRel.getTargetId()) + && rel.getOwnValue().equals(editingRel.getOwnValue())) { + return false; + } + } + for (SelectableObject<Relation> so : this.tarRelList) { + Relation rel = so.getObj(); + if (!rel.getId().equals(editingRel.getId()) + && rel.getSourceId().equals(editingRel.getSourceId()) + && rel.getTargetId().equals(editingRel.getTargetId()) + && rel.getOwnValue().equals(editingRel.getOwnValue())) { + return false; + } + } + return true; + } + + private boolean isOKRelationAttributes() { + List<String> testList = new ArrayList<String>(); + if (selectedRelationAttributes != null) { + for (SelectableObject<Attribute> so : this.selectedRelationAttributes) { + Attribute att = so.getObj(); + if (StringUtils.isBlank(att.getOwnValue())) { + return false; + } + att.setOwnValue(convertAttOrRelOW(att.getOwnValue())); + if (testList.contains(att.getOwnValue())) { + return false; + } else { + testList.add(att.getOwnValue()); + } + } + } + return true; + } + + private boolean isAttributeNameUnique(Attribute editingAtt) { + for (SelectableObject<Attribute> so : this.attList) { + Attribute att = so.getObj(); + if (!att.getId().equals(editingAtt.getId()) + && att.getOwnValue().equals(editingAtt.getOwnValue())) { + return false; + } + } + return true; + } + + public void listenerCancelEditionOfAttribute(ActionEvent event) { + this.selectedAttribute = null; + this.possibleValuesList = null; + } + + public void listenerDeleteAttributes(ActionEvent event) { + try { + List<SelectableObject<Attribute>> toDelete = new ArrayList<SelectableObject<Attribute>>(); + for (SelectableObject<Attribute> so : this.attList) { + if (so.isSelected()) { + toDelete.add(so); + } + } + for (SelectableObject<Attribute> so : toDelete) { + this.getWrapper().removeDefAttribute(so.getObj()); + } + this.loadDefinition(); + } catch (Exception e) { + e.printStackTrace(); + logger.error(e.getMessage(), e); + this.printInternalError(e); + } + } + // *************************************************************** + // *************************************************************** +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/AbstractBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,95 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.io.IOException; +import java.io.Serializable; +import java.text.DateFormat; +import java.util.Date; + +import javax.faces.context.ExternalContext; +import javax.faces.context.FacesContext; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.cache.WrapperService; + +public abstract class AbstractBean implements Serializable{ + + private static final long serialVersionUID = -8646299519985691771L; + private static String BEAN_APP = "ApplicationBean1"; + private static String BEAN_SESSION = "Session"; + + public Object getRequestBean(String name){ + return FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get(name); + } + + public Object getSessionBean(String name){ + return FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(name); + } + + public Object getApplicationBean(String name){ + return FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get(name); + } + + public void addSessionBean(String name, Object bean){ + FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(name, bean); + } + + public ApplicationBean getAppBean(){ + ApplicationBean app = (ApplicationBean)getApplicationBean(BEAN_APP); + if(app == null){ + app = new ApplicationBean(); + FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().put(BEAN_APP, app); + } + return app; + } + + protected void printInternalError(Exception e){ + addErrorMsg("Internal Error, this action could not be executed correctly."); + addErrorMsg(e.getMessage()); + addErrorMsg("Server time: " + DateFormat.getDateTimeInstance().format(new Date())); + addErrorMsg("Please inform support: jurzua@mpiwg-berlin.mpg.de"); + } + + protected SessionBean getSessionBean() { + SessionBean session = + ((SessionBean)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(BEAN_SESSION)); + if(session == null){ + session = new SessionBean(); + FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(BEAN_SESSION, session); + } + return session; + } + + public void addGeneralMsg(String msg){ + System.out.println(msg); + this.getSessionBean().addGeneralMsg(msg); + } + + public void addErrorMsg(String msg){ + this.getSessionBean().addErrorMsg(msg); + } + + public void addException(Exception e){ + this.getSessionBean().addErrorMsg("Internal error: " + e.getMessage()); + } + + protected void redirect(String redirectPath, String parameters){ + FacesContext fc = FacesContext.getCurrentInstance(); + ExternalContext ec = fc.getExternalContext(); + String contextPath = ec.getRequestContextPath(); + if(StringUtils.isEmpty(redirectPath)){ + redirectPath = ec.getRequestServletPath(); + } + try { + //System.out.println(contextPath + redirectPath + parameters); + ec.redirect(ec.encodeActionURL(contextPath + redirectPath + parameters)); + + //ec.redirect(contextPath + redirectPath + parameters); + } catch (IOException e) { + e.printStackTrace(); + } + } + + protected WrapperService getWrapper() { + return getAppBean().getWrapper(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/AbstractISMIBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,1154 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +import javax.faces.context.FacesContext; +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Node; +import org.mpi.openmind.repository.bo.Relation; +import org.mpi.openmind.security.SecurityService; +import org.mpi.openmind.security.bo.User; +import org.mpiwg.itgroup.escidoc.bo.ESciDocItem; +import org.mpiwg.itgroup.escidoc.bo.Publication; +import org.mpiwg.itgroup.escidoc.utils.ESciDocItemDataTable; +import org.mpiwg.itgroup.escidoc.utils.SelectedESciDocItems; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.entry.dataBeans.SimpleSearchCache; +import de.mpiwg.itgroup.ismi.util.guiComponents.Reference; +import de.mpiwg.itgroup.ismi.util.guiComponents.ReferenceTable; +import de.mpiwg.itgroup.ismi.util.guiComponents.StatusChecker; +import de.mpiwg.itgroup.ismi.util.guiComponents.StatusImage; +import de.mpiwg.itgroup.ismi.utils.SelectableObject; + +/** + * + * @author jurzua + */ +public class AbstractISMIBean extends AbstractBean implements Serializable{ + + private static final long serialVersionUID = 9193140306343947209L; + + private static Logger logger = Logger.getLogger(AbstractISMIBean.class); + + public static String WITNESS = "WITNESS"; + public static String TEXT = "TEXT"; + public static String PERSON = "PERSON"; + public static String COLLECTION = "COLLECTION"; + public static String CODEX = "CODEX"; + public static String REPOSITORY = "REPOSITORY"; + public static String ALIAS = "ALIAS"; + public static String PLACE = "PLACE"; + public static String SUBJECT = "SUBJECT"; + public static String REFERENCE = "REFERENCE"; + public static String ROLE = "ROLE"; + public static String DIGITALIZATION = "DIGITALIZATION"; + public static String FLORUIT_DATE = "FLORUIT_DATE"; + + public static String is_digitalization_of = "is_digitalization_of"; + public static String is_part_of = "is_part_of"; + public static String is_in = "is_in"; + public static String has_subject = "has_subject"; + public static String misattributed_to = "misattributed_to"; + public static String lived_in = "lived_in"; + public static String owned_by = "owned_by"; + public static String has_role = "has_role"; + public static String was_student_of = "was_student_of"; + public static String is_alias_name_of = "is_alias_name_of"; + public static String is_prime_alias_name_of = "is_prime_alias_name_of"; + public static String is_alias_title_of = "is_alias_title_of"; + public static String is_prime_alias_title_of = "is_prime_alias_title_of"; + public static String alias = "alias"; + public static String has_floruit_date = "has_floruit_date"; + + public static String rel_was_created_by = "was_created_by"; + public static String rel_was_copied_by = "was_copied_by"; + public static String is_exemplar_of = "is_exemplar_of"; + public static String is_possible_exemplar_of = "is_possible_exemplar_of"; + public static String rel_had_patron = "had_patron"; + public static String rel_has_title_written_as = "has_title_written_as"; + public static String rel_has_author_written_as = "has_author_written_as"; + public static String rel_is_reference_of = "is_reference_of"; + + public static String rel_was_studied_by = "was_studied_by"; + + public static String PAGE_EDITOR = "entry_edit_entity"; + public static String PAGE_SIMPLE_SEARCH = "simple_search"; + public static String PAGE_MERGE = "general_merge"; + + //some attributes names + public static String name = "name"; + public static String name_translit = "name_translit"; + public static String full_title_translit = "full_title_translit"; + + public static int MAX_SUGGEST = 25; + + protected boolean selectedSaveAsNew = false; + + private HashSet<StatusChecker> statusChecker = new HashSet<StatusChecker>(); + private boolean warning = false; + private String warningMessage = ""; + private boolean displayWarning = false; + + //private PanelPopup popup = new PanelPopup(); + //private String popupText = ""; + + private String currentId; + private String currentIdMsg; + + // used in the new version + private Boolean create_error = false; + private String selectedWitnessID = "0"; + private boolean showWitness; + private boolean showTitle = false; + + private Map<String, String> attributes = new HashMap<String, String>(); + protected String defObjectClass = null; + + protected String displayUrl; + + protected Entity entity; + + protected long start; + + public String save(){ + logger.info("*************** START Saving "+ this.defObjectClass + " [ID=" + entity.getId() +", user"+ getUserName() +"] *********************"); + this.start = System.currentTimeMillis(); + return null; + } + + protected void saveEnd(){ + logger.info("*************** END Saving "+ this.defObjectClass + " [ID=" + entity.getId() +", user"+ getUserName() +"] *********************\n"); + } + + public Entity getEntity() { + if (this.entity == null) { + this.entity = new Entity(); + this.entity.setObjectClass(defObjectClass); + this.entity.setLightweight(false); + this.loadAttributes(this.entity); + } + return entity; + } + + protected void printSuccessSavingEntity(){ + this.addGeneralMsg("The entity was successfully saved!"); + this.addGeneralMsg("Its ID is " + this.entity.getId()); + } + + public void setEntity(Entity entity) { + this.entity = entity; + } + + public String getSaveButtonLabel(){ + if(entity.isPersistent()) + return "Save"; + return "Create"; + } + + public boolean isRenderSaveButton(){ + //#{(CurrentText.entity.id == null and Session.canCreate) || (CurrentText.entity.id != null and Session.canEdit)} + if((!entity.isPersistent() && getSessionBean().isCanCreate()) || + entity.isPersistent() && getSessionBean().isCanEdit()) + return true; + return false; + } + + public String clearAction(){ + System.out.println("clearAction"); + this.entity = new Entity(Node.TYPE_ABOX, this.defObjectClass, false); + this.setEntity(this.entity); + return PAGE_EDITOR; + } + + public String actionReloadEntity(){ + Long id = null; + try{ + id = new Long(this.getCurrentId()); + }catch (Exception e) {} + + if(id != null){ + Entity tmp = getWrapper().getEntityById(id); + if(tmp != null && tmp.getObjectClass().equals(this.defObjectClass)){ + this.setEntity(tmp); + }else{ + this.setCurrentIdMsg("Entity no found!"); + } + }else{ + this.setCurrentIdMsg("ID is not valid!"); + } + return PAGE_EDITOR; + } + + public String getDisplayUrl() { + return displayUrl; + } + + public void setDisplayUrl(String displayUrl) { + this.displayUrl = displayUrl; + } + + public static String generateDisplayUrl(Entity author, Entity title, Entity witness, String rootUrl){ + //example: ?personId=414996&textId=36650&witnessId=66802#witnesses + StringBuilder sb = new StringBuilder(); + if(author != null && author.isPersistent()){ + sb.append(rootUrl + "/search/displayAuthor.xhtml?"); + sb.append("personId=" + author.getId()); + if(title != null && title.isPersistent()){ + sb.append("&textId=" + title.getId()); + if(witness != null && witness.isPersistent()){ + sb.append("&witness=" + witness.getId()); + sb.append("#witnesses"); + }else{ + sb.append("#titles"); + } + } + }else if(title != null && title.isPersistent()){ + sb.append(rootUrl + "/search/displayTitle.xhtml?"); + sb.append("&textId=" + title.getId()); + if(witness != null && witness.isPersistent()){ + sb.append("&witness=" + witness.getId()); + sb.append("#witnesses"); + }else{ + sb.append("#titles"); + } + + } + return sb.toString(); + } + + //******************************** + //**** PUBLICATIONS END NOTE ***** + //******************************** + + private ReferenceTable endNoteRefTable = new ReferenceTable(); + + protected void loadEndNoteRefs(){ + this.endNoteRefTable.loadRefs(getEntRefs()); + } + + public ReferenceTable getEndNoteRefTable() { + return endNoteRefTable; + } + + public void setEndNoteRefTable(ReferenceTable endNoteRefTable) { + this.endNoteRefTable = endNoteRefTable; + } + + private List<Entity> getEntRefs(){ + List<Entity> rs = new ArrayList<Entity>(); + for (Relation rel : this.entity.getTargetRelations()) { + if (rel.getOwnValue().equals(rel_is_reference_of)) { + rs.add(getWrapper().getEntityByIdWithContent(rel.getSourceId())); + } + } + return rs; + } + + //******************************** + //**** PUBLICATIONS ESciDOC ****** + //******************************** + + private ESciDocItemDataTable refDataTable = new ESciDocItemDataTable(this); + protected SelectedESciDocItems selectedItems = new SelectedESciDocItems(); + + public ESciDocItemDataTable getRefDataTable() { + return refDataTable; + } + + public void setRefDataTable(ESciDocItemDataTable refDataTable) { + this.refDataTable = refDataTable; + } + + public void listenerRemoveReference(ActionEvent event){ + List<String> pubIdList = new ArrayList<String>(); + for(String pubId : this.selectedItems.getMap().keySet()){ + if(this.selectedItems.getMap().get(pubId)){ + pubIdList.add(pubId); + } + } + for(String pubId : pubIdList){ + this.selectedItems.removeById(pubId); + } + } + + public void loadReferences(Entity currentEntity){ + this.loadReferences(currentEntity, new ArrayList<String>()); + } + + public void loadReferences(Entity currentEntity, List<String> idsNoFound){ + this.selectedItems.setList(new ArrayList<ESciDocItem>()); + boolean escidocRespondOK = true; + try{ + + for (Relation rel : currentEntity.getTargetRelations()) { + if (rel.getOwnValue().equals(rel_is_reference_of)) { + Entity source = getWrapper().getEntityByIdWithContent(rel.getSourceId()); + ESciDocItem item = getAppBean().getRefCache().getItem(source.getOwnValue()); + if(item == null){ + item = new ESciDocItem(source.getOwnValue()); + item.setErrorLoading(ESciDocItem.ESCIDOC_ERROR_ID_NO_FOUND); + idsNoFound.add(source.getOwnValue()); + } + + /*Publication pub = ESciDocHandler.getPublicationById(source.getOwnValue()); + if(pub == null){ + pub = new Publication(source.getOwnValue()); + pub.setErrorLoading(Publication.ESCIDOC_ERROR_ID_NO_FOUND); + idsNoFound.add(source.getOwnValue()); + } + */ + Attribute att = source.getAttributeByName("additional_information"); + if(att != null){ + item.getPublication().setAdditionalInformation(att.getOwnValue()); + } + item.getPublication().setEntity(source); + this.selectedItems.addESciDocItem(item); + } + } + }catch (Exception e) { + escidocRespondOK = false; + } + this.reportEscidocError(escidocRespondOK, idsNoFound); + } + + + + protected void reportEscidocError(boolean escidocRespondOK, List<String> idsNoFound){ + if(!escidocRespondOK){ + addGeneralMsg("The references could not be loaded. The server did not respond."); + addGeneralMsg("Exception connecting to http://escidoc.mpiwg-berlin.mpg.de:8080 "); + } + + if(!idsNoFound.isEmpty()){ + addGeneralMsg("The following references were not found in Pubman server:"); + StringBuilder sb = new StringBuilder(); + int count = 0; + for(String id : idsNoFound){ + if(count > 0){ + sb.append(", "); + } + sb.append(id); + } + addGeneralMsg(sb.toString()); + } + + } + + protected void prepareEndNoteRefs2Save() throws Exception{ + //REFERENCE -> is_reference_of -> WITNESS + this.entity.removeAllTargetRelationsByName(rel_is_reference_of); + for(SelectableObject<Reference> so : this.endNoteRefTable.list){ + Reference ref = so.getObj(); + + Entity entRef = ref.getEnt(); + getWrapper().saveAssertion(entRef, getUserName()); + //entity can be no persistent, therefore the assignment of the relation should be done after the save + entRef.addSourceRelation(rel_is_reference_of, entity); + //new Relation(entRef, entity, rel_is_reference_of); + } + } + + protected Entity prepareESciDocRefs2Save(Entity currentEntity) throws Exception{ + //REFERENCE -> is_reference_of -> WITNESS + currentEntity.removeAllTargetRelationsByName(rel_is_reference_of); + for(ESciDocItem item : this.selectedItems.getList()){ + Publication pub = item.getPublication(); + if(pub.getEntity() == null){ + Entity pubEntity = new Entity(Node.TYPE_ABOX, REFERENCE, false); + pubEntity.setOwnValue(pub.getObjid()); + pubEntity.addAttribute(new Attribute("id", "escidoc-objid", pub.getObjid())); + if(StringUtils.isNotEmpty(pub.getAdditionalInformation())){ + pubEntity.addAttribute(new Attribute("additional_information", "text", pub.getAdditionalInformation())); + } + pubEntity = getWrapper().saveEntity(pubEntity, getUserName()); + pub.setEntity(pubEntity); + }else{ + if(pub.getEntity().getAttributeByName("additional_information") != null){ + pub.getEntity().getAttributeByName("additional_information").setOwnValue(pub.getAdditionalInformation()); + }else{ + pub.getEntity().addAttribute(new Attribute("additional_information", "text", pub.getAdditionalInformation())); + } + pub.setEntity(getWrapper().saveEntity(pub.getEntity(), getUserName())); + } + Relation rel = new Relation(pub.getEntity(), currentEntity, rel_is_reference_of); + } + return currentEntity; + } + + public static de.mpiwg.itgroup.ismi.util.guiComponents.Calendar updateCalendar(Attribute att){ + de.mpiwg.itgroup.ismi.util.guiComponents.Calendar calendar = null; + if(att != null && StringUtils.isNotEmpty(att.getOwnValue())){ + calendar = new de.mpiwg.itgroup.ismi.util.guiComponents.Calendar(att.getOwnValue()); + }else{ + calendar = new de.mpiwg.itgroup.ismi.util.guiComponents.Calendar(); + } + return calendar; + } + + protected void loadAttributes(Entity entity) { + attributes = new HashMap<String, String>(); + if (entity != null) { + for (Attribute defAtt : getWrapper().getDefAttributes(this.defObjectClass)) { + Attribute originalAtt = entity.getAttributeByName(defAtt + .getOwnValue()); + String attValue = (originalAtt != null) ? originalAtt + .getOwnValue() : ""; + attributes.put(defAtt.getOwnValue(), attValue); + } + } else { + for (Attribute defAtt : getWrapper().getDefAttributes(this.defObjectClass)) { + attributes.put(defAtt.getOwnValue(), ""); + } + } + } + + public void reset(){ + this.setSelectedSaveAsNew(false); + this.setCurrentId(""); + this.setCurrentIdMsg(""); + this.setAttributes(new HashMap<String, String>()); + this.selectedItems = new SelectedESciDocItems(); + this.displayUrl = null; + this.endNoteRefTable = new ReferenceTable(); + } + + public boolean isSelectedSaveAsNew() { + return selectedSaveAsNew; + } + + public void setSelectedSaveAsNew(boolean selectedSaveAsNew) { + this.selectedSaveAsNew = selectedSaveAsNew; + } + + /** + * <p> + * "Entity -> CurrentEntity" + * </p> + * <p> + * This method updates the attributes of the given entity with the + * attributes of the attributes Map<String, String>. + * </p> + * + * @return the input's entity with updated attributes. + */ + public Entity updateEntityAttributes(Entity entity) { + if (entity == null) { + entity = new Entity(Node.TYPE_ABOX, false); + //entity.setObjectClass(getDefinition().getOwnValue()); + entity.setObjectClass(this.defObjectClass); + } + //for (Attribute defAtt : getDefinition(entity).getAttributes()) { + for (Attribute defAtt : getWrapper().getDefAttributes(this.defObjectClass)) { + Attribute att = entity.getAttributeByName(defAtt.getOwnValue()); + if (StringUtils.isNotEmpty(this.attributes + .get(defAtt.getOwnValue()))) { + if (att == null) { + att = new Attribute(defAtt); + entity.addAttribute(att); + } + att.setOwnValue(this.attributes.get(defAtt.getOwnValue())); + att.setObjectClass(defAtt.getOwnValue()); + } else if (att != null) { + // the attribute must be deleted. + entity.getAttributes().remove(att); + } + } + return entity; + } + + protected List<SelectItem> updateSuggestedPersonByRole(String searchWord, String objClass, String attName, String role){ + List<Attribute> attList = getWrapper().getAttributesByDefByAttName(objClass, attName, searchWord.toString(), -1); + + List<SelectItem> suggestedItems = new ArrayList<SelectItem>(); + if (attList == null) + return suggestedItems; + + int count = 0; + for (Attribute att : attList) { + if(getCache().roleContainsPersonId(role, att.getSourceId())){ + SelectItem item = new SelectItem(att, att.getOwnValue() + " [" + att.getSourceId() + "]","description: " + att); + suggestedItems.add(item); + count++; + if(count == MAX_SUGGEST) + break; + } + } + return suggestedItems; + } + + protected List<SelectItem> updateSuggestedItems(ValueChangeEvent event, + String objClass, String attName) { + return updateSuggestedItems((String) event.getNewValue(), objClass, + attName); + } + + protected List<SelectItem> updateSuggestedItems(String searchWord, + String objClass, String attName) { + + List<Attribute> attList = getWrapper().getAttributesByDefByAttName(objClass, attName, searchWord.toString(), MAX_SUGGEST); + + List<SelectItem> suggestedItems = new ArrayList<SelectItem>(); + if (attList == null) + return suggestedItems; + + for (Attribute att : attList) { + SelectItem item = new SelectItem(att, att.getOwnValue() + " [" + att.getSourceId() + "]", + "description: " + att); + suggestedItems.add(item); + } + return suggestedItems; + } + + protected SimpleSearchCache getCache(){ + return getAppBean().getSimpleSearchCache(); + } + + protected List<SelectItem> updateSuggestedItems(String objClass, + String firstName, String firstValue, String secondName, + String secondValue) { + + List<Attribute> attList = + getWrapper(). + searchAttribute(firstName, firstValue, secondName, secondValue, objClass, MAX_SUGGEST); + + List<SelectItem> suggestedItems = new ArrayList<SelectItem>(); + if (attList == null) + return suggestedItems; + + for (Attribute att : attList) { + SelectItem item = new SelectItem(att, att.getOwnValue() + " [" + att.getSourceId() + "]"); + suggestedItems.add(item); + } + return suggestedItems; + } + + public Map<String, String> getAttributes() { + return attributes; + } + + public void setAttributes(Map<String, String> attributes) { + this.attributes = attributes; + } + + /** + * <p> + * This method plays the role of a small cache to get quickly the + * definitions. + * </p> + * TODO this method must be implemented into a bean in session context and + * research by every beans. + * + * @param assertion + * @return + */ + public Entity getLWDefinition(Entity assertion) { + return getWrapper().getDefinition(assertion.getObjectClass()); + } + + public Entity getLWDefinition(String objClass) { + return getWrapper().getDefinition(objClass); + } + + /** + * <p> + * Returns the target's entity of a relation. The returned target is no + * light weight. + * <p> + * + * @param rel + * @param target + * @return + */ + protected Entity getTargetRelation(Relation rel) { + Entity target = rel.getTarget(); + if (target == null) { + target = getWrapper().getEntityById(rel.getTargetId()); + rel.setTarget(target); + } else if (target.isLightweight()) { + target = getWrapper().getEntityContent(target); + } + return target; + } + + protected Attribute getTargetAttribute(Entity target, String name) { + Attribute att = getWrapper().getAttributeByName(target.getId(), name); + + if (att == null) { + att = new Attribute(); + att.setOwnValue(target.getOwnValue()); + } + return att; + } + + protected WrapperService getWrapper() { + return getAppBean().getWrapper(); + } + + /** + * <p> + * Return the <code>FacesContext</code> instance for the current request. + */ + protected FacesContext context() { + return (FacesContext.getCurrentInstance()); + } + + public void setCreate_error(Boolean create_error) { + this.create_error = create_error; + } + + public Boolean getCreate_error() { + return create_error; + } + + /** + * Eine Liste <code>toBeRestricted</code> wird so eingeschraenkt, dass nur + * noch die jenigen uebrig bleiben, die �ber die Relation + * <code>relation</code> mit einem der Elemente aus + * <code>contraintIds</code> verbunden sind. + * + * @param toBeRestricted + * @param constraintIds + * @param relation + * @param mode + * @return + */ + protected List<SelectItem> restrictList(List<SelectItem> toBeRestricted, + List<String> constraintIds, String relation, String mode) { + + List<SelectItem> newList = new ArrayList<SelectItem>(); + + for (SelectItem s : toBeRestricted) { + Entity ent = getWrapper().getEntityById( + Long.valueOf((String) s.getValue())); + if (s.getValue().equals("0")) { + newList.add(s); + continue; + } + + List<Relation> rels; + if (mode.equals("target")) { + rels = ent.getTargetRelations(); + } else if (mode.equals("source")) { + rels = ent.getSourceRelations(); + } else { + System.err.println("restrict List - mode not defined:" + mode); + return null; + } + + for (Relation r : rels) { + if (r.getObjectClass().equals(relation)) { + Long id; + if (mode.equals("target")) { + id = r.getSource().getId(); + } else if (mode.equals("source")) { + id = r.getTarget().getId(); + } else { + System.err.println("restrict List - mode not defined:" + + mode); + return null; + } + if (constraintIds.contains(String.valueOf(id))) { + newList.add(s); + } + } + } + } + + return newList; + } + + public String getSelectedWitnessID() { + return selectedWitnessID; + } + + public void setShowWitness(boolean showWitness) { + this.showWitness = showWitness; + } + + public boolean isShowWitness() { + return showWitness; + } + + public void setShowTitle(boolean showTitle) { + this.showTitle = showTitle; + } + + public boolean isShowTitle() { + return showTitle; + } + /* + public PanelPopup getPopup() { + return popup; + } + + public void setPopup(PanelPopup popup) { + this.popup = popup; + } + + public String getPopupText() { + return popupText; + } + + public void setPopupText(String popupText) { + this.popupText = popupText; + }*/ + + + public String getUserName(){ + User user = getSessionUser(); + if(user == null) + return ""; + else + return user.getEmail(); + } + + public User getSessionUser() { + SessionBean bean = getSessionBean(); + if(bean != null){ + return bean.getUser(); + }else{ + return null; + } + } + + public void fillList(List<SelectItem> list, String[] array) { + list.add(new SelectItem("")); + for (int i = 0; i < array.length; i++) { + list.add(new SelectItem(array[i])); + } + + } + + public boolean isWarning() { + return warning; + } + + public void setWarning(boolean warning) { + this.warning = warning; + } + + public void setWarningMessage(String warningMessage) { + this.warningMessage = warningMessage; + } + + public String getWarningMessage() { + return warningMessage; + } + + public void setDisplayWarning(boolean displayWarning) { + this.displayWarning = displayWarning; + } + + public boolean isDisplayWarning() { + return displayWarning; + } + + public void registerChecker(StatusChecker sc) { + statusChecker.add(sc); + } + + public void registerChecker(ListenerObject lo, String message) { + registerChecker(lo.statusImage, message); + + } + + public void registerChecker(StatusChecker sc, String message) { + sc.setMessage(message); + statusChecker.add(sc); + } + + class CheckResults { + List<String> errors = new ArrayList<String>(); + List<String> warnings = new ArrayList<String>(); + public boolean hasErrors = false; + public boolean hasWarnings = false; + + } + + public CheckResults getCheckResults() { + CheckResults cr = new CheckResults(); + + for (StatusChecker sc : statusChecker) { + if (sc.getStatus().equals("false")) { + cr.hasErrors = true; + cr.errors.add(sc.getMessage()); + } else if (sc.getStatus().equals("unset")) { + cr.hasWarnings = true; + cr.warnings.add(sc.getMessage()); + } + } + return cr; + } + + protected ListenerObject changeValue(String ownvalue, ListenerObject lo, String suggestType, String suggestAttributeName, + List<SelectItem> restrictedItems) { + if (restrictedItems != null) { + lo.suggestedItems = restrictedItems;} + + if (ownvalue == null || ownvalue.equals("")) + lo.statusImage.setStatus("unset"); + else + lo.statusImage.setStatus("false"); + lo.entity = null; + // setze erst mal den Eigenwert auf das eingebene. + Attribute at = new Attribute(); + at.setOwnValue(ownvalue); + lo.attribute = at; + Entity element = null; + if (lo.suggestedItems != null) // schaue in der liste der vorgebenen Ereignisse nach. + for (SelectItem item : lo.suggestedItems) { + if (item.getLabel().equals(ownvalue)) { + if (Attribute.class.isInstance(item.getValue())){ // entweder es ist schon ein attribute + lo.attribute = (Attribute) item.getValue(); + element = getWrapper().getEntityById( + lo.attribute.getSourceId()); + }else{ //oder ein paar wert / id// = (Attribute) item.getValue(); + element = getWrapper().getEntityById(Long.valueOf((String) item.getValue())); + lo.setEntityAndAttribute(element, suggestAttributeName); + } + if (element != null) { + if(element.isLightweight()){ + element = getWrapper().getEntityByIdWithContent(element.getId()); + } + lo.entity = element; + lo.statusImage.setStatus("ok"); + } + break; + } + + } else { + //juc *** List<Entity> ents = getWrapper().getLightweightConceptsByAttribute(null, suggestType, suggestAttributeName, ownvalue, 1, false); + List<Entity> ents = getWrapper().getEntitiesByAtt(suggestType, suggestAttributeName, ownvalue, 1, false); + if (ents.size()==1){ + lo.setEntityAndAttribute(ents.get(0),suggestAttributeName); + lo.statusImage.setStatus("ok"); + } + + } + return lo; + + } + + + + protected ListenerObject changeValuePersonByRole(ValueChangeEvent event, ListenerObject lo, String role){ + if (event.getNewValue() == null) { + return lo; + }else if(StringUtils.isEmpty(event.getNewValue().toString()) && (event.getOldValue() == null || StringUtils.isEmpty(event.getOldValue().toString()))){ + //if the old and new value are empty, then return + return lo; + } + if (event.getNewValue().equals(event.getOldValue())) { + return lo; + } + + String ownValue = (String) event.getNewValue(); + + if(StringUtils.isEmpty(ownValue)) + lo.statusImage.setStatus("unset"); + else + lo.statusImage.setStatus("false"); + + lo.entity = null; + // setze erst mal den Eigenwert auf das eingebene. + Attribute at = new Attribute(); + at.setOwnValue(ownValue); + lo.attribute = at; + for (SelectItem item : lo.suggestedItems) { + if (StringUtils.isNotEmpty(item.getLabel()) && + item.getLabel().equals(ownValue)) { + //System.out.println("item.getValue()= " + item.getValue()); + lo.attribute = (Attribute) item.getValue(); + Entity element = getWrapper().getEntityById( + lo.attribute.getSourceId()); + + if (element != null) { + if(element.isLightweight()){ + element = getWrapper().getEntityByIdWithContent(element.getId()); + } + lo.entity = element; + lo.statusImage.setStatus(StatusImage.STATUS_OK); + } + break; + } + + } + + //juc lo.suggestedItems = updateSuggestedPersonByRole(ownValue, PERSON, "name", role); + lo.suggestedItems = updateSuggestedPersonByRole(ownValue, PERSON, "name_translit", role); + + + return lo; + } + + protected ListenerObject changeValue(String ownvalue, ListenerObject lo, + String suggestType, String suggestAttributeName) { + + return changeValue(ownvalue, lo, suggestType, suggestAttributeName, + null); + } + + protected ListenerObject changeListener(ValueChangeEvent event, + ListenerObject lo, String suggestType, String suggestAttributeName, + String restrictingAttributeName, String restrictingAttributeValue) { + try { + if (event.getNewValue() == null) { + return lo; + }else if(StringUtils.isEmpty(event.getNewValue().toString()) && (event.getOldValue() == null || StringUtils.isEmpty(event.getOldValue().toString()))){ + //if the old and new value are empty, then return + return lo; + } + if (event.getNewValue().equals(event.getOldValue())) { + return lo; + } + + String ownvalue = (String) event.getNewValue(); + + if(StringUtils.isEmpty(ownvalue)) + lo.statusImage.setStatus(StatusImage.STATUS_UNSET); + else + lo.statusImage.setStatus(StatusImage.STATUS_FALSE); + + lo.entity = null; + // setze erst mal den Eigenwert auf das eingebene. + Attribute at = new Attribute(); + at.setOwnValue(ownvalue); + lo.attribute = at; + for (SelectItem item : lo.suggestedItems) { + if (StringUtils.isNotEmpty(item.getLabel()) && + item.getLabel().equals(ownvalue)) { + //System.out.println("item.getValue()= " + item.getValue()); + lo.attribute = (Attribute) item.getValue(); + Entity element = getWrapper().getEntityById( + lo.attribute.getSourceId()); + + if (element != null) { + if(element.isLightweight()){ + element = getWrapper().getEntityByIdWithContent(element.getId()); + } + lo.entity = element; + lo.statusImage.setStatus(StatusImage.STATUS_OK); + } + break; + } + + } + + if (restrictingAttributeName == null) { + lo.suggestedItems = this.updateSuggestedItems(event, + suggestType, suggestAttributeName); + } else { + lo.suggestedItems = this.updateSuggestedItems(suggestType, + suggestAttributeName, event.getNewValue().toString(), + restrictingAttributeName, restrictingAttributeValue); + } + + } catch (Exception e) { + e.printStackTrace(); + } + return lo; + } + + protected void generateSecundaryOW(Entity entity, String user) throws Exception{ + List<Entity> nodeList = new ArrayList<Entity>(); + + long start = System.currentTimeMillis(); + if(entity.getObjectClass().equals(PLACE)){ + this.generateOW4City(entity, nodeList, user); + long medium = System.currentTimeMillis(); + System.out.println("nodeList.size(): " + nodeList.size() + " time: " + (medium - start)); + getWrapper().saveEntityListAsNodeWithoutContent(nodeList, user); + System.out.println("Save time: " + (System.currentTimeMillis() - medium)); + }else if(entity.getObjectClass().equals(REPOSITORY)){ + this.generateOW4Repository(entity, nodeList, new HashMap<String, String>(), user); + long medium = System.currentTimeMillis(); + System.out.println("nodeList.size(): " + nodeList.size() + " time: " + (medium - start)); + getWrapper().saveEntityListAsNodeWithoutContent(nodeList, user); + System.out.println("Save time: " + (System.currentTimeMillis() - medium)); + }else if(entity.getObjectClass().equals(COLLECTION)){ + this.generateOW4Collection(entity, nodeList, new HashMap<String, String>(), user); + long medium = System.currentTimeMillis(); + System.out.println("nodeList.size(): " + nodeList.size() + " time: " + (medium - start)); + getWrapper().saveEntityListAsNodeWithoutContent(nodeList, user); + System.out.println("Save time: " + (System.currentTimeMillis() - medium)); + }else if(entity.getObjectClass().equals(CODEX)){ + this.generateOW4Codex(entity, nodeList, new HashMap<String, String>(), user); + long medium = System.currentTimeMillis(); + System.out.println("nodeList.size(): " + nodeList.size() + " time: " + (medium - start)); + getWrapper().saveEntityListAsNodeWithoutContent(nodeList, user); + System.out.println("Save time: " + (System.currentTimeMillis() - medium)); + }else if(entity.getObjectClass().equals(TEXT)){ + generateOW4Text(entity, user); + long medium = System.currentTimeMillis(); + System.out.println("Saving witnessList time: " + (medium - start)); + } + //TODO PERSON and TEXT + } + + private void generateOW4City(Entity city, List<Entity> nodeList, String user){ + Map<String, String> map = new HashMap<String, String>(); + map.put(PLACE, city.getOwnValue()); + + List<Entity> repoList = getWrapper().getSourcesForTargetRelation(city, is_in, REPOSITORY, -1); + for(Entity repo : repoList){ + this.generateOW4Repository(repo, nodeList, map, user); + } + } + + private void generateOW4Repository(Entity repository, List<Entity> nodeList, Map<String, String> map, String user){ + if(map.size() == 0){ + List<Entity> placeList = getWrapper().getTargetsForSourceRelation(repository, is_in, PLACE, 1); + map.put(PLACE, ((placeList.size() > 0) ? placeList.get(0).getOwnValue() : "")); + } + + map.put(REPOSITORY, repository.getOwnValue()); + List<Entity> collectionList = getWrapper().getSourcesForTargetRelation(repository, is_part_of, COLLECTION, -1); + for(Entity collection : collectionList){ + this.generateOW4Collection(collection, nodeList, map, user); + } + } + + private void generateOW4Collection(Entity collection, List<Entity> nodeList, Map<String, String> map, String user){ + if(map.size() == 0){ + List<Entity> repoList = getWrapper().getTargetsForSourceRelation(collection, is_part_of, REPOSITORY, 1); + map.put(REPOSITORY, (repoList.size() > 0) ? repoList.get(0).getOwnValue() : ""); + if(repoList.size() > 0){ + Entity repository = repoList.get(0); + List<Entity> placeList = getWrapper().getTargetsForSourceRelation(repository, is_in, PLACE, 1); + map.put(PLACE, (placeList.size() > 0) ? placeList.get(0).getOwnValue() : ""); + }else{ + map.put(REPOSITORY, ""); + map.put(PLACE, ""); + } + } + + map.put(COLLECTION, collection.getOwnValue()); + List<Entity> list = getWrapper().getSourcesForTargetRelation(collection, is_part_of, CODEX, -1); + for(Entity codex : list){ + //update ow codex + Attribute att = getWrapper().getAttributeByName(codex.getId(), "identifier"); + if(att != null){ + codex.setOwnValue(collection.getOwnValue() + "_" + att.getOwnValue()); + nodeList.add(codex); + } + this.generateOW4Codex(codex, nodeList, map, user); + } + } + + private void generateOW4Codex(Entity codex, List<Entity> nodeList, Map<String, String> map, String user){ + if(map.size() == 0){ + List<Entity> collList = getWrapper().getTargetsForSourceRelation(codex, is_part_of, COLLECTION, 1); + map.put(COLLECTION, (collList.size() > 0 ) ? collList.get(0).getOwnValue() : ""); + if(collList.size() > 0){ + Entity collection = collList.get(0); + List<Entity> repoList = getWrapper().getTargetsForSourceRelation(collection, is_part_of, REPOSITORY, 1); + map.put(REPOSITORY, (repoList.size() > 0) ? repoList.get(0).getOwnValue() : ""); + if(repoList.size() > 0){ + Entity repository = repoList.get(0); + List<Entity> placeList = getWrapper().getTargetsForSourceRelation(repository, is_in, PLACE, 1); + map.put(PLACE, (placeList.size() > 0) ? placeList.get(0).getOwnValue() : ""); + }else{ + map.put(PLACE, ""); + } + }else{ + map.put(COLLECTION, ""); + map.put(REPOSITORY, ""); + map.put(PLACE, ""); + } + } + List<Entity> list = getWrapper().getSourcesForTargetRelation(codex, is_part_of, WITNESS, -1); + String placeText = (StringUtils.isNotEmpty(map.get(PLACE))) ? "_" + map.get(PLACE) : ""; + String repoText = (StringUtils.isNotEmpty(map.get(REPOSITORY))) ? "_" + map.get(REPOSITORY) : ""; + String codexText = (codex != null) ? "_" + codex.getOwnValue() : ""; + + for(Entity witness : list){ + List<Entity> textList = getWrapper().getTargetsForSourceRelation(witness, "is_exemplar_of", TEXT, -1); + String textName = (textList.size() > 0) ? textList.get(0).getOwnValue() : ""; + witness.setOwnValue(textName + placeText + repoText + codexText); + nodeList.add(witness); + } + } + + private void generateOW4Text(Entity text, String user) throws Exception{ + List<Entity> witnessList = getWrapper().getSourcesForTargetRelation(text, "is_exemplar_of", WITNESS, -1); + List<Entity> listToSave = new ArrayList<Entity>(); + for(Entity witness : witnessList){ + List<Entity> list = getWrapper().getTargetsForSourceRelation(witness, "is_part_of", "CODEX", 1); + if(list.size() > 0){ + Entity codex = list.get(0); + list = getWrapper().getTargetsForSourceRelation(codex, "is_part_of", "COLLECTION", 1); + if(list.size() > 0){ + Entity collection = list.get(0); + list = getWrapper().getTargetsForSourceRelation(collection, "is_part_of", "REPOSITORY", 1); + if(list.size() > 0){ + Entity repository = list.get(0); + list = getWrapper().getTargetsForSourceRelation(repository, "is_in", "PLACE", 1); + if(list.size() > 0){ + Entity city = list.get(0); + witness.setOwnValue(text.getOwnValue() + "_" + city.getOwnValue() + "_" + repository.getOwnValue() + "_" + codex.getOwnValue()); + listToSave.add(witness); + } + } + } + } + getWrapper().saveEntityListAsNodeWithoutContent(listToSave, user); + } + } + + protected SecurityService getSecurityService() { + return getAppBean().getSecurityService(); + } + + protected ListenerObject changeListener(ValueChangeEvent event, + ListenerObject lo, String suggestType, String suggestAttributeName) { + + return changeListener(event, lo, suggestType, suggestAttributeName, + null, null); + } + + public String getCurrentId() { + return currentId; + } + + public void setCurrentId(String currentId) { + this.currentId = currentId; + } + + public String getCurrentIdMsg() { + return currentIdMsg; + } + + public void setCurrentIdMsg(String currentIdMsg) { + this.currentIdMsg = currentIdMsg; + } + + public SelectedESciDocItems getSelectedItems() { + return selectedItems; + } + + public void setSelectedItems(SelectedESciDocItems selectedItems) { + this.selectedItems = selectedItems; + } + + public String getDefObjectClass() { + return defObjectClass; + } + + public void setDefObjectClass(String defObjectClass) { + this.defObjectClass = defObjectClass; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/ApplicationBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,589 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.faces.context.FacesContext; +import javax.faces.model.SelectItem; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.configuration.ConfigurationService; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.services.ServiceRegistry; +import org.mpi.openmind.search.SearchService; +import org.mpi.openmind.security.SecurityService; +import org.mpiwg.itgroup.escidoc.ESciDocCache; + +import de.mpiwg.itgroup.ismi.entry.dataBeans.SimpleSearchCache; +import de.mpiwg.itgroup.ismi.publicView.PublicCodexList; + +/** + * <p> + * Application scope data bean for your application. Create properties here to + * represent cached data that should be made available to all users and pages in + * the application. + * </p> + * + * <p> + * An instance of this class will be created for you automatically, the first + * time your application evaluates a value binding expression or method binding + * expression that references a managed bean using this class. + * </p> + * + * @version ApplicationBean1.java + * @version Created on 23.06.2009, 10:58:17 + * @author jurzua + */ + +public class ApplicationBean implements Serializable{ + + private static final long serialVersionUID = 804932192506497432L; + + private static Logger logger = Logger.getLogger(ApplicationBean.class); + + public static String urlISMIExportServiceAuthors = + "http://ismi-dev.mpiwg-berlin.mpg.de/ISMI/database/export/authorsTitlesWitness"; + + public static String urlISMIExportServiceTitles = + "http://ismi-dev.mpiwg-berlin.mpg.de/ISMI/database/export/titlesWitnesses"; + + private BiographyBean biographyBean; + + private PublicCodexList publicCodexList; + + public ESciDocCache refCache = new ESciDocCache(); + + public static String generateExportURL(String urlRoot, List<Long> list, String mode){ + StringBuilder sb = new StringBuilder(urlRoot); + + sb.append("?ids=" + generateIdList(list)); + + if(StringUtils.isNotEmpty(mode)){ + sb.append("&mode=" + mode); + } + + return sb.toString(); + } + + public static String generateIdList(List<Long> list){ + StringBuilder sb = new StringBuilder(); + + int count = 0; + for(Long id : list){ + + if(count>0){ + sb.append("%7C"); + } + sb.append(id); + count++; + } + return sb.toString(); + } + + public static String generateExportURL(String urlRoot, String idList, String mode){ + StringBuilder sb = new StringBuilder(urlRoot); + + sb.append("?ids=" + idList); + if(StringUtils.isNotEmpty(mode)){ + sb.append("&mode=" + mode); + } + + return sb.toString(); + } + + + public static String generateExportURL(String urlRoot, Long id, String mode){ + StringBuilder sb = new StringBuilder(urlRoot); + + sb.append("?ids=" + id); + if(StringUtils.isNotEmpty(mode)){ + sb.append("&mode=" + mode); + } + + return sb.toString(); + } + + public static String CURRENT_WITNESS = "CurrentWitness"; + public static String CURRENT_CODEX = "CurrentCodex"; + public static String CURRENT_TEXT = "CurrentText"; + public static String CURRENT_PERSON = "CurrentPerson"; + public static String CURRENT_ALIAS = "CurrentAlias"; + public static String CURRENT_COLLECTION = "CurrentCollection"; + public static String CURRENT_REPOSITORY = "CurrentRepository"; + public static String CURRENT_CITY = "CurrentCity"; + public static String CURRENT_SUBJECT = "CurrentSubject"; + public static String CURRENT_ROLE = "CurrentRole"; + public static String CURRENT_DIGI = "CurrentDigi"; + + private transient SimpleSearchCache simpleSearchCache; + ServiceRegistry serviceRegistry = null; + + + private List<SelectItem> roleList = new ArrayList<SelectItem>(); + private List<Entity> entityRoleList = new ArrayList<Entity>(); + private boolean roleListDirty = true; + + private static List<SelectItem> yes_no = new ArrayList<SelectItem>(); + private static List<SelectItem> roles = new ArrayList<SelectItem>(); + + private static List<SelectItem> suggestedStatus = new ArrayList<SelectItem>(); + private static List<SelectItem> suggestedBindings = new ArrayList<SelectItem>(); + private static List<SelectItem> writingSurfaces = new ArrayList<SelectItem>(); + private static List<SelectItem> pageLayout = new ArrayList<SelectItem>(); + private static List<SelectItem> scripts = new ArrayList<SelectItem>(); + private static List<SelectItem> sourcesOfInformation = new ArrayList<SelectItem>(); + private static List<SelectItem> suggestedLanguages = new ArrayList<SelectItem>(); + private static List<SelectItem> suggestedTextTypes = new ArrayList<SelectItem>(); + private static List<SelectItem> suggestedBoolean = new ArrayList<SelectItem>(); + + + public static String STATUS_NEED_VERIFICATION = "needs verification"; + public static String STATUS_VERIFIED_BY_CATALOGUE = "verified by catalogue"; + public static String STATUS_VERIFIED_BY_WITNESS = "verified by witness"; + public static String STATUS_NOT_CHECKED = "not checked"; + + public static String FORMATED_DATE = "formatted date"; + public static String PLAIN_DATE = "plain date"; + private static List<SelectItem> dateTypes = new ArrayList<SelectItem>(); + + private List<SelectItem> suggestedSubjects = null; + + public void resetSuggestedSubjects(){ + this.suggestedSubjects = new ArrayList<SelectItem>(); + this.suggestedSubjects.add(new SelectItem(null, "-- choose --")); + + List<Entity> cats = getWrapper().getEntitiesByAtt("SUBJECT", "type", "main_subject", -1, false); + + for(Entity cat : cats){ + SelectItem item = new SelectItem(cat.getId(), cat.getOwnValue()); + + item.setStyle("font-weight: bold; padding-left: 0px; font-size: 14;"); + this.suggestedSubjects.add(item); + List<Entity> subCats = getWrapper().getSourcesForTargetRelation(cat, "is_part_of", "SUBJECT", -1); + for(Entity subCat : subCats){ + + item = new SelectItem(subCat.getId(), subCat.getOwnValue()); + item.setStyle("padding-left: 10px; font-size: 12;"); + this.suggestedSubjects.add(item); + + List<Entity> subsubCats = getWrapper().getSourcesForTargetRelation(subCat, "is_part_of", "SUBJECT", -1); + for(Entity subsubCat : subsubCats){ + if(subsubCat != null){ + item = new SelectItem(subsubCat.getId(), subsubCat.getOwnValue()); + + this.suggestedSubjects.add(item); + + }else{ + + System.out.println("####################ERROR####################"); + System.out.println("resetSuggestedSubjects"); + System.out.println(" main: " + cat); + System.out.println(" sub: " + subCat); + } + } + } + } + } + + public List<SelectItem> getSuggestedSubjects() { + if(suggestedSubjects == null){ + this.resetSuggestedSubjects(); + } + return suggestedSubjects; + } + + public void setSuggestedSubjects(List<SelectItem> suggestedSubjects) { + this.suggestedSubjects = suggestedSubjects; + } + + public void listenerSynchronizeESciDocCacheWithServer(){ + this.refCache.synchronizeWithServer(); + } + + static{ + + dateTypes.add(new SelectItem(FORMATED_DATE)); + dateTypes.add(new SelectItem(PLAIN_DATE)); + + String[] status = new String[]{"needs verification", "verified by catalogue", "verified by witness"}; + Arrays.sort(status); + + suggestedStatus.add(new SelectItem("", STATUS_NOT_CHECKED)); + for(int i=0; i< status.length; i++){ + suggestedStatus.add(new SelectItem(status[i])); + } + + String[] binding = new String[]{"cardboard", "leather with flap", "leather without flap"}; + Arrays.sort(binding); + + suggestedBindings.add(new SelectItem("", "-- choose --")); + for(int i=0; i< binding.length; i++){ + suggestedBindings.add(new SelectItem(binding[i])); + } + + + String[] langs = new String[] { "Arabic", "Persian-Farsi", + "Greek-classical", "Hebrew", "Latin", "Syriac", "Armenian", + "Castillian", "Catalan", "Chinese", "French", "German", + "Greek-Byzantine", "Hindi", "Italian", "Mongolian", + "Persian-Old", "Persian-Middle", "Russian", "Sanskrit", + "Turkish (Ottoman pre-1839)", "Turkish (Ottoman 1839-)", + "Turkish (pre-Ottoman)", "Turkish-Republican", "Urdu", "Uighur" }; + Arrays.sort(langs); + + suggestedLanguages.add(new SelectItem("", "-- choose --")); + for(int i = 0; i < langs.length; i++){ + suggestedLanguages.add(new SelectItem(langs[i])); + } + + String[] tts = new String[] { + "First-order prose composition (or compilation) [matn]", + "First-order verse composition (didactic poem)", + "Second-order composition (Commentary) [sharh]", + "Third-order composition (Supercommentary)", + "Fourth-order composition (Gloss)", + "Fifth-order composition (Supergloss)", + "Sixth-order composition", "Seventh-order composition", + "Rearrangement", "Abridgement (epitome)", "Versification", + "Translation", "Paraphrase", "Supplement" }; + Arrays.sort(tts); + + suggestedTextTypes.add(new SelectItem("", "-- choose --")); + for(int i = 0; i < tts.length; i++){ + suggestedTextTypes.add(new SelectItem(tts[i])); + } + + yes_no.add(new SelectItem("", "-- choose --")); + yes_no.add(new SelectItem("yes")); + yes_no.add(new SelectItem("no")); + + suggestedBoolean.add(new SelectItem("", "-- choose --")); + suggestedBoolean.add(new SelectItem("true")); + suggestedBoolean.add(new SelectItem("false")); + + roles.add(new SelectItem("", "-- choose --")); + roles.add(new SelectItem("annotator")); + roles.add(new SelectItem("author")); + roles.add(new SelectItem("copyist")); + roles.add(new SelectItem("illuminator")); + roles.add(new SelectItem("illustrator")); + roles.add(new SelectItem("owner")); + roles.add(new SelectItem("patron")); + roles.add(new SelectItem("reader")); + roles.add(new SelectItem("student")); + roles.add(new SelectItem("teacher")); + roles.add(new SelectItem("translator")); + + writingSurfaces.add(new SelectItem("", "-- choose --")); + writingSurfaces.add(new SelectItem("HARD", "HARD")); + writingSurfaces.add(new SelectItem("marble", " marble")); + writingSurfaces.add(new SelectItem("metal instrument", " metal instrument")); + writingSurfaces.add(new SelectItem("stone", " stone")); + writingSurfaces.add(new SelectItem("SOFT", "SOFT")); + writingSurfaces.add(new SelectItem("paper", " paper")); + writingSurfaces.add(new SelectItem("papyrus", " papyrus")); + writingSurfaces.add(new SelectItem("parchment", " parchment")); + + pageLayout.add(new SelectItem("", "-- choose --")); + pageLayout.add(new SelectItem("Frame-ruled")); + pageLayout.add(new SelectItem("Paper")); + + scripts.add(new SelectItem("", "-- choose --")); + scripts.add(new SelectItem("Maghribi")); + scripts.add(new SelectItem("Naskh")); + scripts.add(new SelectItem("Nasta'liq")); + scripts.add(new SelectItem("Riqa'")); + scripts.add(new SelectItem("Ruq'ah")); + scripts.add(new SelectItem("Shikastah")); + scripts.add(new SelectItem("Sudani")); + scripts.add(new SelectItem("Ta'liq")); + scripts.add(new SelectItem("Tawqi'")); + scripts.add(new SelectItem("Other-see Notes")); + + + sourcesOfInformation.add(new SelectItem("", "-- choose --")); + sourcesOfInformation.add(new SelectItem("Actual Witness")); + sourcesOfInformation.add(new SelectItem("Microfilm")); + sourcesOfInformation.add(new SelectItem("Digital Form (DVD/CD)")); + sourcesOfInformation.add(new SelectItem("Catalogue (Give Full Citation In Notes)")); + } + + public SearchService getSS() { + return serviceRegistry.getSearchService(); + } + + public WrapperService getWrapper() { + return serviceRegistry.getWrapper(); + } + + public SecurityService getSecurityService() { + return serviceRegistry.getSecurityService(); + } + + public ConfigurationService getConfService(){ + return serviceRegistry.getConfigurationService(); + } + + /** + * <p> + * Construct a new application data bean instance. + * </p> + */ + public ApplicationBean() { + logger.info("Initialize ApplicationBean1"); + this.serviceRegistry = new ServiceRegistry(); + this.simpleSearchCache = new SimpleSearchCache(serviceRegistry); + } + + public List<SelectItem> getYes_no() { + return yes_no; + } + + public List<SelectItem> getRoles() { + return roles; + } + + public List<SelectItem> getWritingSurfaces(){ + return writingSurfaces; + } + + public List<SelectItem> getPageLayout(){ + return pageLayout; + } + + public List<SelectItem> getScripts(){ + return scripts; + } + + public List<SelectItem> getSuggestedStatus(){ + return suggestedStatus; + } + + public List<SelectItem> getSuggestedBindings(){ + return suggestedBindings; + } + + public List<SelectItem> getSourcesOfInformation(){ + return sourcesOfInformation; + } + + public List<SelectItem> getSuggestedLanguages(){ + return suggestedLanguages; + } + + public List<SelectItem> getSuggestedTextTypes(){ + return suggestedTextTypes; + } + + public List<SelectItem> getSuggestedBoolean(){ + return suggestedBoolean; + } + + public List<SelectItem> getDateTypes(){ + return dateTypes; + } + + public SimpleSearchCache getSimpleSearchCache() { + return simpleSearchCache; + } + + public void setSimpleSearchCache(SimpleSearchCache simpleSearchCache) { + this.simpleSearchCache = simpleSearchCache; + } + + public void setRoleListAsDirty(){ + this.roleListDirty = true; + } + + public String getRoot(){ + return FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath(); + } + + public List<SelectItem> getRoleList(){ + if(roleListDirty){ + this.roleList = new ArrayList<SelectItem>(); + this.entityRoleList = getWrapper().getEntitiesByDef("ROLE"); + for(Entity e : this.entityRoleList){ + this.roleList.add(new SelectItem(e.getId(), e.getOwnValue())); + } + this.roleListDirty = false; + } + + return this.roleList; + } + + public String getEditImage(){ + return "/resources/images/system/edit_20.png"; + } + + public String getImgEdit16(){ + return "/resources/images/system/edit_16.png"; + } + + public String getImgEdit32(){ + return "/resources/images/system/edit_32.png"; + } + + public String getImgRemove16(){ + return "/resources/images/system/remove_16.png"; + } + + public String getImgRemove32(){ + return "/resources/images/system/remove_32.png"; + } + + public String getImgVersions16(){ + return "/resources/images/system/versions_16.png"; + } + + public String getImgVersions32(){ + return "/resources/images/system/versions_32.png"; + } + + public String getImgSave16(){ + return "/resources/images/system/save_16.png"; + } + + public String getImgSave32(){ + return "/resources/images/system/save_32.png"; + } + + public String getImgClean16(){ + return "/resources/images/system/clean_16.png"; + } + + public String getImgClean32(){ + return "/resources/images/system/clean_32.png"; + } + + public String getImgNew16(){ + return "/resources/images/system/new_16.png"; + } + + public String getImgNew32(){ + return "/resources/images/system/new_32.png"; + } + + public String getImgSeach16(){ + return "/resources/images/system/search_16.png"; + } + + public String getImgSearch32(){ + return "/resources/images/system/search_32.png"; + } + + public String getDisplayImage(){ + return "/resources/images/display_32.png"; + } + + public String getWorldImage(){ + return "/resources/images/icy_earth_32.png"; + } + + public String getBookImage(){ + return "/resources/images/book_32.png"; + } + + public String getSearchImage(){ + return "/resources/images/search_32.png"; + } + + public String getImgNetwork32(){ + return "/resources/images/network_32.png"; + } + + public String getImgPerson32(){ + return "/resources/images/person_32.png"; + } + + + public String getImgDown32(){ + return "/resources/images/down_32.png"; + } + + public String getImgUp32(){ + return "/resources/images/up_32.png"; + } + + ///**** + //private List<Entity> texts; + private List<SelectItem> textsSelectItems; + private boolean dirty = false; + + private void updateListAllTexts(){ + textsSelectItems = new ArrayList<SelectItem>(); + for (Entity text : getWrapper().getEntitiesByDef("TEXT")){ + textsSelectItems.add(new SelectItem(text.getId(), text.getOwnValue() + " [" +text.getId()+ "]")); + } + } + + public List<SelectItem> getAllTexts() { + if(this.dirty || textsSelectItems == null){ + this.updateListAllTexts(); + this.dirty = false; + } + return textsSelectItems; + } + + public void setAllTextsAsDirty(){ + this.dirty = true; + } + + public ESciDocCache getRefCache() { + return refCache; + } + + public String getJSConfirmationSave(){ + return "if(!confirm('Do you really want to save the changes?')){ return false; };"; + } + + public String getJSConfirmationLogout(){ + return "if(!confirm('Do you really want to end your session?')){ return false; };"; + } + + public String getJSConfirmationDelete(){ + return "if(!confirm('Do you really want to delete this?')){ return false; };"; + } + + public String getJSConfirmationSaveAsNew(){ + return "if(!confirm('Do you really want to save the entity as new?')){ return false;};"; + } + + public String getJSConfirmationMerge(){ + return "if(!confirm('Do you really want to merge these entities?')){ return false;};"; + } + + public String getJSConfirmationCleanForm(){ + return "if(!confirm('Do you really want to clear the form?')){ return false;};"; + } + + public String getContextRoot(){ + + HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); + + + + String port = (StringUtils.equals(request.getLocalPort() + "", "80")) ? "" : (":" + request.getLocalPort()); + String path = request.getScheme() + "://" + request.getLocalName() + port + request.getContextPath(); + + return path; + } + + public BiographyBean getBiographyBean(){ + if(biographyBean == null) + this.biographyBean = new BiographyBean(); + return this.biographyBean; + } + + public PublicCodexList getPublicCodexList(){ + if(publicCodexList == null){ + publicCodexList = new PublicCodexList(); + } + return publicCodexList; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/BiographyBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,104 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.utils.EntitySortByNormalizedOwnValue; + +public class BiographyBean extends AbstractBean{ + + private boolean dirty = true; + + private Map<String, List<Biography>> biographyMap; + private List<String> indexList = null; + + public BiographyBean(){ + } + + private void load(){ + this.dirty = false; + this.biographyMap = new HashMap<String, List<Biography>>(); + + + + List<Entity> rs = getAppBean().getWrapper().getEntitiesByAtt("PERSON", "url", "http://islamsci.mcgill.ca/RASI/BEA", -1, true); + + for(Entity ent : rs){ + String normalizedOv = ent.getNormalizedOwnValue(); + String index = new String(normalizedOv.charAt(0) + ""); + index = index.toUpperCase(); + + if(!this.biographyMap.containsKey(index)){ + this.biographyMap.put(index, new ArrayList<BiographyBean.Biography>()); + } + this.biographyMap.get(index).add(new Biography(ent, getAppBean().getWrapper())); + } + + for(String index : this.biographyMap.keySet()){ + Collections.sort(this.biographyMap.get(index)); + } + + this.indexList = new ArrayList<String>(this.biographyMap.keySet()); + Collections.sort(indexList); + } + + public List<String> getIndexList(){ + if(dirty) + this.load(); + return this.indexList; + } + + public Map<String, List<Biography>> getBiographyMap(){ + if(dirty) + this.load(); + return this.biographyMap; + } + + public void makeDirty(){ + this.dirty = true; + } + + public class Biography implements Comparable<Biography>{ + private Long personId; + private String biographyUrl; + private String label; + private String normalizedLabel; + + public Biography(Entity person, WrapperService wrapper){ + Attribute att = wrapper.getAttributeByName(person.getId(), "url"); + + this.label = person.getOwnValue(); + this.personId = person.getId(); + this.biographyUrl = att.getOwnValue(); + this.normalizedLabel = person.getNormalizedOwnValue(); + } + + public Long getPersonId() { + return personId; + } + public String getBiographyUrl() { + return biographyUrl; + } + public String getLabel() { + return label; + } + + public int compareTo(Biography o) { + return this.normalizedLabel.compareTo(o.normalizedLabel); + + } + + @Override + public String toString(){ + return "[" + this.personId + "] " + this.label + " - " + this.biographyUrl; + } + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/CodexEditorTemplate.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,866 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +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 de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.auxObjects.lo.WitnessCityLO; +import de.mpiwg.itgroup.ismi.auxObjects.lo.WitnessCollectionLO; +import de.mpiwg.itgroup.ismi.auxObjects.lo.WitnessCountryLO; +import de.mpiwg.itgroup.ismi.auxObjects.lo.WitnessRepositoryLO; +import de.mpiwg.itgroup.ismi.util.guiComponents.StatusImage; +import de.mpiwg.itgroup.ismi.utils.SelectItemSort; + + +/** + * CODEX -> is_part_of -> COLLECTION + * COLLECTION -> is_part_of -> REPOSITORY + * REPOSITORY -> is_in -> PLACE[city] + * PLACE[city] -> is_part_of -> PLACE[country] + * @author jurzua + * + */ +public class CodexEditorTemplate extends UnityChecker { + + /** + * + */ + private static final long serialVersionUID = 7580021280544772497L; + private static Logger logger = Logger.getLogger(CodexEditorTemplate.class); + public static int MAX_CODICES = 1000; + public static int MAX_REPOSITORIES = 100; + public static int MAX_COLLECTIONS = 100; + public static int MAX_PLACES = 100; + + private ListenerObject countryLo; + private ListenerObject cityLo; + private ListenerObject repositoryLo; + private ListenerObject collectionLo; + private ListenerObject codexLo; + + private List<SelectItem> citiesInCurrentCountry; + private List<SelectItem> repositoriesInCurrentCity; + private List<SelectItem> collectionsInCurrentRepository; + private List<SelectItem> shelfMarksInCurrentCollection; + + private boolean thereExistMoreCodices = false; + + public CodexEditorTemplate(){ + logger.debug("Init: " + this.getClass().getName()); + this.reset(); + } + + @Override + public void reset(){ + super.reset(); + this.countryLo = new WitnessCountryLO(PLACE, "name", this); + this.cityLo = new WitnessCityLO(PLACE, "name", this); + this.repositoryLo = new WitnessRepositoryLO(REPOSITORY, "name", this); + this.collectionLo = new WitnessCollectionLO(COLLECTION, "name", this); + this.codexLo = new ListenerObject(CODEX, "identifier"); + + this.citiesInCurrentCountry = new ArrayList<SelectItem>(); + this.repositoriesInCurrentCity = new ArrayList<SelectItem>(); + this.collectionsInCurrentRepository = new ArrayList<SelectItem>(); + this.shelfMarksInCurrentCollection = new ArrayList<SelectItem>(); + + this.thereExistMoreCodices = false; + } + + public void setCountry(Entity country){ + this.getCountryLo().setEntityAndAttribute0(country); + this.restrictByCountry(country); + } + + public void setCity(Entity city) { + this.getCityLo().setEntityAndAttribute0(city); + this.restrictByCity(city); + + List<Entity> list = getWrapper().getTargetsForSourceRelation(city, is_part_of, PLACE, 1); + + if(list.size() > 0){ + this.setCountry(list.get(0)); + } + } + + public void setRepository(Entity repository) { + this.getRepositoryLo().setEntityAndAttribute0(repository); + this.restrictByRepository(repository); + + List<Entity> list = getWrapper().getTargetsForSourceRelation(repository, is_in, PLACE, 5); + + if(list.size() > 0){ + this.setCity(list.get(0)); + } + } + + public void setCollection(Entity collection) { + this.getCollectionLo().setEntityAndAttribute0(collection); + this.restrictByCollection(collection); + + List<Entity> repoList = getWrapper().getTargetsForSourceRelation(collection, is_part_of, REPOSITORY, 1); + + if(repoList.size() > 0){ + this.setRepository(repoList.get(0)); + } + } + + /** + * Listen to a change of the country where the codex is located. Restrict + * possible collections/repositories/codices to object in this city. + * + * @param event + */ + /* rich + public void countryChangeListener(ValueChangeEvent event) { + + this.setCitiesInCurrentCountry(new ArrayList<SelectItem>()); + + this.setCountryLo(changeListener(event, getCountryLo(), PLACE, "name","type","region")); + if (getCountryLo().entity!=null && getCountryLo().entity.isPersistent()){ + this.setCountry(getCountryLo().entity); + } + this.checkConsistencyFromCountryToCodex(); + }*/ + + /** + * Listen to a change of the city where the codex is located. Restrict + * possible collections/repositories/codices to object in this city. + * + * @param event + */ + /* rich + public void cityChangeListener(ValueChangeEvent event) { + + this.setRepositoriesInCurrentCity(new ArrayList<SelectItem>()); + + this.setCityLo(changeListener(event, getCityLo(), PLACE, "name", "type", "city")); + + if (this.getCityLo().entity!=null && this.getCityLo().entity.isPersistent()){ + this.setCity(this.getCityLo().entity); + } + this.checkConsistencyFromCountryToCodex(); + + } + */ + /* + public void repositoryChangeListener(ValueChangeEvent event) { + + this.setCollectionsInCurrentRepository(new ArrayList<SelectItem>()); + this.setShelfMarksInCurrentCollection(new ArrayList<SelectItem>()); + + this.setRepositoryLo(changeListener(event, this.getRepositoryLo(), REPOSITORY, "name")); + + if (this.getRepositoryLo().entity!= null && this.getRepositoryLo().entity.isPersistent()){ + this.setRepository(this.getRepositoryLo().entity); + } + this.checkConsistencyFromCountryToCodex(); + + }*/ + + + /** + * <p>When the collection is changed by the user this method will be called.</p> + * <p>This modification means that the COLLECTION of the relation CODEX-> + * is_part_of-> COLLECTION is replaced.</p> + * @param newEvent + */ + /* rich + public void collectionChangeListener(ValueChangeEvent event) { + + this.setShelfMarksInCurrentCollection(new ArrayList<SelectItem>()); + + this.setCollectionLo(this.changeListener(event, this.getCollectionLo(), COLLECTION, "name")); + + Entity currentCollection = this.getCollectionLo().entity; + if(currentCollection != null && currentCollection.isPersistent()){ + this.setCollection(currentCollection); + } + + this.checkConsistencyFromCountryToCodex(); + + }*/ + + public void inCurrentCountryListener(ValueChangeEvent event) { + inCurrentListener(getCitiesInCurrentCountry(), event); + } + + public void inCurrentCityListener(ValueChangeEvent event) { + inCurrentListener(getRepositoriesInCurrentCity(), event); + } + + public void inCurrentRepositoryListener(ValueChangeEvent event) { + inCurrentListener(getCollectionsInCurrentRepository(), event); + } + + public void inCurrentListener(List<SelectItem> items, ValueChangeEvent event) { + if (event.getNewValue() == null) { + return; + } + if (event.getNewValue().equals(event.getOldValue())) { + return; + } + String newValue = (String) event.getNewValue(); + for (SelectItem item : items) { + if (item.getValue().equals(newValue)) { + //System.out.println(item.getValue()); + Entity ent = + getWrapper().getEntityById(Long.valueOf((String) item.getValue())); + + if(ent != null){ + String ct = ent.getObjectClass(); + if (ct.equals(CODEX)) { + this.getCodexLo().setEntityAndAttribute0(ent); + Attribute identifier = getWrapper().getAttributeByName(ent.getId(), "identifier"); + + if(identifier != null){ + this.getCodexLo().statusImage.setStatus(StatusImage.STATUS_OK); + } + //changeValueAttCodex(this.getCodexLo().getAttribute().getOwnValue()); + break; + + } else if (ct.equals(REPOSITORY)) { + this.setRepository(ent); + break; + } else if (ct.equals(PLACE)) { + this.setCity(ent); + break; + + } else if (ct.equals(COLLECTION)) { + setCollection(ent); + break; + } else { + break; + } + } + }else{ + logger.error("Entity no found " + item.getValue() + ", however it should exist."); + } + } + this.checkConsistencyFromCountryToCodex(); + } + + public void checkConsistencyFromCountryToCodex(ActionEvent event){ + this.checkConsistencyFromCountryToCodex(); + } + + public CodexForList getCodexData(Entity entity) { + Entity currentRepository = null; + + CodexForList entForList = new CodexForList(); + entForList.id = entity.getId(); + if (entity.isLightweight()){ + entity = getWrapper().getEntityContent(entity); + } + Attribute identAttr = entity.getAttributeByName("identifier"); + if (identAttr != null) + entForList.ident = identAttr.getValue(); + List<Relation> rels = null; + try { + if (entity.isLightweight()){ + entity = getWrapper().getEntityContent(entity); + } + + rels = entity.getSourceRelations(); + } catch (Exception e) { + e.printStackTrace(); + rels = null; + } + if (rels != null) { + for (Relation rel : rels) { + + Entity coll = getWrapper().getEntityById(rel.getTargetId()); + coll = getWrapper().getEntityContent(coll); + + if (rel.getOwnValue().equals(is_part_of) + && coll.getObjectClass().equals(COLLECTION)) { + Attribute name = coll.getAttributeByName("name"); + if (name != null) + entForList.collection = name.getValue(); + try { + Relation rel2 = coll + .getSourceRelationByOwnValue(is_part_of); + if (rel2 != null) { + currentRepository = getWrapper().getEntityById(rel2.getTargetId()); + Attribute nameRep = currentRepository + .getAttributeByName("name"); + if (nameRep != null) + entForList.repository = nameRep.getValue(); + + } + } catch (Exception e) { + e.printStackTrace(); + } + + } else if (rel.getOwnValue().equals(is_part_of) + && coll.getObjectClass().equals(REPOSITORY)) { + Attribute name = coll.getAttributeByName("name"); + if (name != null) + entForList.repository = name.getValue(); + currentRepository = coll; + } else if (rel.getOwnValue().equals(is_in) + && coll.getObjectClass().equals(PLACE)) { + Attribute name = coll.getAttributeByName("name"); + // TODO: ersetze �ber all den String f�r das Attribute + // zur + // Anzeige durch eine Konstante bzw. durch + // getAttRepository.getName, dann kann es leichter + // geaendert + // werden, bzw. ducrch eine dynamischen getOwnValue. + if (name != null) + entForList.place = name.getValue(); + } + + } + } + + if (currentRepository != null) { + Relation rel = null; + try { + if (currentRepository.isLightweight()) + entity = getWrapper().getEntityContent(currentRepository); + + rel = currentRepository.getSourceRelationByOwnValue(is_in); + } catch (Exception e) { + e.printStackTrace(); + rel = null; + } + if (rel != null) { + Entity coll = getWrapper().getEntityById(rel.getSourceId()); + if (coll.getObjectClass().equals(PLACE)) { + Attribute name = coll.getAttributeByName("name"); + // TODO: ersetze ueber all den String fuer das Attribute + // zur + // Anzeige durch eine Konstante bzw. durch + // getAttRepository.getName, dann kann es leichter + // geaendert + // werden, bzw. ducrch eine dynamischen getOwnValue. + if (name != null) + entForList.place = name.getValue(); + } + + } + } + return entForList; + } + + /** + * Restrict all list for the select menu, to the place selected + * TODO @Dirk this method seeks relations, which does not exist more, it implicates a bad performance. + * @param country + */ + protected void restrictByCountry(Entity country) { + + this.setCitiesInCurrentCountry(new ArrayList<SelectItem>()); + + for (Entity src : getWrapper().getSourcesForTargetRelation(country, is_part_of, PLACE, MAX_PLACES)) { + getCitiesInCurrentCountry().add(new SelectItem(String.valueOf(src + .getId()), src.getOwnValue())); + } + } + + /** + * Restrict all list for the select menu, to the place selected + * + * @param place + */ + protected void restrictByCity(Entity place) { + + this.setRepositoriesInCurrentCity(new ArrayList<SelectItem>()); + + for (Entity src : getWrapper().getSourcesForTargetRelation(place, is_in, "REPOSITORY",MAX_REPOSITORIES)) { + this.getRepositoriesInCurrentCity().add(new SelectItem(String.valueOf(src + .getId()), src.getOwnValue())); + } + } + + /** + * Restrict all list for the select menu, to the place selected + * + * @param repository + */ + public void restrictByRepository(Entity repository) { + + this.setCollectionsInCurrentRepository(new ArrayList<SelectItem>()); + for (Entity src : getWrapper().getSourcesForTargetRelation(repository, is_part_of, COLLECTION, MAX_COLLECTIONS)) { + this.getCollectionsInCurrentRepository().add(new SelectItem(String + .valueOf(src.getId()), src.getOwnValue())); + } + } + + protected void restrictByCollection(Entity collection) { + this.setShelfMarksInCurrentCollection(restrictShelfMarks(collection)); + } + + protected List<SelectItem> restrictShelfMarks(Entity collection) { + List<SelectItem> items = new ArrayList<SelectItem>(); + int countCodex = 0; + for (Entity src : getWrapper().getSourcesForTargetRelation(collection, is_part_of, CODEX, MAX_CODICES)) { + countCodex++; + items.add(new SelectItem(String.valueOf(src.getId()), src + .getOwnValue() + + "(" + src.getObjectClass() + ")")); + } + Collections.sort(items, new SelectItemSort()); + this.thereExistMoreCodices = (countCodex == MAX_CODICES) ? true : false; + return items; + } + + /* + * ######################## + * Country -> Codex + * ######################## + */ + + public void checkConsistencyFromCountryToCodex(){ + boolean consistent = false; + + Entity country = this.getCountryLo().entity; + if(country != null && country.isPersistent() && StringUtils.isNotEmpty(getCountryLo().getAttribute().getValue())){ + + Attribute att = getWrapper().getAttributeByName(country.getId(), "name"); + + if(att != null && getCountryLo().getAttribute().getValue().equals(att.getValue())){ + this.getCountryLo().statusImage.setStatus(StatusImage.STATUS_OK); + consistent = true; + }else{ + this.getCountryLo().statusImage.setStatus(StatusImage.STATUS_FALSE); + } + }else{ + this.getCountryLo().statusImage.setStatus(StatusImage.STATUS_UNSET); + } + + if(consistent){ + this.checkConsistencyFromCityToCodex(country); + }else{ + this.labelStatesAsFalseOrUnset(true, true, true, true, false); + } + } + + private void checkConsistencyFromCityToCodex(Entity country){ + boolean consistent = false; + + Entity city = this.getCityLo().entity; + if(city != null && city.isPersistent() && StringUtils.isNotEmpty(getCityLo().getAttribute().getValue())){ + + List<Entity> list = getWrapper().getTargetsForSourceRelation(city, is_part_of, PLACE, 1); + + if(list.size() > 0 && list.get(0).getId().longValue() == country.getId().longValue()){ + this.getCityLo().statusImage.setStatus(StatusImage.STATUS_OK); + consistent = true; + }else{ + this.getCityLo().statusImage.setStatus(StatusImage.STATUS_FALSE); + } + }else{ + this.getCityLo().statusImage.setStatus(StatusImage.STATUS_UNSET); + } + + if(consistent){ + this.checkConsistencyFromRepositoryToCodex(city); + }else{ + this.labelStatesAsFalseOrUnset(true, true, true, false, false); + } + } + + private void checkConsistencyFromRepositoryToCodex(Entity city){ + boolean consistent = false; + + Entity repository = this.getRepositoryLo().entity; + if(repository != null && repository.isPersistent() && StringUtils.isNotEmpty(getRepositoryLo().getAttribute().getValue())){ + //juc List<Entity> list = getSearchServ().getTargetsForSourceRelation(repository, is_in, PLACE, 1); + List<Entity> list = getWrapper().getTargetsForSourceRelation(repository, is_in, PLACE, 1); + + if(list.size() > 0 && list.get(0).getId().longValue() == city.getId().longValue()){ + this.getRepositoryLo().statusImage.setStatus(StatusImage.STATUS_OK); + consistent = true; + }else{ + this.getRepositoryLo().statusImage.setStatus(StatusImage.STATUS_FALSE); + } + }else{ + this.getRepositoryLo().statusImage.setStatus(StatusImage.STATUS_UNSET); + } + + if(consistent){ + this.checkConsistencyFromCollectionToCodex(repository); + }else{ + this.labelStatesAsFalseOrUnset(true, true, false, false, false); + } + } + + private void checkConsistencyFromCollectionToCodex(Entity repository){ + boolean consistent = false; + + Entity collection = this.getCollectionLo().entity; + if(collection != null && collection.isPersistent() && StringUtils.isNotEmpty(getCollectionLo().getAttribute().getValue())){ + + List<Entity> list = getWrapper().getTargetsForSourceRelation(collection, is_part_of, REPOSITORY, 1); + + if(list.size() > 0 && list.get(0).getId().longValue() == repository.getId().longValue()){ + this.getCollectionLo().statusImage.setStatus(StatusImage.STATUS_OK); + consistent = true; + }else{ + this.getCollectionLo().statusImage.setStatus(StatusImage.STATUS_FALSE); + } + }else{ + this.getCollectionLo().statusImage.setStatus(StatusImage.STATUS_UNSET); + } + + if(consistent){ + this.checkConsistencyOfCodex(collection); + }else{ + this.labelStatesAsFalseOrUnset(true, false, false, false, false); + } + } + + private void checkConsistencyOfCodex(Entity collection){ + + Entity codex = this.getCodexLo().entity; + if(codex != null && codex.isPersistent() && StringUtils.isNotEmpty(getCodexLo().getAttribute().getValue())){ + + Attribute identifier = getWrapper().getAttributeByName(codex.getId(), "identifier"); + + List<Entity> list = getWrapper().getTargetsForSourceRelation(codex, is_part_of, COLLECTION, 1); + + if(list.size() > 0 && list.get(0).getId().longValue() == collection.getId().longValue() && + identifier != null && this.getCodexLo().getAttribute().getValue().equals(identifier.getValue())){ + this.getCodexLo().setStatus(StatusImage.STATUS_OK); + }else{ + this.getCodexLo().setStatus(StatusImage.STATUS_FALSE); + } + }else{ + this.getCodexLo().setStatus(StatusImage.STATUS_UNSET); + } + } + + /** + * If a previous method detects that some elements (a subset of {CODEX,...,COUNTRY}) + * of the cycle can not be 'OK' (see: StatusImage states), + * this method will label the mentioned elements as either 'FALSE' or 'UNSET' + * + * @param bCodex true if you are sure that it can not be 'ok'. + * @param bCollection true if you are sure that it can not be 'ok'. + * @param bRepository true if you are sure that it can not be 'ok'. + * @param bCity true if you are sure that it can not be 'ok'. + * @param bCountry true if you are sure that it can not be 'ok'. + */ + public void labelStatesAsFalseOrUnset(boolean bCodex, boolean bCollection, boolean bRepository, boolean bCity, boolean bCountry){ + + if(bCodex){ + Entity codex = this.getCodexLo().entity; + if(codex != null && codex.isPersistent() && StringUtils.isNotEmpty(getCodexLo().getAttribute().getValue())) + this.getCodexLo().statusImage.setStatus(StatusImage.STATUS_FALSE); + else + this.getCodexLo().statusImage.setStatus(StatusImage.STATUS_UNSET); + } + + if(bCollection){ + Entity collection = this.getCollectionLo().entity; + if(collection != null && collection.isPersistent() && StringUtils.isNotEmpty(this.getCollectionLo().getAttribute().getValue())) + this.getCollectionLo().statusImage.setStatus(StatusImage.STATUS_FALSE); + else + this.getCollectionLo().statusImage.setStatus(StatusImage.STATUS_UNSET); + } + + if(bRepository){ + Entity repository = this.getRepositoryLo().entity; + if(repository != null && repository.isPersistent() && StringUtils.isNotEmpty(this.getRepositoryLo().getAttribute().getValue())) + this.getRepositoryLo().statusImage.setStatus(StatusImage.STATUS_FALSE); + else + this.getRepositoryLo().statusImage.setStatus(StatusImage.STATUS_UNSET); + } + + if(bCity){ + Entity city = this.getCityLo().entity; + if(city != null && city.isPersistent() && StringUtils.isNotEmpty(this.getCityLo().getAttribute().getValue())) + this.getCityLo().statusImage.setStatus(StatusImage.STATUS_FALSE); + else + this.getCityLo().statusImage.setStatus(StatusImage.STATUS_UNSET); + } + + if(bCountry){ + Entity country = this.getCountryLo().entity; + if(country != null && country.isPersistent() && StringUtils.isNotEmpty(this.getCountryLo().getAttribute().getValue())) + this.getCountryLo().statusImage.setStatus(StatusImage.STATUS_FALSE); + else + this.getCountryLo().statusImage.setStatus(StatusImage.STATUS_UNSET); + } + + } + + public ListenerObject getCountryLo() { + return countryLo; + } + public void setCountryLo(ListenerObject countryLo) { + this.countryLo = countryLo; + } + public ListenerObject getCityLo() { + return cityLo; + } + public void setCityLo(ListenerObject cityLo) { + this.cityLo = cityLo; + } + public ListenerObject getRepositoryLo() { + return repositoryLo; + } + public void setRepositoryLo(ListenerObject repositoryLo) { + this.repositoryLo = repositoryLo; + } + public ListenerObject getCollectionLo() { + return collectionLo; + } + public void setCollectionLo(ListenerObject collectionLo) { + this.collectionLo = collectionLo; + } + public ListenerObject getCodexLo() { + return codexLo; + } + public void setCodexLo(ListenerObject codexLo) { + this.codexLo = codexLo; + } + + public void setCitiesInCurrentCountry(List<SelectItem> citiesInCurrentCountry) { + this.citiesInCurrentCountry = citiesInCurrentCountry; + } + + public void setRepositoriesInCurrentCity( + List<SelectItem> repositoriesInCurrentCity) { + this.repositoriesInCurrentCity = repositoriesInCurrentCity; + } + + public void setCollectionsInCurrentRepository( + List<SelectItem> collectionsInCurrentRepository) { + this.collectionsInCurrentRepository = collectionsInCurrentRepository; + } + + public void setShelfMarksInCurrentCollection( + List<SelectItem> shelfMarksInCurrentCollection) { + this.shelfMarksInCurrentCollection = shelfMarksInCurrentCollection; + } + + public boolean isThereExistMoreCodices() { + return thereExistMoreCodices; + } + + public void setThereExistMoreCodices(boolean thereExistMoreCodices) { + this.thereExistMoreCodices = thereExistMoreCodices; + } + + public List<SelectItem> getCitiesInCurrentCountry() { + if(this.citiesInCurrentCountry != null && + this.citiesInCurrentCountry.size() > 0 && + (this.citiesInCurrentCountry.get(0).getLabel() == null || + !this.citiesInCurrentCountry.get(0).getLabel().equals("-- choose --"))){ + SelectItem chooser = new SelectItem("", "-- choose --"); + this.citiesInCurrentCountry.add(0, chooser); + } + return citiesInCurrentCountry; + } + + public List<SelectItem> getRepositoriesInCurrentCity() { + if(this.repositoriesInCurrentCity != null && + this.repositoriesInCurrentCity.size() > 0 && + (this.repositoriesInCurrentCity.get(0).getLabel() == null || + !this.repositoriesInCurrentCity.get(0).getLabel().equals("-- choose --"))){ + SelectItem chooser = new SelectItem("", "-- choose --"); + this.repositoriesInCurrentCity.add(0, chooser); + } + return repositoriesInCurrentCity; + } + + public List<SelectItem> getCollectionsInCurrentRepository() { + if(this.collectionsInCurrentRepository != null && + this.collectionsInCurrentRepository.size() > 0 && + (this.collectionsInCurrentRepository.get(0).getLabel() == null || + !this.collectionsInCurrentRepository.get(0).getLabel().equals("-- choose --"))){ + SelectItem chooser = new SelectItem("", "-- choose --"); + this.collectionsInCurrentRepository.add(0, chooser); + } + return collectionsInCurrentRepository; + } + + public List<SelectItem> getShelfMarksInCurrentCollection() { + if(shelfMarksInCurrentCollection != null && + this.shelfMarksInCurrentCollection.size() > 0 && + (this.shelfMarksInCurrentCollection.get(0).getLabel() == null || + !this.shelfMarksInCurrentCollection.get(0).getLabel().equals("-- choose --"))){ + SelectItem chooser = new SelectItem("", "-- choose --"); + this.shelfMarksInCurrentCollection.add(0, chooser); + } + return shelfMarksInCurrentCollection; + } + public class CodexForList { + + public String ident; + public String repository; + public String collection; + public String place; + public String city; + public Long id; + + public String getIdent() { + return ident; + } + + public void setIdent(String ident) { + this.ident = ident; + } + + public String getRepository() { + return repository; + } + + public void setRepository(String repository) { + this.repository = repository; + } + + public String getCollection() { + return collection; + } + + public void setCollection(String collection) { + this.collection = collection; + } + + public String getPlace() { + return place; + } + + public void setPlace(String place) { + this.place = place; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String toString() { + String str = ""; + if (ident != null && !ident.equals("")) + str += ident; + + if (collection != null && !collection.equals("")) + str += "_" + collection; + if (repository != null && !repository.equals("")) + str += "_" + repository; + if (city != null && !city.equals("")) + str += city; + + return str; + + } + } + + + protected boolean isRepositoryConsistentBeforeSave(){ + this.checkConsistencyFromCountryToCodex(); + + if(!getCountryLo().getStatus().equals(StatusImage.STATUS_OK)){ + this.addErrorMsg("The country is marked as: " + getCountryLo().getStatus() + ". The entity could not be saved."); + return false; + } + + if(!getCityLo().getStatus().equals(StatusImage.STATUS_OK)){ + this.addErrorMsg("The city is marked as: " + getCityLo().getStatus() + ". The entity could not be saved."); + return false; + } + + return true; + } + + protected boolean isCollectionConsistentBeforeSave(){ + + if(!isRepositoryConsistentBeforeSave()){ + return false; + } + + if(!getRepositoryLo().getStatus().equals(StatusImage.STATUS_OK)){ + this.addErrorMsg("The repository is marked as: " + getRepositoryLo().getStatus() + ". The entity could not be saved."); + return false; + } + + return true; + } + + protected boolean isCodexConsistentBeforeSave(){ + + if(!isCollectionConsistentBeforeSave()){ + return false; + } + + if(!getCollectionLo().getStatus().equals(StatusImage.STATUS_OK)){ + this.addErrorMsg("The collection is marked as: " + getCollectionLo().getStatus() + ". The entity could not be saved."); + return false; + } + + return true; + } + + protected boolean isWitnessConsistentBeforeSave(){ + + if(!isCodexConsistentBeforeSave()){ + return false; + } + + if(!getCodexLo().getStatus().equals(StatusImage.STATUS_OK)){ + this.addErrorMsg("The codex is marked as: " + getCodexLo().getStatus() + ". The entity could not be saved."); + return false; + } + + return true; + } + + + public void editThisCountryAction(ActionEvent event){ + if(this.getCountryLo().entity != null && this.getCountryLo().entity.isPersistent()){ + getSessionBean().editEntity(this.getCountryLo().entity); + } + } + + public void editThisCityAction(ActionEvent event){ + if(this.getCityLo().entity != null && this.getCityLo().entity.isPersistent()){ + getSessionBean().editEntity(this.getCityLo().entity); + } + } + + public void editThisRepositoryAction(ActionEvent event){ + if(this.getRepositoryLo().entity != null && this.getRepositoryLo().entity.isPersistent()){ + getSessionBean().editEntity(this.getRepositoryLo().entity); + } + } + + public void editThisCollectionAction(ActionEvent event){ + if(this.getCollectionLo().entity != null && this.getCollectionLo().entity.isPersistent()){ + getSessionBean().editEntity(this.getCollectionLo().entity); + } + } + + public void editThisCodexAction(ActionEvent event){ + if(this.getCodexLo().entity != null && this.getCodexLo().entity.isPersistent()){ + getSessionBean().editEntity(this.getCodexLo().entity); + } + } + + public void identifierChangedListener(ValueChangeEvent event) { + if(event.getNewValue() != null){ + inCurrentListener(getShelfMarksInCurrentCollection(), event); + }else{ + getCodexLo().setEntity(null); + getCodexLo().setAttribute(new Attribute("identifier", TEXT, "")); + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/CurrentAliasBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,48 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.io.Serializable; + +import org.apache.log4j.Logger; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Node; + + +public class CurrentAliasBean extends AbstractISMIBean implements Serializable{ + private static final long serialVersionUID = 3420778447263527153L; + + private static Logger logger = Logger.getLogger(CurrentAliasBean.class); + + public CurrentAliasBean(){ + this.entity = new Entity(Node.TYPE_ABOX, ALIAS, false); + setDefObjectClass(ALIAS); + } + + @Override + public void setEntity(Entity alias) { + this.entity = alias; + if(this.entity.isLightweight()){ + this.entity = getWrapper().getEntityContent(this.entity); + } + this.loadAttributes(this.entity); + } + + @Override + public String save(){ + super.save(); + try { + this.entity = updateEntityAttributes(this.entity); + this.entity = getWrapper().saveEntity(this.entity, getSessionUser().getEmail()); + getAppBean().getSimpleSearchCache().setMapDirty(true); + + logger.info("Entity saved - Time = " + (System.currentTimeMillis() - start) + ", " + entity); + this.printSuccessSavingEntity(); + + } catch (Exception e) { + logger.error(e.getMessage(), e); + e.printStackTrace(); + this.printInternalError(e); + } + saveEnd(); + return PAGE_EDITOR; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/CurrentCityBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,211 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Node; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.utils.SelectableObject; + + +public class CurrentCityBean extends CodexEditorTemplate implements Serializable{ + private static final long serialVersionUID = -8609055286714729597L; + + private static Logger logger = Logger.getLogger(CurrentCityBean.class); + + private List<SelectItem> suggestedTypes; + + private List<SelectableObject<Entity>> placesPartOfThis; + private List<SelectableObject<Entity>> peopleLivedIn; + + public CurrentCityBean() { + this.reset(); + + } + + @Override + public void reset(){ + super.reset(); + this.entity = new Entity(Node.TYPE_ABOX, PLACE, false); + this.suggestedTypes = new ArrayList<SelectItem>(); + + this.placesPartOfThis = new ArrayList<SelectableObject<Entity>>(); + this.peopleLivedIn = new ArrayList<SelectableObject<Entity>>(); + + //setDefinition(getDefinition(PLACE)); + setDefObjectClass(PLACE); + String[] types = new String[]{"city","institution", "city_part", "region"}; + fillList(suggestedTypes, types); + + registerChecker(getCountryLo(), "Country not valid!"); + } + + @Override + public void setEntity(Entity city) { + this.reset(); + this.entity = city; + + if(this.entity.isPersistent()){ + if(city.isLightweight()){ + this.entity = getWrapper().getEntityContent(this.entity); + } + + this.loadAttributes(this.entity); + + List<Entity> list = getWrapper().getTargetsForSourceRelation(city, is_part_of, PLACE, -1); + if(list.size() > 0){ + this.setCountry(list.get(0)); + if(list.size() > 1){ + addErrorMsg("Ontological inconsistency. This place 'is part of' " + list.size() + " other places."); + addErrorMsg("List:"); + for(Entity place : list){ + addErrorMsg(place.getOwnValue() + " [" + place.getId() + "]"); + } + } + } + + for(Entity place : getWrapper().getSourcesForTargetRelation(city, is_part_of, PLACE, -1)){ + String label = place.getOwnValue() + " [" + place.getId() + "]"; + this.placesPartOfThis.add(new SelectableObject<Entity>(place, label)); + } + + for(Entity person : getWrapper().getSourcesForTargetRelation(city, lived_in, PERSON, -1)){ + String label = person.getOwnValue() + " [" + person.getId() + "]"; + this.peopleLivedIn.add(new SelectableObject<Entity>(person, label)); + } + + //this.loadReferences(this.entity); + this.loadEndNoteRefs(); + + this.setCurrentId(this.entity.getId().toString()); + this.checkConsistencyFromCountryToCodex(); + } + } + + @Override + public String save(){ + super.save(); + try { + + CheckResults cr = getCheckResults(); + if (cr.hasErrors){ + getSessionBean().setErrorMessages(cr); + getSessionBean().setDisplayError(true); + this.setSelectedSaveAsNew(false); + return "SAVE_ERROR"; + } + + this.entity = this.updateEntityAttributes(this.entity); + + String cityName = (this.entity.getAttributeByName(name) != null) ? this.entity.getAttributeByName(name).getValue() : ""; + if(StringUtils.isNotEmpty(cityName)){ + if(!checkUnityCity(cityName, (isSelectedSaveAsNew()) ? null : this.entity.getId(), this.getCountryLo().entity)){ + this.renderUnityCheckerDialog(); + this.setSelectedSaveAsNew(false); + return "SAVE_ERROR"; + } + }else{ + this.addErrorMsg("Ths entity has not been saved, because its name was empty."); + this.addErrorMsg("You must enter a name."); + return "SAVE_ERROR"; + } + + //this.entity.removeSourceRelation("is_part_of", this.getCountryLo().entity); + //replaceSourceRelation(this.entity, this.getCountryLo().entity, "PLACE", "is_part_of"); + this.entity.replaceSourceRelation(this.getCountryLo().entity, PLACE, is_part_of); + + this.entity.removeAllTargetRelationsByName(is_part_of); + for(SelectableObject<Entity> so : this.placesPartOfThis){ + Entity place = getWrapper().getEntityByIdWithContent(so.getObj().getId()); + Relation isPartOf = new Relation(place, this.entity, is_part_of); + } + + this.entity.removeAllTargetRelationsByName(lived_in); + for(SelectableObject<Entity> so : this.peopleLivedIn){ + Entity person = getWrapper().getEntityByIdWithContent(so.getObj().getId()); + Relation livedIn = new Relation(person, this.entity, lived_in); + } + + //REFERENCE -> is_reference_of -> THIS + //this.entity = this.prepareReferencesToSave(this.entity); + this.prepareEndNoteRefs2Save(); + + //String lastAction = ""; + if(this.isSelectedSaveAsNew()){ + this.entity.removeAllTargetRelations(is_in, REPOSITORY); + this.entity = getWrapper().saveEntityAsNew(this.entity, getSessionUser().getEmail()); + this.setSelectedSaveAsNew(false); + //lastAction = "Save place as new entity"; + }else{ + this.entity = getWrapper().saveEntity(this.entity, getSessionUser().getEmail()); + //lastAction = "Save place"; + } + //setActionInfo(lastAction); + this.generateSecundaryOW(this.entity, getSessionUser().getEmail()); + this.setCurrentId(this.entity.getId().toString()); + + logger.info("Entity saved - Time = " + (System.currentTimeMillis() - start) + ", " + entity); + this.printSuccessSavingEntity(); + + this.setSelectedSaveAsNew(false); + + } catch (Exception e) { + logger.error(e.getMessage(), e); + e.printStackTrace(); + this.printInternalError(e); + } + saveEnd(); + + return PAGE_EDITOR; + } + + public void listenerRemovePlacesPartOfThis(){ + for(SelectableObject<Entity> so : new ArrayList<SelectableObject<Entity>>(this.placesPartOfThis)){ + if(so.isSelected()){ + this.placesPartOfThis.remove(so); + } + } + } + + public void listenerRemovePeopleLivedIn(){ + for(SelectableObject<Entity> so : new ArrayList<SelectableObject<Entity>>(this.peopleLivedIn)){ + if(so.isSelected()){ + this.peopleLivedIn.remove(so); + } + } + } + + public String saveAsNewEntity(){ + this.setSelectedSaveAsNew(true); + return save(); + } + public List<SelectItem> getSuggestedTypes() { + return suggestedTypes; + } + public void setSuggestedTypes(List<SelectItem> suggestedTypes) { + this.suggestedTypes = suggestedTypes; + } + + public List<SelectableObject<Entity>> getPlacesPartOfThis() { + return placesPartOfThis; + } + + public void setPlacesPartOfThis(List<SelectableObject<Entity>> placesPartOfThis) { + this.placesPartOfThis = placesPartOfThis; + } + + public List<SelectableObject<Entity>> getPeopleLivedIn() { + return peopleLivedIn; + } + + public void setPeopleLivedIn(List<SelectableObject<Entity>> peopleLivedIn) { + this.peopleLivedIn = peopleLivedIn; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/CurrentCodexBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,382 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.io.Serializable; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +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.Node; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.util.guiComponents.Calendar; +import de.mpiwg.itgroup.ismi.util.guiComponents.EntityList; + +/** + * @author jurzua + * + */ +public class CurrentCodexBean extends CodexEditorTemplate implements Serializable{ + private static final long serialVersionUID = -4242977362183330958L; + + private static Logger logger = Logger.getLogger(CurrentCodexBean.class); + + //private Entity codex; + + private List<Entity> witnessInCurrentCodex; + private boolean showWitnessInCurrentCodex; + + private EntityList ownedByPeople; + private EntityList readByPeople; + + private List<SelectItem> suggestedBindingList = new ArrayList<SelectItem>(); + + private CodexEditorTemplate referencedCodexTemplate; + private Boolean isAlias; + + + public CurrentCodexBean() { + this.entity = new Entity(Node.TYPE_ABOX, CODEX, false); + setDefObjectClass(CODEX); + registerChecker(getCityLo(), "city is not valid"); + registerChecker(getCountryLo(), "country is not valid"); + registerChecker(getRepositoryLo(), "repository is not valid"); + registerChecker(getCollectionLo(), "collection is not valid"); + + this.refreshBindingList(); + } + + @Override + public void reset(){ + super.reset(); + this.entity = new Entity(Node.TYPE_ABOX, CODEX, false); + + this.ownedByPeople = new EntityList(PERSON, "name_translit", true); + this.readByPeople = new EntityList(PERSON, "name_translit", true); + + this.witnessInCurrentCodex = new ArrayList<Entity>(); + this.showWitnessInCurrentCodex = false; + this.isAlias = false; + this.referencedCodexTemplate = new CodexEditorTemplate(); + this.refreshBindingList(); + } + + public void listenerRefreshBindingList(ActionEvent event){ + this.refreshBindingList(); + } + + public void listenerEditCalendarOwnedBy(ActionEvent event){ + Entity entity = (Entity)getRequestBean("item"); + if(entity != null){ + Calendar cal = this.ownedByPeople.getCalendar(entity.getId()); + getSessionBean().editCalendar(cal, ownedByPeople, entity.getId()); + } + } + + public void listenerEditCalendarReadBy(ActionEvent event){ + Entity entity = (Entity)getRequestBean("item"); + if(entity != null){ + Calendar cal = this.readByPeople.getCalendar(entity.getId()); + getSessionBean().editCalendar(cal, readByPeople, entity.getId()); + } + } + + private void refreshBindingList(){ + this.suggestedBindingList = new ArrayList<SelectItem>(); + suggestedBindingList.add(new SelectItem("", "--choose--")); + Attribute binding = getWrapper().getDefAttributeByOwnValue(this.entity.getObjectClass(), "binding"); + if(binding != null){ + for(String s : binding.getPossibleValuesList()){ + this.suggestedBindingList.add(new SelectItem(s)); + } + } + } + + public String createCollectionAction() { + getSessionBean().setSelectedTab(SessionBean.COLLECTION_TAB); + return "edit"; + } + + @Override + public void setEntity(Entity codex) { + this.reset(); + this.entity = codex; + logger.info("Set Codex " + this.entity); + try { + if(this.entity != null && this.entity.isPersistent()){ + if(this.entity.isLightweight()){ + this.entity = getWrapper().getEntityContent(this.entity); + } + + this.loadAttributes(this.entity); + + Attribute isAliasAtt = getWrapper().getAttributeByName(this.entity.getId(), "is_alias"); + if(isAlias != null){ + try{ + this.isAlias = new Boolean(isAliasAtt.getOwnValue()); + }catch(Exception ex){ + this.isAlias = false; + } + }else{ + this.isAlias = false; + } + + for(Relation rel : getWrapper().getSourceRelations(codex, owned_by, PERSON, -1)) { + this.ownedByPeople.add(getWrapper().getEntityById(rel.getTargetId()), rel.getAttributeByName("date")); + } + + for(Relation rel : getWrapper().getSourceRelations(codex, "read_by", PERSON, -1)) { + this.readByPeople.add(getWrapper().getEntityById(rel.getTargetId()), rel.getAttributeByName("date")); + } + + for (Entity target : getWrapper() + .getTargetsForSourceRelation(codex, is_part_of, COLLECTION, 1)) { + String ct = target.getObjectClass(); + + if (ct.equals(COLLECTION)) { + this.setCollection(target); + } + } + + List<Entity> list = getWrapper().getTargetsForSourceRelation(codex, "is_alias_of", CODEX, 1); + if(!list.isEmpty()){ + this.setReferencedCodex(list.get(0)); + //this.referencedCodexTemplate.setCodexLo(codexLo); + //this.referencedCodexLO.setEntityAndAttribute(list.get(0), "identifier"); + } + + + //this.loadReferences(this.entity); + this.loadEndNoteRefs(); + + this.setCurrentId(this.entity.getId().toString()); + this.checkConsistencyFromCountryToCodex(); + } + } catch (Exception e) { + logger.info(e.getMessage(), e); + printInternalError(e); + } + } + + public void setReferencedCodex(Entity codex){ + this.referencedCodexTemplate.getCodexLo().setEntityAndAttribute(codex, "identifier"); + + if(this.referencedCodexTemplate.getCodexLo().entity != null && + this.referencedCodexTemplate.getCodexLo().entity.isPersistent()){ + + List<Entity> list = getWrapper().getTargetsForSourceRelation(codex, is_part_of, COLLECTION, 1); + if(list.size() > 0){ + this.referencedCodexTemplate.setCollection(list.get(0)); + } + } + } + + @Override + public String save() { + super.save(); + try { + CheckResults cr = getCheckResults(); + if (cr.hasErrors) { + getSessionBean().setErrorMessages(cr); + getSessionBean().setDisplayError(true); + this.setSelectedSaveAsNew(false); + return PAGE_EDITOR; + } + + if (this.entity == null) { + this.entity = new Entity(); + this.entity.setObjectClass("CODEX"); + } + + this.entity = this.updateEntityAttributes(this.entity); + + if(this.entity.getAttributeByName("is_alias") != null){ + this.entity.getAttributeByName("is_alias").setOwnValue(this.isAlias.toString()); + }else{ + this.entity.addAttribute(new Attribute("is_alias", "boolean", this.isAlias.toString())); + } + + if(this.isAlias){ + if(referencedCodexTemplate.getCodexLo().entity != null){ + // CODEX -> is_part_of -> CODEX + this.entity.replaceSourceRelation(referencedCodexTemplate.getCodexLo().entity, CODEX, "is_alias_of"); + }else{ + this.entity.removeAllSourceRelations("is_alias_of", CODEX); + } + } + + //checking is the identifier is unique for the selected collecion + String identifier = (this.entity.getAttributeByName("identifier") != null) ? this.entity.getAttributeByName("identifier").getValue() : ""; + if(StringUtils.isNotEmpty(identifier)){ + if(!checkUnityCodex(identifier, (isSelectedSaveAsNew()) ? null : this.entity.getId(), this.getCollectionLo().entity)){ + this.renderUnityCheckerDialog(); + this.setSelectedSaveAsNew(false); + return PAGE_EDITOR; + } + }else{ + this.addErrorMsg("This entity has not been saved, because its identifier was empty."); + this.addErrorMsg("You must enter an identifier."); + return PAGE_EDITOR; + } + + if(!isCodexConsistentBeforeSave()){ + return PAGE_EDITOR; + } + + this.entity.replaceSourceRelation(this.getCollectionLo().entity, COLLECTION, is_part_of); + + // CODEX -> owner_by (manyToMany) -> PERSON + this.entity.removeAllSourceRelationsByName(owned_by); + + // CODEX -> read_by (manyToMany) -> PERSON + this.entity.removeAllSourceRelationsByName("read_by"); + + //REFERENCE -> is_reference_of -> THIS + //this.entity = this.prepareReferencesToSave(this.entity); + this.prepareEndNoteRefs2Save(); + + if (this.isSelectedSaveAsNew()) { + this.entity = getWrapper().saveEntityAsNew(this.entity,getSessionUser().getEmail()); + this.setSelectedSaveAsNew(false); + } else { + for(Entity owner : this.ownedByPeople.getEntities()){ + if(owner.isLightweight()){ + owner = getWrapper().getEntityByIdWithContent(owner.getId()); + } + Relation ownerBy = new Relation(this.entity, owner, owned_by); + Calendar cal = ownedByPeople.getCalendar(owner.getId()); + if(cal != null){ + ownerBy.addAttribute(new Attribute("date", "date", cal.toJSONString())); + } + } + for(Entity reader : this.readByPeople.getEntities()){ + Relation readBy = new Relation(this.entity, reader, "read_by"); + Calendar cal = readByPeople.getCalendar(reader.getId()); + if(cal != null){ + readBy.addAttribute(new Attribute("date", "date", cal.toJSONString())); + } + } + + this.entity = getWrapper().saveEntity(this.entity, getSessionUser().getEmail()); + } + + this.generateSecundaryOW(this.entity, getSessionUser().getEmail()); + getSessionBean().setEditFormCurrentEntId(this.entity.getId()); + + logger.info("Entity saved - Time = " + (System.currentTimeMillis() - start) + ", " + entity); + this.printSuccessSavingEntity(); + + this.setSelectedSaveAsNew(false); + + } catch (Exception e) { + logger.error(e.getMessage(), e); + e.printStackTrace(); + this.printInternalError(e); + } + + saveEnd(); + return PAGE_EDITOR; + } + + public String saveAsNewEntity() { + this.setSelectedSaveAsNew(true); + return save(); + } + + public void setLWCodex(Entity codex) { + this.entity = codex; + } + + public void actionShowWitnessDialog(ActionEvent event){ + if(this.witnessInCurrentCodex.size() == 0 && this.entity.isPersistent()){ + this.witnessInCurrentCodex = + getWrapper().getSourcesForTargetRelation(this.entity, "is_part_of", "WITNESS", 50); + } + this.setShowWitnessInCurrentCodex(true); + } + + public void actionCloseWitnessDialog(ActionEvent event){ + this.setShowWitnessInCurrentCodex(false); + } + + public void actionEditThisWitness(ActionEvent event){ + this.setShowWitnessInCurrentCodex(false); + Entity currentWitness = (Entity)getRequestBean("witness"); + if(currentWitness != null && currentWitness.isPersistent()){ + getSessionBean().editEntity(currentWitness); + } + } + + public List<Entity> getWitnessInCurrentCodex() { + return witnessInCurrentCodex; + } + + public void setWitnessInCurrentCodex(List<Entity> witnessInCurrentCodex) { + this.witnessInCurrentCodex = witnessInCurrentCodex; + } + + public boolean isShowWitnessInCurrentCodex() { + if(this.entity == null || !this.entity.isPersistent()){ + return false; + } + return showWitnessInCurrentCodex; + } + + public void setShowWitnessInCurrentCodex(boolean showWitnessInCurrentCodex) { + this.showWitnessInCurrentCodex = showWitnessInCurrentCodex; + } + + public void actionEditThisCollection(ActionEvent event){ + if(this.getCollectionLo().entity != null && getCollectionLo().entity.isPersistent()){ + getSessionBean().editEntity(this.getCollectionLo().entity); + } + } + + public EntityList getOwnedByPeople() { + return ownedByPeople; + } + + public void setOwnedByPeople(EntityList ownedByPeople) { + this.ownedByPeople = ownedByPeople; + } + + public List<SelectItem> getSuggestedBindingList() { + return suggestedBindingList; + } + + public void setSuggestedBindingList(List<SelectItem> suggestedBindingList) { + this.suggestedBindingList = suggestedBindingList; + } + + public CodexEditorTemplate getReferencedCodexTemplate() { + return referencedCodexTemplate; + } + + public void setReferencedCodexTemplate( + CodexEditorTemplate referencedCodexTemplate) { + this.referencedCodexTemplate = referencedCodexTemplate; + } + + public Boolean getIsAlias() { + return isAlias; + } + + public void setIsAlias(Boolean isAlias) { + this.isAlias = isAlias; + } + + public EntityList getReadByPeople() { + return readByPeople; + } + + public void setReadByPeople(EntityList readByPeople) { + this.readByPeople = readByPeople; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/CurrentCollectionBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,192 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.io.Serializable; +import java.util.HashMap; + +import javax.faces.event.ActionEvent; + +import org.apache.commons.lang.StringUtils; +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.Node; + +import de.mpiwg.itgroup.ismi.util.guiComponents.StatusImage; + +public class CurrentCollectionBean extends CodexEditorTemplate implements + Serializable { + private static final long serialVersionUID = 5723693904746973203L; + + public static int MAX_PLACES = 100; + public static int MAX_REPOSITORIES = 100; + private static Logger logger = Logger + .getLogger(CurrentCollectionBean.class); + + protected Boolean restrictCities = true; + private Boolean restrictRepositories = true; + + // private Entity collection; + + @Override + public void reset() { + super.reset(); + this.entity = new Entity(Node.TYPE_ABOX, COLLECTION, false); + + this.restrictCities = true; + this.restrictRepositories = true; + + this.entity = new Entity(Node.TYPE_ABOX, COLLECTION, false); + } + + public CurrentCollectionBean() { + this.reset(); + // setDefinition(getDefinition("COLLECTION")); + setDefObjectClass(COLLECTION); + registerChecker(getCityLo(), "City is not valid!"); + registerChecker(getCountryLo(), "Country is not valid!"); + registerChecker(getRepositoryLo(), "Repository is not valid!"); + } + + public Boolean getRestrictCities() { + return restrictCities; + } + + public void setRestrictCities(Boolean restrictCities) { + this.restrictCities = restrictCities; + } + + public Boolean getRestrictRepositories() { + return restrictRepositories; + } + + public void setRestrictRepositories(Boolean restrictRepositories) { + this.restrictRepositories = restrictRepositories; + } + + public void setEntity(Entity collection) { + this.reset(); + this.entity = collection; + + if (this.entity != null && this.entity.isPersistent()) { + if (this.entity.isLightweight()) { + this.entity = getWrapper().getEntityContent(this.entity); + } + + this.loadAttributes(this.entity); + + for (Entity target : getWrapper().getTargetsForSourceRelation( + collection, "is_part_of", REPOSITORY, 1)) { + setRepository(target); + } + + // this.loadReferences(this.entity); + this.loadEndNoteRefs(); + + this.setCurrentId(this.entity.getId().toString()); + this.checkConsistencyFromCountryToCodex(); + } + } + + public String saveAsNewEntity() { + this.setSelectedSaveAsNew(true); + return save(); + } + + @Override + public String save() { + super.save(); + try { + + CheckResults cr = getCheckResults(); + if (cr.hasErrors) { + getSessionBean().setErrorMessages(cr); + getSessionBean().setDisplayError(true); + this.setSelectedSaveAsNew(false); + return ""; + } + + this.entity = this.updateEntityAttributes(this.entity); + // checking is the identifier is unique for the selected collecion + Attribute attName = this.entity.getAttributeByName("name"); + String collectionName = (attName == null) ? null : attName + .getValue(); + if (StringUtils.isNotEmpty(collectionName)) { + if (!checkUnityCollection(collectionName, + (isSelectedSaveAsNew()) ? null : this.entity.getId(), + this.getRepositoryLo().entity)) { + this.renderUnityCheckerDialog(); + this.setSelectedSaveAsNew(false); + return ""; + } + } else { + this.addErrorMsg("Ths entity has not been saved, because its name was empty."); + this.addErrorMsg("You must enter a name."); + return ""; + } + + if (!isCollectionConsistentBeforeSave()) { + return ""; + } + + // this.entity.removeSourceRelation(is_part_of + // ,this.getRepositoryLo().entity); + // this.replaceSourceRelation(this.entity, + // this.getRepositoryLo().entity, "REPOSITORY", "is_part_of"); + if (this.getRepositoryLo().entity != null + && this.getRepositoryLo().entity.isLightweight()) { + this.getRepositoryLo().entity = getWrapper() + .getEntityByIdWithContent( + this.getRepositoryLo().entity.getId()); + } + this.entity.replaceSourceRelation(this.getRepositoryLo().entity, + REPOSITORY, is_part_of); + + // REFERENCE -> is_reference_of -> THIS + // this.entity = this.prepareReferencesToSave(this.entity); + this.prepareEndNoteRefs2Save(); + + if (isSelectedSaveAsNew()) { + this.entity.removeAllTargetRelations(is_part_of, CODEX); + this.entity = getWrapper().saveEntityAsNew(this.entity, + getSessionUser().getEmail()); + } else { + this.entity = getWrapper().saveEntity(this.entity, + getSessionUser().getEmail()); + } + + this.generateSecundaryOW(this.entity, getSessionUser().getEmail()); + this.setCurrentId(this.entity.getId().toString()); + + logger.info("Entity saved - Time = " + + (System.currentTimeMillis() - start) + ", " + entity); + this.printSuccessSavingEntity(); + + this.setSelectedSaveAsNew(false); + + } catch (Exception e) { + logger.error(e.getMessage(), e); + e.printStackTrace(); + this.printInternalError(e); + } + saveEnd(); + + return PAGE_EDITOR; + } + + /** + * <p> + * This method saves the collection without the loading of its contain when + * it is not necessary. LW means that the collection keeps light weight or + * without attributes and relation. + * </p> + * <p> + * It is normally used by classes (like: CurrentCodex, CurrentWitness) which + * inherit of this class. + * </p> + * + * @param collection + */ + public void setLWCollection(Entity collection) { + this.entity = collection; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/CurrentDigitalizationBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,91 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.io.Serializable; +import java.util.List; + +import org.apache.log4j.Logger; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Node; +import org.mpi.openmind.security.bo.User; + +public class CurrentDigitalizationBean extends CodexEditorTemplate implements Serializable{ + + private static final long serialVersionUID = 4910425502556948216L; + + private static Logger logger = Logger.getLogger(CurrentDigitalizationBean.class); + + + public CurrentDigitalizationBean(){ + super(); + this.entity = new Entity(Node.TYPE_ABOX, DIGITALIZATION, false); + setDefObjectClass(DIGITALIZATION); + } + + @Override + public void reset(){ + super.reset(); + this.entity = new Entity(Node.TYPE_ABOX, DIGITALIZATION, false); + } + + @Override + public void setEntity(Entity digi){ + this.reset(); + this.entity = digi; + + if(this.entity.isPersistent()){ + if (entity.isLightweight()) { + entity = getWrapper().getEntityContent(digi); + } + } + + this.loadAttributes(this.entity); + + List<Entity> list = getWrapper().getTargetsForSourceRelation(entity, is_digitalization_of, CODEX, -1); + if(list.size() > 0){ + this.setCodex(list.get(0)); + } + } + + + public void setCodex(Entity codex){ + this.getCodexLo().setEntityAndAttribute(codex, "identifier"); + + if(this.getCodexLo().entity != null && this.getCodexLo().entity.isPersistent()){ + + List<Entity> list = getWrapper().getTargetsForSourceRelation(codex, is_part_of, COLLECTION, 1); + if(list.size() > 0){ + this.setCollection(list.get(0)); + } + } + } + + @Override + public String save() { + super.save(); + try { + User user = getSessionUser(); + + this.entity = this.updateEntityAttributes(this.entity); + + // DIGITALIZATION -> is_digitalization_of -> CODEX + this.entity.replaceSourceRelation(getCodexLo().entity, CODEX, is_digitalization_of); + + this.entity = getWrapper().saveEntity(this.entity, user.getEmail()); + + this.setEntity(this.entity); + + logger.info("Entity saved - Time = " + (System.currentTimeMillis() - start) + ", " + entity); + + this.printSuccessSavingEntity(); + + } catch (Exception e) { + logger.error(e.getMessage(), e); + e.printStackTrace(); + this.printInternalError(e); + } + saveEnd(); + return PAGE_EDITOR; + } + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/CurrentPersonBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,454 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.io.Serializable; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import javax.faces.component.UIComponent; +import javax.faces.convert.Converter; +import javax.faces.event.ActionEvent; +import javax.faces.event.AjaxBehaviorEvent; +import javax.faces.event.ValueChangeEvent; + +import org.apache.log4j.Logger; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Node; +import org.mpi.openmind.repository.bo.Relation; +import org.mpi.openmind.repository.utils.RomanizationLoC; +import org.mpi.openmind.repository.utils.TransliterationUtil; + + + +/* rich +import com.icesoft.faces.async.render.SessionRenderer; +import com.icesoft.faces.component.ext.HtmlCommandButton; +import com.icesoft.faces.component.ext.HtmlInputHidden; +*/ +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.util.guiComponents.Calendar; +import de.mpiwg.itgroup.ismi.util.guiComponents.EntityList; + +public class CurrentPersonBean extends AbstractISMIBean implements Serializable{ + private static final long serialVersionUID = -3366510497089165294L; + + private static Logger logger = Logger.getLogger(CurrentPersonBean.class); + + //private Entity person; + private String newAlias; + + private String romanizedNameTranslit; + + public static String birth_date = "birth_date"; + public static String death_date = "death_date"; + + private ListenerObject birthPlaceLo = new ListenerObject(PLACE, name); + private ListenerObject deathPlaceLo = new ListenerObject(PLACE, name); + + private String valueShortName; + private Entity shortNameAlias; // is now an alias of type "prime" + + private transient Calendar calBirthDate; + private transient Calendar calDeathDate; + + private Map<String, Boolean> deletedAliases = new HashMap<String, Boolean>(); + + private EntityList livedInPlaces; + private EntityList aliasList; + private EntityList roleList; + private EntityList studentOfList; + private EntityList floruitList; + + @Override + public void reset(){ + super.reset(); + this.entity = new Entity(Node.TYPE_ABOX, PERSON, false); + + this.newAlias = new String(); + + this.livedInPlaces = new EntityList(PLACE, name, true); + this.aliasList = new EntityList(ALIAS, "alias", getWrapper(), getUserName()); + this.roleList = new EntityList(ROLE, "name", getWrapper(), getUserName()); + this.studentOfList = new EntityList(PERSON, "name_translit", "Student of"); + this.floruitList = new EntityList(FLORUIT_DATE, "date", getWrapper(), getUserName(), true); + + this.valueShortName = ""; + this.shortNameAlias = null; + + this.birthPlaceLo.reset(); + + this.deathPlaceLo.reset(); + + this.deletedAliases = new HashMap<String, Boolean>(); + + this.calBirthDate = new Calendar(); + this.calDeathDate = new Calendar(); + + } + + public EntityList getRoleList() { + return roleList; + } + + public void setRoleList(EntityList roleList) { + this.roleList = roleList; + } + + public EntityList getAliasList() { + return aliasList; + } + + public void setAliasList(EntityList aliasList) { + this.aliasList = aliasList; + } + + public CurrentPersonBean() { + this.reset(); + setDefObjectClass(PERSON); + registerChecker(birthPlaceLo, "Birth place not valid!"); + registerChecker(deathPlaceLo, "Death place not valid!"); + } + + /** + * + * @param event + */ + public void shortNameChangeListener(ValueChangeEvent event) { + try { + if (event.getNewValue() == null) { + return; + } + if (event.getNewValue().equals(event.getOldValue())) { + return; + } + + String newShortName = (String) event.getNewValue(); + + if (shortNameAlias == null) { + shortNameAlias = new Entity(org.mpi.openmind.repository.bo.Node.TYPE_ABOX, ALIAS, false); + + } + + Attribute attr = this.shortNameAlias.getAttributeByName(alias); + if (attr == null) { + this.shortNameAlias.addAttribute(new Attribute(alias, TEXT, + newShortName)); + } else + attr.setValue(newShortName); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + public String translitNameAction() { + String pn = getAttributes().get(name); + + String translit = TransliterationUtil.getTransliteration(pn); + this.getAttributes().put(name_translit, translit); + + return PAGE_EDITOR; + } + + public Calendar getCalBirthDate() { + return calBirthDate; + } + + public void setCalBirthDate(Calendar calBirthDate) { + this.calBirthDate = calBirthDate; + } + + public Calendar getCalDeathDate() { + return calDeathDate; + } + + public void setCalDeathDate(Calendar calDeathDate) { + this.calDeathDate = calDeathDate; + } + + @Override + public void setEntity(Entity person) { + this.reset(); + + this.entity = person; + + if(this.entity != null && this.entity.isPersistent()){ + if (this.entity.isLightweight()) { + this.entity = this.getWrapper().getEntityContent(person); + } + + this.calDeathDate = updateCalendar(this.entity.getAttributeByName(death_date)); + this.calBirthDate = updateCalendar(this.entity.getAttributeByName(birth_date)); + + this.setCurrentId(this.entity.getId().toString()); + this.loadAttributes(this.entity); + + for (Relation rel : this.entity.getSourceRelations()) { + Entity target = getWrapper().getEntityById(rel.getTargetId()); + if (rel.getOwnValue().equals("was_born_in")) { + this.birthPlaceLo.setEntityAndAttribute0(target); + //this.personWasBornInName = (target == null) ? "" : target.getOwnValue(); + } else if (rel.getOwnValue().equals(lived_in)) { + this.livedInPlaces.add(target, rel.getAttributeByName("date")); + } else if (rel.getOwnValue().equals(was_student_of)) { + this.studentOfList.add(target); + } else if (rel.getOwnValue().equals(has_role)) { + this.roleList.add(target); + } else if (rel.getOwnValue().equals("died_in")) { + this.deathPlaceLo.setEntityAndAttribute0(target); + } else if (rel.getOwnValue().equals("has_floruit_date")) { + Attribute calAtt = getWrapper().getAttributeByName(target.getId(), "date"); + this.floruitList.add(target, calAtt); + } + } + + for (Relation rel : this.entity.getTargetRelations()) { + if (rel.getOwnValue().equals("was_created_by") && rel.getSourceObjectClass().equals(TEXT)) { + //Entity title = getWrapper().getEntityById(rel.getSourceId()); + } else if (rel.getOwnValue().equals("is_alias_name_of")) { + Entity alias = getWrapper().getEntityById(rel.getSourceId()); + this.aliasList.add(alias); + } else if (rel.getOwnValue().equals("is_prime_alias_name_of")) { + Entity alias = getWrapper().getEntityByIdWithContent(rel.getSourceId()); + this.shortNameAlias = alias; + this.valueShortName = alias.getAttributeByName("alias").getValue(); + } + } + + //this.loadReferences(this.entity); + this.loadEndNoteRefs(); + this.displayUrl = generateDisplayUrl(person, null, null, getAppBean().getRoot()); + + } + } + + /** + * Saves the current Person. TODO save the target's relations. + * + * @return + */ + @Override + public String save() { + super.save(); + try { + + long start = System.currentTimeMillis(); + + CheckResults cr = getCheckResults(); + if (cr.hasErrors){ + getSessionBean().setErrorMessages(cr); + getSessionBean().setDisplayError(true); + return "SAVE_ERROR"; + } + + getAttributes().put(birth_date, this.calBirthDate.toJSONString()); + getAttributes().put(death_date, this.calDeathDate.toJSONString()); + + + this.entity = updateEntityAttributes(this.entity); + this.entity.replaceSourceRelation(birthPlaceLo.entity, PLACE, "was_born_in"); + + this.entity.replaceSourceRelation(deathPlaceLo.entity, PLACE, "died_in"); + + this.entity.removeAllTargetRelationsByName(is_prime_alias_name_of); + if (shortNameAlias != null) { + shortNameAlias.setObjectClass(ALIAS); + shortNameAlias = getWrapper().saveEntity(shortNameAlias, getSessionUser().getEmail()); + Relation aliasRel = new Relation(shortNameAlias, this.entity, is_alias_name_of); + } + + //ALIAS -> is_alias_name_of -> PERSON + this.entity.removeAllTargetRelationsByName(is_alias_name_of); + for(Entity alias : this.aliasList.getEntities()){ + Entity alias0 = getWrapper().getEntityByIdWithContent(alias.getId()); + Relation aliasRel = new Relation(alias0, this.entity, is_alias_name_of); + } + + // PERSON -> lived_in manyToMany -> PLACE + this.entity.removeAllSourceRelationsByName(lived_in); + for(Entity place : this.livedInPlaces.getEntities()){ + //loadRelation(this.person, place, PLACE, lived_in); + Entity place0 = getWrapper().getEntityByIdWithContent(place.getId()); + Relation livedIn = new Relation(this.entity, place0, lived_in); + Calendar cal = livedInPlaces.getCalendar(place.getId()); + if(cal != null){ + livedIn.addAttribute(new Attribute("date", "date", cal.toJSONString())); + } + } + + // Person -> has_floruit_date -> FLORUIT DATE + this.entity.removeAllSourceRelationsByName(has_floruit_date); + for(Entity floruitDate : this.floruitList.getEntities()){ + Entity floruitDate0 = getWrapper().getEntityByIdWithContent(floruitDate.getId()); + Calendar cal = floruitList.getCalendar(floruitDate.getId()); + + if(floruitDate0.getAttributeByName("date") == null){ + floruitDate0.addAttribute(new Attribute("date", "date", cal.toJSONString())); + }else{ + floruitDate0.getAttributeByName("date").setValue(cal.toJSONString()); + } + getWrapper().saveAssertion(floruitDate0, getUserName()); + Relation hasFloruitDate = new Relation(this.entity, floruitDate0, has_floruit_date); + } + + //PERSON -> student of manyToMany -> PERSON + this.entity.removeAllSourceRelationsByName(was_student_of); + for(Entity teacher : this.studentOfList.getEntities()){ + Entity teacher0 = getWrapper().getEntityByIdWithContent(teacher.getId()); + Relation studentOf = new Relation(this.entity, teacher0, was_student_of); + } + + //PERSON -> has_role -> ROLE + this.entity.removeAllSourceRelationsByName(has_role); + for(Entity role : this.roleList.getEntities()){ + Entity role0 = getWrapper().getEntityByIdWithContent(role.getId()); + Relation hasRole = new Relation(this.entity, role0, has_role); + } + + //REFERENCE -> is_reference_of -> THIS + //this.entity = this.prepareReferencesToSave(this.entity); + this.prepareEndNoteRefs2Save(); + + this.entity = getWrapper().saveEntity(this.entity, getSessionUser().getEmail()); + this.setEntity(this.entity); + this.getCache().setMapDirty(true); + this.getAppBean().getBiographyBean().makeDirty(); + + logger.info("Entity saved - Time = " + (System.currentTimeMillis() - start) + ", " + entity); + this.printSuccessSavingEntity(); + + //getPopup().setRendered(false); + + + //setPopupText("CHANGING"); + + } catch (Exception e) { + logger.error(e.getMessage(), e); + e.printStackTrace(); + this.printInternalError(e); + } + saveEnd(); + return PAGE_EDITOR; + } + + public void listenerEditCalendarForLivedInPlaces(ActionEvent event){ + Entity entity = (Entity)getRequestBean("item"); + if(entity != null){ + Calendar cal = this.livedInPlaces.getCalendar(entity.getId()); + getSessionBean().editCalendar(cal, livedInPlaces, entity.getId()); + } + } + + public void listenerEditCalendarForFloruitDate(ActionEvent event){ + Entity entity = (Entity)getRequestBean("item"); + if(entity != null){ + Calendar cal = this.floruitList.getCalendar(entity.getId()); + getSessionBean().editCalendar(cal, floruitList, entity.getId()); + } + } + + public void listenerRomanizeNameTranslit(AjaxBehaviorEvent event){ + if(getAttributes().get("name_translit") != null) + this.romanizedNameTranslit = RomanizationLoC.convert(getAttributes().get("name_translit")); + } + + public Entity getShortName() { + return shortNameAlias; + } + + public void setShortName(Entity shortName) { + this.shortNameAlias = shortName; + } + + public String getValueShortName() { + return valueShortName; + } + + public void setValueShortName(String valueShortName) { + this.valueShortName = valueShortName; + } + + public void setToDate(Object x) { + System.out.println("hello"); + } + + public Converter getToDate() { + return new myDateTimeConverter(); + + } + + public Map<String, Boolean> getDeletedAliases() { + return deletedAliases; + } + + public void setDeletedAliases(Map<String, Boolean> deletedAliases) { + this.deletedAliases = deletedAliases; + } + + public void setNewAlias(String newAlias) { + this.newAlias = newAlias; + } + + public String getNewAlias() { + return newAlias; + } + + public String editMe(){ + if(this.entity != null){ + getSessionBean().editEntity(this.entity); + return "entry_edit_entity"; + } + return ""; + } + + public void setBirthPlaceLo(ListenerObject birthPlaceLo) { + this.birthPlaceLo = birthPlaceLo; + } + + public ListenerObject getBirthPlaceLo() { + return birthPlaceLo; + } + + public ListenerObject getDeathPlaceLo() { + return deathPlaceLo; + } + + public void setDeathPlaceLo(ListenerObject deathPlaceLo) { + this.deathPlaceLo = deathPlaceLo; + } + + public EntityList getLivedInPlaces() { + return livedInPlaces; + } + + public void setLivedInPlaces(EntityList livedInPlaces) { + this.livedInPlaces = livedInPlaces; + } + + public EntityList getStudentOfList() { + return studentOfList; + } + + + public void setStudentOfList(EntityList studentOfList) { + this.studentOfList = studentOfList; + } + + public EntityList getFloruitList() { + return floruitList; + } + + public void setFloruitList(EntityList floruitList) { + this.floruitList = floruitList; + } + + public String getRomanizedNameTranslit() { + return romanizedNameTranslit; + } + + public void setRomanizedNameTranslit(String romanizedNameTranslit) { + this.romanizedNameTranslit = romanizedNameTranslit; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/CurrentRepositoryBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,122 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.io.Serializable; + +import org.apache.commons.lang.StringUtils; +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.Node; + +public class CurrentRepositoryBean extends CodexEditorTemplate implements Serializable{ + private static final long serialVersionUID = 2926289436446091260L; + + private static Logger logger = Logger.getLogger(CurrentRepositoryBean.class); + + public static int MAX_PLACES = 100; + //private Entity repository; + + @Override + public void reset(){ + super.reset(); + this.entity = new Entity(Node.TYPE_ABOX, REPOSITORY, false); + } + + public CurrentRepositoryBean(){ + this.reset(); + setDefObjectClass(REPOSITORY); + registerChecker(getCityLo().statusImage, "City not valid!"); + registerChecker(getCountryLo().statusImage, "Country is not valid!"); + } + + + @Override + public void setEntity(Entity repository) { + this.reset(); + this.entity = repository; + + if(this.entity != null && this.entity.isPersistent()){ + if(this.entity.isLightweight()){ + this.entity = getWrapper().getEntityContent(this.entity); + } + + this.setCurrentId(this.entity.getId().toString()); + this.loadAttributes(this.entity);//, getDefinition(this.entity)); + + //this.loadReferences(this.entity); + this.loadEndNoteRefs(); + + for(Entity city : getWrapper().getTargetsForSourceRelation(this.entity, "is_in", PLACE, 1)){ + this.setCity(city); + } + } + } + + public String saveAsNewEntity(){ + this.setSelectedSaveAsNew(true); + return save(); + } + + + @Override + public String save(){ + super.save(); + try { + CheckResults cr = getCheckResults(); + if (cr.hasErrors){ + getSessionBean().setErrorMessages(cr); + getSessionBean().setDisplayError(true); + this.setSelectedSaveAsNew(false); + return PAGE_EDITOR; + } + + this.entity = this.updateEntityAttributes(this.entity); + + + Attribute attName = this.entity.getAttributeByName("name"); + String repositoryName = (attName == null) ? null : attName.getValue(); + if(StringUtils.isNotEmpty(repositoryName)){ + if(!checkUnityRepository(repositoryName, (isSelectedSaveAsNew()) ? null : this.entity.getId(), this.getCityLo().entity)){ + this.renderUnityCheckerDialog(); + this.setSelectedSaveAsNew(false); + return PAGE_EDITOR; + } + }else{ + this.addErrorMsg("Ths entity has not been saved, because its name was empty."); + this.addErrorMsg("You must enter a name."); + return PAGE_EDITOR; + } + + if(!isRepositoryConsistentBeforeSave()){ + return PAGE_EDITOR; + } + + this.entity.replaceSourceRelation(this.getCityLo().getEntity(), PLACE, is_in); + + //REFERENCE -> is_reference_of -> THIS + //this.entity = this.prepareReferencesToSave(this.entity); + this.prepareEndNoteRefs2Save(); + + if(isSelectedSaveAsNew()){ + this.entity.removeAllTargetRelations(is_part_of, COLLECTION); + this.entity = getWrapper().saveEntityAsNew(this.entity, getSessionUser().getEmail()); + }else{ + this.entity = getWrapper().saveEntity(this.entity, getSessionUser().getEmail()); + } + + this.generateSecundaryOW(this.entity, getSessionUser().getEmail()); + getSessionBean().setEditFormCurrentEntId(this.entity.getId()); + + logger.info("Entity saved - Time = " + (System.currentTimeMillis() - start) + ", " + entity); + this.printSuccessSavingEntity(); + + this.setSelectedSaveAsNew(false); + } catch (Exception e) { + logger.error(e.getMessage(), e); + e.printStackTrace(); + this.printInternalError(e); + } + saveEnd(); + return PAGE_EDITOR; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/CurrentRoleBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,77 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Node; + +public class CurrentRoleBean extends AbstractISMIBean{ + + /** + * + */ + private static final long serialVersionUID = -4934098828218979428L; + private static Logger logger = Logger.getLogger(CurrentRoleBean.class); + + public CurrentRoleBean(){ + this.entity = new Entity(Node.TYPE_ABOX, ROLE, false); + this.setDefObjectClass(ROLE); + } + + @Override + public void reset(){ + super.reset(); + this.entity = new Entity(Node.TYPE_ABOX, ROLE, false); + } + + @Override + public void setEntity(Entity role) { + this.reset(); + this.entity = role; + + if(this.entity != null && this.entity.isPersistent()){ + if (this.entity.isLightweight()) { + this.entity = getWrapper().getEntityContent(role); + } + this.loadAttributes(this.entity);//, getDefinition(this.entity)); + } + } + + @Override + public String save(){ + super.save(); + try { + + if(isConsistent()){ + this.entity = updateEntityAttributes(this.entity); + this.entity = getWrapper().saveEntity(this.entity, getUserName()); + getAppBean().setRoleListAsDirty(); + + logger.info("Entity saved - Time = " + (System.currentTimeMillis() - start) + ", " + entity); + this.printSuccessSavingEntity(); + } + + } catch (Exception e) { + logger.error(e.getMessage(), e); + e.printStackTrace(); + this.printInternalError(e); + } + + saveEnd(); + return PAGE_EDITOR; + } + + private boolean isConsistent(){ + + if(getAttributes().containsKey("name") && + StringUtils.isNotEmpty(getAttributes().get("name"))){ + return true; + + }else{ + addErrorMsg("The role has not be saved, because its name can not be empty!"); + return false; + } + + + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/CurrentSubjectBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,152 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.model.SelectItem; + +import org.apache.log4j.Logger; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Node; +import org.mpi.openmind.repository.bo.Relation; +import org.mpi.openmind.security.bo.User; + + +public class CurrentSubjectBean extends AbstractISMIBean { + + private static final long serialVersionUID = -435164522506185752L; + + private static Logger logger = Logger.getLogger(CurrentSubjectBean.class); + + public static String type = "type"; + public static String NO_SUBJECT = "NO_SUBJECT"; + + public static String has_subject = "has_subject"; + public static String SUBJECT = "SUBJECT"; + public static String main_subject = "main_subject"; + public static String sub_subject = "sub_subject"; + + private Long idMainSubject; + + private List<SelectItem> suggestedCategories = new ArrayList<SelectItem>(); + private List<SelectItem> suggestedTypes = new ArrayList<SelectItem>(); + + public CurrentSubjectBean(){ + suggestedTypes.add(new SelectItem(null, "-- choose --")); + suggestedTypes.add(new SelectItem(main_subject, main_subject)); + suggestedTypes.add(new SelectItem(sub_subject, sub_subject)); + reset(); + } + + @Override + public void reset(){ + super.reset(); + this.entity = new Entity(Node.TYPE_ABOX, SUBJECT, false); + + setDefObjectClass(SUBJECT); + this.idMainSubject = null; + + this.suggestedCategories = new ArrayList<SelectItem>(); + this.suggestedCategories.add(new SelectItem(null, "-- choose --")); + + List<Entity> cats = getWrapper().getEntitiesByAtt(SUBJECT, type, main_subject, -1, true); + + for(Entity cat : cats){ + SelectItem item = new SelectItem(cat.getId(), cat.getOwnValue()); + + item.setStyle("font-weight: bold; padding-left: 0px; font-size: 14;"); + this.suggestedCategories.add(item); + List<Entity> subCats = getWrapper().getSourcesForTargetRelation(cat, is_part_of, SUBJECT, -1); + for(Entity subCat : subCats){ + + SelectItem subItem = new SelectItem(subCat.getId(), subCat.getOwnValue()); + subItem.setStyle("padding-left: 10px; font-size: 12;"); + + this.suggestedCategories.add(subItem); + List<Entity> subsubCats = getWrapper().getSourcesForTargetRelation(subCat, is_part_of, SUBJECT, -1); + for(Entity subsubCat : subsubCats){ + + SelectItem subsubItem = new SelectItem(subsubCat.getId(), subsubCat.getOwnValue()); + subsubItem.setStyle("padding-left: 20px; font-size: 10;"); + this.suggestedCategories.add(subsubItem); + } + } + } + } + + public void setEntity(Entity subject) { + this.reset(); + + this.entity = subject; + if(this.entity.isPersistent()){ + this.setCurrentId(this.entity.getId().toString()); + if (subject.isLightweight()) { + this.entity = getWrapper().getEntityContent(this.entity); + } + this.loadAttributes(this.entity);//, getDefinition(this.entity)); + + for (Relation rel : this.entity.getSourceRelations()) { + if(rel.getOwnValue().equals(is_part_of)){ + this.idMainSubject = rel.getTargetId(); + } + } + } + } + + @Override + public String save() { + super.save(); + try { + User user = getSessionUser(); + + this.entity = updateEntityAttributes(this.entity); + + this.entity.removeAllSourceRelations(is_part_of, SUBJECT); + if(getIdMainSubject() != null){ + Entity mainCategory = getWrapper().getEntityById(getIdMainSubject()); + //replaceSourceRelation(this.entity, mainCategory, SUBJECT, is_part_of); + this.entity.replaceSourceRelation(mainCategory, SUBJECT, is_part_of); + } + + this.entity = getWrapper().saveEntity(this.entity, user.getEmail()); + getSessionBean().setEditFormCurrentEntId(this.entity.getId()); + + logger.info("Entity saved - Time = " + (System.currentTimeMillis() - start) + ", " + entity); + this.printSuccessSavingEntity(); + + getAppBean().resetSuggestedSubjects(); + } catch (Exception e) { + logger.error(e.getMessage(), e); + e.printStackTrace(); + this.printInternalError(e); + } + + saveEnd(); + return PAGE_EDITOR; + + } + + public List<SelectItem> getSuggestedCategories() { + return suggestedCategories; + } + + public void setSuggestedCategories(List<SelectItem> suggestedCategories) { + this.suggestedCategories = suggestedCategories; + } + + public Long getIdMainSubject() { + return idMainSubject; + } + + public void setIdMainSubject(Long idMainSubject) { + this.idMainSubject = idMainSubject; + } + + public List<SelectItem> getSuggestedTypes() { + return suggestedTypes; + } + + public void setSuggestedTypes(List<SelectItem> suggestedTypes) { + this.suggestedTypes = suggestedTypes; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/CurrentTextBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,1269 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +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 javax.faces.event.AjaxBehaviorEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +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.Node; +import org.mpi.openmind.repository.bo.Relation; +import org.mpi.openmind.repository.utils.NormalizerUtils; +import org.mpi.openmind.repository.utils.RomanizationLoC; +import org.mpi.openmind.repository.utils.TransliterationUtil; +import org.mpi.openmind.security.bo.User; + + + + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.entry.utils.PrivacityUtils; +import de.mpiwg.itgroup.ismi.util.guiComponents.Calendar; +import de.mpiwg.itgroup.ismi.util.guiComponents.EndNoteMisattribution; +import de.mpiwg.itgroup.ismi.util.guiComponents.EndNoteMisattributionTable; +import de.mpiwg.itgroup.ismi.util.guiComponents.EntityList; +import de.mpiwg.itgroup.ismi.util.guiComponents.TargetMisattribution; +import de.mpiwg.itgroup.ismi.util.guiComponents.MisattributionDataTable; + +public class CurrentTextBean extends AbstractISMIBean implements Serializable{ + private static final long serialVersionUID = 1017399812886455381L; + + private static Logger logger = Logger.getLogger(CurrentTextBean.class); + + private String valueShortTitle; + private Entity shortTitleAlias; // is now an alias of type "prime" + private String romanizedTitle; + private String romanizedPrimaAlias; + + private String valueTranslitTitle; + private Entity translitTitleAlias; // is now an alias of type "prime" + + private ListenerObject authorLo = new ListenerObject(PERSON, "name_translit"); + //private String authorInfo; + + private ListenerObject placeLo = new ListenerObject(PLACE, "name"); + + private ListenerObject dedicatedPersonLo = new ListenerObject(PERSON, "name_translit"); + + private ListenerObject commentaryLo = new ListenerObject(TEXT, "full_title_translit"); + + private ListenerObject translationLo = new ListenerObject(TEXT, "full_title_translit"); + + private ListenerObject versionLo = new ListenerObject(TEXT, "full_title_translit"); + + private static String PERSON_TYPE_CREATED_BY = "created_by"; + private static String PERSON_TYPE_DEDICATED_TO = "dedicated_to"; + private String personType; + + private Attribute attTitleAlias = new Attribute(); + private Map<Long, Boolean> deletedTitleAliases = new HashMap<Long, Boolean>(); + private String newTitleAlias; + + private Attribute attIncipitAlias = new Attribute(); + private Map<Long, Boolean> deletedIncipitAliases = new HashMap<Long, Boolean>(); + private String newIncipitAlias; + + private Attribute attExplicitAlias = new Attribute(); + private Map<Long, Boolean> deletedExplicitAliases = new HashMap<Long, Boolean>(); + private String newExplicitAlias; + + private Long idSubject; + private Entity subject; + + public static String main_subject = "main_subject"; + public static String sub_subject = "sub_subject"; + public static String type = "type"; + public static String NO_SUBJECT = "NO_SUBJECT"; + + private boolean searchTextDialogRendered = false; + private String stringTitle; + private String stringAuthor; + private List<SelectItem> textsFound = new ArrayList<SelectItem>(); + + private Long idTextSelected; + + private String COMMENTARY_CALLER = "Commentary"; + private String TRANSLATION_CALLER = "Translation"; + private String VERSION_CALLER = "Version"; + + private String searchCaller; + + private transient Calendar creationDate; + + private String textAuthorName; + private String textAuthorNameTranslit; + + private Boolean selectPersonRendered = false; + private List<SelectItem> personList = new ArrayList<SelectItem>(); + private Long selectedPersonId; + private boolean restrictedByRole = false; + + private EntityList aliasList; + private EntityList incipitAliasList; + private EntityList explicitAliasList; + + //private MisattributionDataTable misattDataTable; + private transient EndNoteMisattributionTable misattTable; + + public CurrentTextBean() { + this.reset(); + } + + @Override + public void reset(){ + super.reset(); + this.entity = new Entity(Node.TYPE_ABOX, TEXT, false); + setDefObjectClass(TEXT); + + this.aliasList = new EntityList(ALIAS, "alias", getWrapper(), getUserName()); + this.incipitAliasList = new EntityList(ALIAS, "alias", getWrapper(), getUserName()); + this.explicitAliasList = new EntityList(ALIAS, "alias", getWrapper(), getUserName()); + //this.misattDataTable = new MisattributionDataTable(PERSON, "name_translit"); + this.misattTable = new EndNoteMisattributionTable(); + + this.selectPersonRendered = false; + this.selectedPersonId = null; + this.personList = new ArrayList<SelectItem>(); + this.restrictedByRole = false; + + this.textAuthorName = new String(); + this.textAuthorNameTranslit = new String(); + + this.valueShortTitle = null; + this.shortTitleAlias = null; // is now an alias of type "prime" + + this.valueTranslitTitle = null; + this.translitTitleAlias = null; // is now an alias of type "prime" + + //this.authorLo = new ListenerObject(); + this.authorLo.reset(); + //this.authorInfo = null; + + //this.placeLo = new ListenerObject(); + this.placeLo.reset(); + + this.dedicatedPersonLo.reset(); + + this.commentaryLo.reset(); + + this.translationLo.reset(); + + this.versionLo.reset(); + + this.attTitleAlias = new Attribute(); + this.deletedTitleAliases = new HashMap<Long, Boolean>(); + this.newTitleAlias = null; + + this.attIncipitAlias = new Attribute(); + this.deletedIncipitAliases = new HashMap<Long, Boolean>(); + this.newIncipitAlias = null; + + this.attExplicitAlias = new Attribute(); + this.deletedExplicitAliases = new HashMap<Long, Boolean>(); + this.newExplicitAlias = null; + + this.idSubject = null; + this.subject = null; + + this.creationDate = new Calendar(); + + + registerChecker(authorLo, "Creator is not valid!"); + registerChecker(placeLo, "Place is not valid!"); + registerChecker(dedicatedPersonLo, "Place is not valid!"); + registerChecker(commentaryLo, "Commentary is not valid!"); + registerChecker(translationLo, "Translation is not valid!"); + registerChecker(versionLo, "Version is not valid!"); + + //getPopup().setRendered(false); + } + + public List<SelectItem> getPersonList() { + return personList; + } + + public void setPersonList(List<SelectItem> personList) { + this.personList = personList; + } + + public Boolean getSelectPersonRendered() { + return selectPersonRendered; + } + + public void setSelectPersonRendered(Boolean selectPersonRendered) { + this.selectPersonRendered = selectPersonRendered; + } + + /** + * Source's Relations # TEXT is_commentary_on TEXT # TEXT is_translation_of + * TEXT # TEXT is_version_of TEXT # TEXT was_created_by PERSON # TEXT + * was_created_in PLACE # TEXT was_dedicated_to PERSON # TEXT has_subject + * SUBJECT + * + * Target's Relations # ALIAS is_alias_title_of TEXT # ALIAS + * is_alias_incipit_of TEXT + * + * @param text + */ + @Override + public void setEntity(Entity text) { + this.reset(); + this.entity = text; + if(this.entity.isPersistent()){ + setCurrentId(this.entity.getId().toString()); + if (text.isLightweight()) { + this.entity = getWrapper().getEntityContent(this.entity); + this.entity.setLightweight(false); + } + + Attribute attCreationDate = this.entity.getAttributeByName("creation_date"); + if(attCreationDate != null && StringUtils.isNotEmpty(attCreationDate.getOwnValue())){ + this.creationDate = new Calendar(attCreationDate.getOwnValue()); + }else{ + this.creationDate = new Calendar(); + } + + + + this.loadAttributes(this.entity);//, getDefinition(this.entity)); + + for (Relation rel : text.getSourceRelations()) { + Entity target = null; + if( rel.getOwnValue().equals(has_subject)){ + this.subject = getTargetRelation(rel); + this.idSubject = subject.getId(); + } else if (rel.getOwnValue().equals("is_commentary_on")) { + target = getTargetRelation(rel); + this.commentaryLo.setEntityAndAttribute0(target); + } else if (rel.getOwnValue().equals("is_translation_of")) { + target = getTargetRelation(rel); + this.translationLo.setEntityAndAttribute0(target); + } else if (rel.getOwnValue().equals("is_version_of")) { + target = getTargetRelation(rel); + this.versionLo.setEntityAndAttribute0(target); + } else if (rel.getOwnValue().equals("was_created_by")) { + target = getTargetRelation(rel); + this.authorLo.setEntityAndAttribute0(target); + + /* + this.authorInfo = "ID = " + authorLo.getEntity().getId(); + Attribute attArabicName = getTargetAttribute(target, "name"); + if(attArabicName != null){ + this.authorInfo += ", Arabic Name = " + attArabicName.getOwnValue(); + this.textAuthorName = attArabicName.getValue(); + }*/ + + if(this.authorLo.attribute != null){ + this.textAuthorNameTranslit = this.authorLo.attribute.getValue(); + } + + } else if (rel.getOwnValue().equals("was_dedicated_to")) { + target = getTargetRelation(rel); + this.dedicatedPersonLo.setEntityAndAttribute0(target); + + } else if (rel.getOwnValue().equals("was_created_in")) { + target = getTargetRelation(rel); + //rich this.placeLo.setEntityAndAttribute(target, "name"); + this.placeLo.setEntityAndAttribute0(target); + //} else if (rel.getOwnValue().equals(misattributed_to)) { + } else if (rel.getOwnValue().equals("has_author_misattribution")) { + target = getTargetRelation(rel); + //String refId = (rel.getAttributeByName("reference_id") != null) ? rel.getAttributeByName("reference_id").getValue() : null; + //String notes = (rel.getAttributeByName("notes") != null) ? rel.getAttributeByName("notes").getValue() : null; + //target=person + //this.misattDataTable.add(target, refId, notes); + //this.misattTable.add(target, ref, rel); + this.misattTable.load(target); + } + + } + for (Relation rel : text.getTargetRelations()) { + + if (rel.getOwnValue().equals("is_alias_title_of")) { + Entity alias = getWrapper().getEntityByIdWithContent(rel.getSourceId()); + this.aliasList.add(alias); + } else if (rel.getOwnValue().equals("is_alias_incipit_of")) { + Entity alias = getWrapper().getEntityByIdWithContent(rel.getSourceId()); + this.incipitAliasList.add(alias); + } else if (rel.getOwnValue().equals("is_alias_explicit_of")) { + Entity alias = getWrapper().getEntityByIdWithContent(rel.getSourceId()); + this.explicitAliasList.add(alias); + } else if (rel.getOwnValue().equals("is_prime_alias_title_of")) { + Entity alias = getWrapper().getEntityByIdWithContent(rel.getSourceId()); + this.shortTitleAlias = alias; + this.valueShortTitle = alias.getAttributeByName("alias").getValue(); + } + } + /* + List<String> idsNoFound = new ArrayList<String>(); + for(TargetMisattribution misAtt : this.misattDataTable.getMisattList()){ + if(misAtt.getItem().getErrorLoading() != null){ + idsNoFound.add(misAtt.getItem().getPublication().getObjid()); + } + }*/ + //this.loadReferences(this.entity); + this.loadEndNoteRefs(); + this.displayUrl = generateDisplayUrl(authorLo.entity, text, null, getAppBean().getRoot()); + } + } + + /** + * Added by DW it is no used anymore + * + * @param event + */ + public void translitTitleChangeListener(ValueChangeEvent event) { + try { + if (event.getNewValue() == null) { + return; + } + if (event.getNewValue().equals(event.getOldValue())) { + return; + } + + String newName = (String) event.getNewValue(); + + if (translitTitleAlias == null) { + translitTitleAlias = new Entity(Node.TYPE_ABOX, "ALIAS", false); + } + + Attribute attr = this.translitTitleAlias + .getAttributeByName("alias"); + if (attr == null) { + this.translitTitleAlias.addAttribute(new Attribute("alias", + TEXT, newName)); + } else + attr.setValue(newName); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + public String translitTitleAction() { + String pn = getAttributes().get("full_title"); + + String translit = TransliterationUtil.getTransliteration(pn); + getAttributes().put("full_title_translit", translit); + + return "translit"; + + } + + public void showSearchTextCommentaryDialog(ActionEvent event) { + this.setSearchTextDialogRendered(true); + this.searchCaller = COMMENTARY_CALLER; + } + + public void showSearchTextTranslationDialog(ActionEvent event) { + this.setSearchTextDialogRendered(true); + this.searchCaller = TRANSLATION_CALLER; + } + + public void showSearchTextVersionDialog(ActionEvent event) { + this.setSearchTextDialogRendered(true); + this.searchCaller = VERSION_CALLER; + } + + public void closeSearchTextDialog(ActionEvent event) { + this.setSearchTextDialogRendered(false); + } + + public void resetSearchText(ActionEvent event) { + this.textsFound = new ArrayList<SelectItem>(); + this.stringAuthor = ""; + this.stringTitle = ""; + } + + public void takeVersion(ActionEvent event) { + if(this.idTextSelected != null){ + Entity ent = getWrapper().getEntityById(idTextSelected); + if(ent != null){ + if (VERSION_CALLER.equals(this.searchCaller)) { + this.versionLo.setEntityAndAttribute0(ent); + + } else if (COMMENTARY_CALLER.equals(this.searchCaller)) { + this.commentaryLo.setEntityAndAttribute0(ent); + + } else if (TRANSLATION_CALLER.equals(this.searchCaller)) { + this.translationLo.setEntityAndAttribute0(ent); + } + this.searchTextDialogRendered = false; + } + } + } + + public String getStringTitle() { + return stringTitle; + } + + public void setStringTitle(String stringTitle) { + this.stringTitle = stringTitle; + } + + public String getStringAuthor() { + return stringAuthor; + } + + public void setStringAuthor(String stringAuthor) { + this.stringAuthor = stringAuthor; + } + + public void searchText(ActionEvent event) { + this.textsFound = new ArrayList<SelectItem>(); + + if(StringUtils.isNotEmpty(stringTitle)){ + if (StringUtils.isNotEmpty(this.stringAuthor)) { + String termAuthor = NormalizerUtils.normalize(stringAuthor); + for(Entity title : getWrapper().getEntitiesByAtt(TEXT, "full_title_translit", stringTitle, -1, true)){ + for(Entity author : + getWrapper().getTargetsForSourceRelation(title, "was_created_by", PERSON, -1)){ + String authorOW = (StringUtils.isNotEmpty(author.getNormalizedOwnValue())) ? author.getNormalizedOwnValue() : ""; + if(authorOW.contains(termAuthor)){ + this.textsFound.add( + new SelectItem(title.getId(), "Title [" + title.getId() + "]: " + title.getOwnValue() + + " - Author: " + author.getOwnValue())); + } + } + } + }else{ + for(Entity title : getWrapper().getEntitiesByAtt(TEXT, "full_title_translit", stringTitle, -1, true)){ + this.textsFound.add( + new SelectItem(title.getId(), "Title: " + title.getOwnValue())); + } + } + }else if (StringUtils.isNotEmpty(this.stringAuthor)) { + String termAuthor = NormalizerUtils.normalize(stringAuthor); + for(Entity author : getCache().getPersonListByRole("Author")){ + String authorOW = (StringUtils.isNotEmpty(author.getNormalizedOwnValue())) ? author.getNormalizedOwnValue() : ""; + if(authorOW.contains(termAuthor)){ + for(Entity title : + getWrapper().getSourcesForTargetRelation(author, "was_created_by", TEXT, -1)){ + this.textsFound.add( + new SelectItem(title.getId(), "Author[" + author.getId() + "]: " + author.getOwnValue() + + " - Title: " + title.getOwnValue())); + } + } + } + } + } + + public void restrictedByRoleChange(ValueChangeEvent event) { + if (event.getNewValue().equals(event.getOldValue())) + return; + Boolean val = (Boolean) event.getNewValue(); + this.setRestrictedByRole(val); + this.updatePersonList(); + } + + public void listenerRomanizeTitleTranslit(AjaxBehaviorEvent event){ + if(getAttributes().get("full_title_translit") != null) + this.romanizedTitle = RomanizationLoC.convert(getAttributes().get("full_title_translit")); + } + + public void listenerRomanizePrimaAlias(AjaxBehaviorEvent event){ + if(valueShortTitle != null){ + this.romanizedPrimaAlias = RomanizationLoC.convert(valueShortTitle); + } + } + + public void listenerShowAllAuthors(ActionEvent event) { + this.setPersonType(PERSON_TYPE_CREATED_BY); + this.updatePersonList(); + } + + public void listenerShowAllDedicatedToPersons(ActionEvent event) { + this.setPersonType(PERSON_TYPE_DEDICATED_TO); + this.updatePersonList(); + } + + private void updatePersonList(){ + if (!restrictedByRole) + this.personList = getCache().getAllPersons(); + else { + this.personList = getCache().getPersonsByRole("Author"); + } + this.selectPersonRendered = true; + } + + public void listenerPersonCancel(ActionEvent event) { + this.selectPersonRendered = false; + } + + public void listenerSelectPerson(ActionEvent event){ + if(this.selectedPersonId != null){ + Entity selectedPerson = getWrapper().getEntityById(selectedPersonId); + if(selectedPerson != null){ + if(this.personType.equals(PERSON_TYPE_CREATED_BY)){ + this.authorLo.setEntityAndAttribute0(selectedPerson); + this.authorLo.entityInfo = "ID = " + authorLo.getEntity().getId(); + + Attribute attArabicName = getTargetAttribute(selectedPerson, "name"); + if(attArabicName != null){ + this.authorLo.entityInfo += ", Arabic Name = " + attArabicName.getOwnValue(); + this.textAuthorName = attArabicName.getValue(); + } + + if(this.authorLo.attribute != null){ + this.textAuthorNameTranslit = this.authorLo.attribute.getValue(); + } + }else if(this.personType.equals(PERSON_TYPE_DEDICATED_TO)){ + this.dedicatedPersonLo.setEntityAndAttribute0(selectedPerson); + } + } + } + this.setSelectPersonRendered(false); + } + + + /** + * Added by DW + * + * @param event + */ + /*jurzua + public void shortTitleChangeListener(ValueChangeEvent event) { + try { + if (event.getNewValue() == null) { + return; + } + if (event.getNewValue().equals(event.getOldValue())) { + return; + } + + String newShortName = (String) event.getNewValue(); + + if (shortTitleAlias == null) { + shortTitleAlias = new Entity(Node.TYPE_ABOX, "ALIAS", false); + } + + Attribute attr = this.shortTitleAlias.getAttributeByName("alias"); + if (attr == null) { + this.shortTitleAlias.addAttribute(new Attribute("alias", + TEXT, newShortName)); + } else + attr.setValue(newShortName); + + } catch (Exception e) { + e.printStackTrace(); + } + }*/ + /* + public void translationChangeListener(ValueChangeEvent event) { + translationLo = changeListener(event, translationLo, TEXT, "full_title_translit"); + + }*/ + + /* + public void commentaryChangedListener(ValueChangeEvent event) { + commentaryLo = changeListener(event, commentaryLo, TEXT, "full_title_translit"); + + }*/ + + /* + public void dedicatedPersonChangedListener(ValueChangeEvent event) { + dedicatedPersonLo = changeListener(event, dedicatedPersonLo, PERSON, "name_translit"); + } + */ + /* + public void valueChangeMethod4Author(ValueChangeEvent event) { + System.out.println("**** " + event.getNewValue()); + System.out.println(this.authorLo.entity); + System.out.println(); + + this.authorInfo = null; + authorLo = changeListener(event, authorLo, PERSON, "name_translit"); + if(authorLo != null && authorLo.entity != null && authorLo.entity.isPersistent()){ + this.authorInfo = "ID = " + authorLo.getEntity().getId(); + Attribute attArabicName = getTargetAttribute(authorLo.entity, "name_translit"); + if(attArabicName != null) + this.authorInfo += ", Arabic Name = " + attArabicName.getOwnValue(); + } + } + + + public void actionListenerNotSelectingAuthor(ActionEvent event){ + this.authorLo.suggestedItems = new ArrayList<SelectItem>(); + this.authorLo.entity = null; + this.authorLo.attribute = null; + }*/ + + + /* + public void actionListenerSelectAuthor(ActionEvent event){ + System.out.println("actionListenerSelectAuthor"); + System.out.println(this.authorLo.entity); + System.out.println(); + + this.authorLo.suggestedItems = new ArrayList<SelectItem>(); + SelectItem selectItem = (SelectItem) getRequestBean("item"); + if(selectItem != null){ + Attribute att = (Attribute)selectItem.getValue(); + + Entity ent = getWrapper().getEntityById(att.getSourceId()); + + if(ent != null){ + this.authorLo.setEntityAndAttribute(ent, "name_translit"); + + this.authorInfo = "ID = " + authorLo.getEntity().getId(); + Attribute attArabicName = getTargetAttribute(ent, "name"); + if(attArabicName != null){ + this.authorInfo += ", Arabic Name = " + attArabicName.getOwnValue(); + this.textAuthorName = attArabicName.getValue(); + } + + if(this.authorLo.attribute != null){ + this.textAuthorNameTranslit = this.authorLo.attribute.getValue(); + } + } + } + } + */ + + + /* + public void placeChangedListener(ValueChangeEvent event) { + placeLo = changeListener(event, placeLo, PLACE, "name"); + }*/ + + /* + @Override + public Entity getEntity() { + if (this.entity == null) { + this.entity = new Entity(); + this.entity.setObjectClass(TEXT); + this.entity.setLightweight(false); + this.loadAttributes(this.entity);//, getDefinition(this.entity)); + } + return this.entity; + } + */ + public boolean mandatoryEntriesOK(){ + boolean ok = true; + if(this.authorLo.entity == null || !this.authorLo.entity.isPersistent()){ + addGeneralMsg("<Created by> is a mandatory entry. If you do not know the author of this text, you should select the person <ANONYMOUS>."); + ok = false; + } + return ok; + } + + @Override + public String save() { + super.save(); + try { + + if(!mandatoryEntriesOK()){ + addGeneralMsg("The entity could not be saved."); + return PAGE_EDITOR; + } + + User user = getSessionUser(); + + CheckResults cr = getCheckResults(); + if (cr.hasErrors) { + getSessionBean().setErrorMessages(cr); + getSessionBean().setDisplayError(true); + return PAGE_EDITOR; + } + + + + getAttributes().put("creation_date", this.creationDate.toJSONString()); + + this.entity = updateEntityAttributes(this.entity); + + this.entity.replaceSourceRelation(commentaryLo.entity, TEXT, "is_commentary_on"); + + this.entity.replaceSourceRelation(translationLo.entity, TEXT, "is_translation_of"); + + this.entity.replaceSourceRelation(versionLo.entity, TEXT, "is_version_of"); + + this.entity.replaceSourceRelation(authorLo.entity, PERSON, "was_created_by"); + + this.entity.replaceSourceRelation(dedicatedPersonLo.entity, PERSON, "was_dedicated_to"); + + this.entity.replaceSourceRelation(placeLo.entity, PLACE, "was_created_in"); + + this.entity.removeAllSourceRelations(has_subject, SUBJECT); + if(getIdSubject() != null){ + this.subject = getWrapper().getEntityByIdWithContent(getIdSubject()); + this.entity.replaceSourceRelation(subject, SUBJECT, has_subject); + } + + + //is_prime_alias_title_of + if(!StringUtils.isEmpty(valueShortTitle)){ + this.entity.removeAllTargetRelations("is_prime_alias_title_of", ALIAS); + + if(this.shortTitleAlias == null){ + //1)create alias, 2) update value of alias3) save alias, and 4) add to this text. + shortTitleAlias = new Entity(Node.TYPE_ABOX, ALIAS, false); + shortTitleAlias.addAttribute(new Attribute("alias", "text", this.valueShortTitle)); + getWrapper().saveEntity(shortTitleAlias, getUserName()); + }else{ + //1) update value, 2) re-save alias + this.shortTitleAlias.getAttributeByName("alias").setOwnValue(this.valueShortTitle); + this.shortTitleAlias.removeAllSourceRelations("is_prime_alias_title_of", TEXT); + getWrapper().saveEntity(shortTitleAlias, getUserName()); + } + Relation aliasRel = new Relation(shortTitleAlias, this.entity, "is_prime_alias_title_of"); + } + + /* + if (this.shortTitleAlias == null + || (shortTitleAlias.getAttributeByName("alias") != null && StringUtils + .isEmpty(shortTitleAlias + .getAttributeByName("alias").getOwnValue()))) { + this.entity.removeAllTargetRelations("is_prime_alias_title_of", + ALIAS); + } else if (this.shortTitleAlias != null) { + shortTitleAlias = getWrapper().saveEntity(shortTitleAlias, user.getEmail()); + this.entity.setAsUniqueTargetRelation("is_prime_alias_title_of", + this.shortTitleAlias); + } + */ + + //ALIAS -> is_alias_title_of -> TEXT + this.entity.removeAllTargetRelationsByName("is_alias_title_of"); + for(Entity alias : this.aliasList.getEntities()){ + Entity alias0 = getWrapper().getEntityByIdWithContent(alias.getId()); + Relation aliasRel = new Relation(alias0, this.entity, "is_alias_title_of"); + } + + //saveAliases2(incipitAliases, deletedIncipitAliases, + // "is_alias_incipit_of"); + //deletedIncipitAliases = refreshAliasMap(incipitAliases, deletedIncipitAliases); + this.entity.removeAllTargetRelationsByName("is_alias_incipit_of"); + for(Entity alias : this.incipitAliasList.getEntities()){ + Entity alias0 = getWrapper().getEntityByIdWithContent(alias.getId()); + Relation aliasRel = new Relation(alias0, this.entity, "is_alias_incipit_of"); + } + + /* + saveAliases2(explicitAliases, deletedExplicitAliases, + "is_alias_explicit_of"); + deletedExplicitAliases = refreshAliasMap(explicitAliases, deletedExplicitAliases); + */ + this.entity.removeAllTargetRelationsByName("is_alias_explicit_of"); + for(Entity alias : this.explicitAliasList.getEntities()){ + Entity alias0 = getWrapper().getEntityByIdWithContent(alias.getId()); + Relation aliasRel = new Relation(alias0, this.entity, "is_alias_explicit_of"); + } + + //String lastAction = ""; + + //REFERENCE -> is_reference_of -> THIS + //this.entity = this.prepareReferencesToSave(this.entity); + this.prepareEndNoteRefs2Save(); + + this.entity.removeAllSourceRelations(EndNoteMisattribution.HAS_AUTHOR_MISATT, EndNoteMisattribution.MISATT); + + this.entity = getWrapper().saveEntity(this.entity, user.getEmail()); + this.getAppBean().setAllTextsAsDirty(); + getAppBean().getSimpleSearchCache().setMapDirty(true); + + this.entity = this.misattTable.saveMisattributions(this.entity); + + this.setEntity(this.entity); + //lastAction = "save text"; + + + this.generateSecundaryOW(this.entity, getSessionUser().getEmail()); + + logger.info("Entity saved - Time = " + (System.currentTimeMillis() - start) + ", " + entity); + this.printSuccessSavingEntity(); + + //setActionInfo(lastAction); + + + } catch (Exception e) { + logger.error(e.getMessage(), e); + e.printStackTrace(); + this.printInternalError(e); + } + saveEnd(); + return PAGE_EDITOR; + } + + public EntityList getIncipitAliasList() { + return incipitAliasList; + } + + public void setIncipitAliasList(EntityList incipitAliasList) { + this.incipitAliasList = incipitAliasList; + } + + /** + * This method saves the text as new entity, and its related alias and + * witness. + * + * @return + */ + public String saveAsNewEntity() { + + try { + User user = getSessionUser(); + + CheckResults cr = getCheckResults(); + if (cr.hasErrors) { + getSessionBean().setErrorMessages(cr); + getSessionBean().setDisplayError(true); + return "SAVE_ERROR"; + } + + + this.entity = updateEntityAttributes(this.entity); + //text.setOwnValue(createOwnValue()); + + //text.removeSourceRelation("is_commentary_of", commentaryLo.entity); + //replaceSourceRelation(text, commentaryLo.entity, TEXT, "is_commentary_on"); + this.entity.replaceSourceRelation(commentaryLo.entity, TEXT, "is_commentary_on"); + + //text.removeSourceRelation("is_translation_of", translationLo.entity); + //replaceSourceRelation(text, translationLo.entity, TEXT, "is_translation_of"); + this.entity.replaceSourceRelation(translationLo.entity, TEXT, "is_translation_of"); + + //text.removeSourceRelation("is_version_of", versionLo.entity); + //replaceSourceRelation(text, versionLo.entity, TEXT, "is_version_of"); + this.entity.replaceSourceRelation(versionLo.entity, TEXT, "is_version_of"); + + //text.removeSourceRelation("was_created_by", authorLo.entity); + //replaceSourceRelation(text, authorLo.entity, PERSON, "was_created_by"); + this.entity.replaceSourceRelation(authorLo.entity, PERSON, "was_created_by"); + + //text.removeSourceRelation("was_dedicated_to", dedicatedPersonLo.entity); + //replaceSourceRelation(text, dedicatedPersonLo.entity, PERSON, + // "was_dedicated_to"); + this.entity.replaceSourceRelation(dedicatedPersonLo.entity, PERSON, "was_dedicated_to"); + + //text.removeSourceRelation("was_created_in", placeLo.entity); + //replaceSourceRelation(text, placeLo.entity, PLACE, "was_created_in"); + this.entity.replaceSourceRelation(placeLo.entity, PLACE, "was_created_in"); + + //String lastAction = ""; + + // removing transiently the target relation, + // because they should not be saved as new + this.entity.removeAllTargetRelations("is_exemplar_of", "WITNESS"); + this.entity.removeAllTargetRelations("is_prime_alias_title_of", "ALIAS"); + this.entity.removeAllTargetRelations("is_alias_title_of", "ALIAS"); + this.entity.removeAllTargetRelations("is_alias_incipit_of", "ALIAS"); + this.entity.removeAllTargetRelations("is_alias_explicit_of", "ALIAS"); + + + this.entity = getWrapper().saveEntityAsNew(this.entity, user.getEmail()); + //((AllTextsBean) this.getSessionBean("AllTexts")).setAllTextsAsDirty(); + this.getAppBean().setAllTextsAsDirty(); + getAppBean().getSimpleSearchCache().setMapDirty(true); + + //lastAction = "save text as new entity"; + getSessionBean().setEditFormCurrentEntId(this.entity.getId()); + + logger.info("The entity was saved successfully!!!" + this.entity); + //this.saveAsNew = false; + + //setActionInfo(lastAction); + + + } catch (Exception e) { + logger.error(e.getMessage(), e); + e.printStackTrace(); + this.printInternalError(e); + } + return PAGE_EDITOR; + } + + /** + * Refresh aliasMap: delete the tuples, which are ticked to be deleted. + * + * @param map + * @return + */ + private Map<Long, Boolean> refreshAliasMap(List<Entity> list, Map<Long, Boolean> aliasesMap){ + for(Long id : aliasesMap.keySet()){ + if(aliasesMap.get(id)){ + aliasesMap.remove(id); + Entity alias = getEntityById(list, id); + if(alias != null){ + list.remove(alias); + } + } + } + return aliasesMap; + } + + public Attribute getAttTitleAlias() { + return attTitleAlias; + } + + public void setAttTitleAlias(Attribute attTitleAlias) { + this.attTitleAlias = attTitleAlias; + } + + public Attribute getAttIncipitAlias() { + return attIncipitAlias; + } + + public void setAttIncipitAlias(Attribute attIncipitAlias) { + this.attIncipitAlias = attIncipitAlias; + } + + public Attribute getAttExplicitAlias() { + return attExplicitAlias; + } + + public void setAttExplicitAlias(Attribute attExplicitAlias) { + this.attExplicitAlias = attExplicitAlias; + } + + public String getValueShortTitle() { + return valueShortTitle; + } + + public void setValueShortTitle(String valueShortTitle) { + this.valueShortTitle = valueShortTitle; + } + + public Entity getShortTitleAlias() { + return shortTitleAlias; + } + + public void setShortTitleAlias(Entity shortTitleAlias) { + this.shortTitleAlias = shortTitleAlias; + } + + public String getValueTranslitTitle() { + return valueTranslitTitle; + } + + public void setValueTranslitTitle(String valueTranslitTitle) { + this.valueTranslitTitle = valueTranslitTitle; + } + + public Entity getTranslitTitleAlias() { + return translitTitleAlias; + } + + public void setTranslitTitleAlias(Entity translitTitleAlias) { + this.translitTitleAlias = translitTitleAlias; + } + + public void setNewTitleAlias(String newAlias) { + this.newTitleAlias = newAlias; + } + + public String getNewTitleAlias() { + return newTitleAlias; + } + + /** + * <p>This method saves transiently the aliases as new Entities, which are not marked to be deleted + * in aliasesMap.</p> + * + * @param aliases list of aliases showing in the interface. + * @param aliasesMap map id - boolean, which indicates if the alias[id] should be deleted(true). + * @param aliasRelationName name of the relation which links this text whith the given alias list. + * @param user + */ + /* + private void saveAliasesAsNew(List<Entity> aliases, + Map<Long, Boolean> aliasesMap, String aliasRelationName, String user) { + + //first step: save the alias, if it is ticked as 'no delete' + for(Long aliasId : aliasesMap.keySet()){ + if(!aliasesMap.get(aliasId)){ + Entity alias = getEntityById(aliases, new Long(aliasId)); + if(alias != null){ + alias.removeAllSourceRelations(aliasRelationName, TEXT); + Relation rel = new Relation(alias, this.entity, aliasRelationName); + getWrapper().saveEntityAsNew(alias, user); + } + } + } + }*/ + + /** + * <p>This method removes transiently the aliases, which are marked to be deleted + * and insert to the text the alias, which are not yet contained.</p> + * + * @param aliases list of aliases showing in the interface. + * @param aliasesMap map id - boolean, which indicates if the alias[id] should be deleted(true). + * @param aliasRelationName name of the relation which links this text whith the given alias list. + */ + /* + private void saveAliases2(List<Entity> aliases, + Map<Long, Boolean> aliasesMap, String aliasRelationName) { + + List<Relation> aliasRelList = this.entity.getTargetRelations(aliasRelationName, "ALIAS"); + + //first step: delete aliases, which are ticked to be deleted and are contained by the current text + for(Relation aliasRel : aliasRelList){ + //if the alias Map does not contain the 'relation source' or it is marked to be deleted, + //the relation should be removed from the text + if(!aliasesMap.containsKey(aliasRel.getSourceId()) || aliasesMap.get(aliasRel.getSourceId())){ + text.removeTargetRelation(aliasRel); + } + } + + //second step: insert alias (as relation) to the text, + //if the alias is not contained by the text + for(Long aliasId : aliasesMap.keySet()){ + if(!aliasesMap.get(aliasId)){ + if(!text.containsTargetRelation(aliasRelationName, new Long(aliasId))){ + Entity alias = getEntityById(aliases, new Long(aliasId)); + if(alias != null){ + Relation rel = new Relation(alias, this.entity, aliasRelationName); + } + } + } + } + }*/ + + /** + * TODO move this method to some util's package + * @return + */ + private Entity getEntityById(List<Entity> list, Long id){ + for(Entity e : list){ + if(e.getId().compareTo(id) == 0){ + return e; + } + } + return null; + } + + public Map<Long, Boolean> getDeletedIncipitAliases() { + return deletedIncipitAliases; + } + + public void setDeletedIncipitAliases( + Map<Long, Boolean> deletedIncipitAliases) { + this.deletedIncipitAliases = deletedIncipitAliases; + } + + public Map<Long, Boolean> getDeletedExplicitAliases() { + return deletedExplicitAliases; + } + + public void setDeletedExplicitAliases( + Map<Long, Boolean> deletedExplicitAliases) { + this.deletedExplicitAliases = deletedExplicitAliases; + } + + public String getNewIncipitAlias() { + return newIncipitAlias; + } + + public void setNewIncipitAlias(String newIncipitAlias) { + this.newIncipitAlias = newIncipitAlias; + } + + public String getNewExplicitAlias() { + return newExplicitAlias; + } + + public void setNewExplicitAlias(String newExplicitAlias) { + this.newExplicitAlias = newExplicitAlias; + } + + public Map<Long, Boolean> getDeletedTitleAliases() { + return deletedTitleAliases; + } + + public void setDeletedTitleAliases(Map<Long, Boolean> deletedTitleAliases) { + this.deletedTitleAliases = deletedTitleAliases; + } + + public boolean isSearchTextDialogRendered() { + return searchTextDialogRendered; + } + + public void setSearchTextDialogRendered(boolean searchTextDialogRendered) { + this.searchTextDialogRendered = searchTextDialogRendered; + } + + public void setTextsFound(List<SelectItem> textsFound) { + this.textsFound = textsFound; + } + + public List<SelectItem> getTextsFound() { + return textsFound; + } + + public Long getIdTextSelected() { + return idTextSelected; + } + + public void setIdTextSelected(Long idTextSelected) { + this.idTextSelected = idTextSelected; + } + + public String getSearchCaller() { + return searchCaller; + } + + public void setSearchCaller(String searchCaller) { + this.searchCaller = searchCaller; + } + public ListenerObject getAuthorLo() { + return authorLo; + } + + public void setAuthorLo(ListenerObject authorLo) { + this.authorLo = authorLo; + } + + public ListenerObject getPlaceLo() { + return placeLo; + } + + public void setPlaceLo(ListenerObject placeLo) { + this.placeLo = placeLo; + } + + public ListenerObject getDedicatedPersonLo() { + return dedicatedPersonLo; + } + + public void setDedicatedPersonLo(ListenerObject dedicatedPersonLo) { + this.dedicatedPersonLo = dedicatedPersonLo; + } + + public ListenerObject getCommentaryLo() { + return commentaryLo; + } + + public void setCommentaryLo(ListenerObject commentaryLo) { + this.commentaryLo = commentaryLo; + } + + public ListenerObject getTranslationLo() { + return translationLo; + } + + public void setTranslationLo(ListenerObject translationLo) { + this.translationLo = translationLo; + } + + public ListenerObject getVersionLo() { + return versionLo; + } + + public void setVersionLo(ListenerObject versionLo) { + this.versionLo = versionLo; + } + + public Long getIdSubject() { + return idSubject; + } + + public void setIdSubject(Long idSubject) { + this.idSubject = idSubject; + } + + public Entity getSubject() { + return subject; + } + + public void setSubject(Entity subject) { + this.subject = subject; + } + + public String getTextAuthorName() { + return textAuthorName; + } + + public Calendar getCreationDate() { + return creationDate; + } + + public void setCreationDate(Calendar creationDate) { + this.creationDate = creationDate; + } + + public void setTextAuthorName(String textAuthorName) { + this.textAuthorName = textAuthorName; + } + + public String getTextAuthorNameTranslit() { + return textAuthorNameTranslit; + } + + public void setTextAuthorNameTranslit(String textAuthorNameTranslit) { + this.textAuthorNameTranslit = textAuthorNameTranslit; + } + + public boolean isRestrictedByRole() { + return restrictedByRole; + } + + public void setRestrictedByRole(boolean restrictedByRole) { + this.restrictedByRole = restrictedByRole; + } + + + public String getPersonType() { + return personType; + } + + public void setPersonType(String personType) { + this.personType = personType; + } + + public EntityList getAliasList() { + return aliasList; + } + + public void setAliasList(EntityList aliasList) { + this.aliasList = aliasList; + } + + public EntityList getExplicitAliasList() { + return explicitAliasList; + } + + public void setExplicitAliasList(EntityList explicitAliasList) { + this.explicitAliasList = explicitAliasList; + } + + public Long getSelectedPersonId() { + return selectedPersonId; + } + + public void setSelectedPersonId(Long selectedPersonId) { + this.selectedPersonId = selectedPersonId; + } + + public EndNoteMisattributionTable getMisattTable() { + return misattTable; + } + + public void setMisattTable(EndNoteMisattributionTable misattTable) { + this.misattTable = misattTable; + } + + public String getRomanizedTitle() { + return romanizedTitle; + } + + public void setRomanizedTitle(String romanizedTitle) { + this.romanizedTitle = romanizedTitle; + } + + public String getRomanizedPrimaAlias() { + return romanizedPrimaAlias; + } + + public void setRomanizedPrimaAlias(String romanizedPrimaAlias) { + this.romanizedPrimaAlias = romanizedPrimaAlias; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/CurrentWitnessBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,1099 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.faces.component.UIComponent; +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +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.Node; +import org.mpi.openmind.repository.bo.Relation; +import org.mpi.openmind.security.bo.User; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.auxObjects.lo.WitnessAuthorLO; +import de.mpiwg.itgroup.ismi.auxObjects.lo.WitnessTextLO; +import de.mpiwg.itgroup.ismi.util.guiComponents.Calendar; +import de.mpiwg.itgroup.ismi.util.guiComponents.EntityList; +import de.mpiwg.itgroup.ismi.util.guiComponents.StatusImage; + +public class CurrentWitnessBean extends CodexEditorTemplate implements Serializable{ + + private static final long serialVersionUID = -7645136722251494419L; + + private static Logger logger = Logger.getLogger(CurrentWitnessBean.class); + + private Boolean codicesOverviewRendered = false; + private List <CodexForList> codicesAll = new ArrayList<CodexForList>(); + + private List<SelectItem> titles_list = new ArrayList<SelectItem>(); + private Long selectedTitleId; + private Boolean selectTitleRendered = false; + private String selectPersonType; + + private List<SelectItem> persons_list = new ArrayList<SelectItem>(); + private Long selectedPersonId; + private Boolean selectPersonRendered = false; + private Boolean restrictedByRole = true; + + //private Entity witness; + + private ListenerObject titleLo = new WitnessTextLO(TEXT, full_title_translit, this); + + private String valueTitle = ""; + + // WITNESS -> has_title_written_as -> ALIAS + private String valueTextWritten = ""; + private List<SelectItem> suggestedTitlesWritten = new ArrayList<SelectItem>(); + private Long valueTitleSelectedId; + + // WITNESS -> has_authorWritten_as -> ALIAS + private String valueAuthorWritten = ""; + private List<SelectItem> suggestedAuthorsWritten = new ArrayList<SelectItem>(); + private Long valueAuthorSelectedId; + + // WITNESS -> is_exemplar_of -> TEXT -> was_created_by -> PERSON + private ListenerObject authorLo = new WitnessAuthorLO(PERSON, name_translit, this); + private String valueAuthor = ""; + + private boolean textUnknown = false; + private static String UNKNOWN = "UNKNOWN"; + + + // WITENSS -> was_copied_by -> PERSON + private ListenerObject copyistLo = new ListenerObject(PERSON, name_translit); + + // WITENSS -> was_copied_at -> PLACE + private ListenerObject copyPlaceLo = new ListenerObject(PLACE, name); + + // WITNESS -> xx -> PERSON + private ListenerObject patronageLo = new ListenerObject(PERSON, name_translit); + + //private List<SelectItem> citiesWithRepositories; + private boolean foundCodex; + + private boolean lockValueAuthor = false; + private boolean lockValueTitle = false; + + private boolean createCodexRendered = false; + private boolean renderShowAllCodexCandidates = false; + //private Entity witness_old; + + private String newIdentifier; + + //private IslamicCalendar islamicCalCopyDate; + private transient Calendar copyDate; + + private EntityList studiedByList; + private EntityList possibleExamplerOfList; + + public CurrentWitnessBean() { + super(); + this.entity = new Entity(Node.TYPE_ABOX, WITNESS, false); + setDefObjectClass(WITNESS); + + registerChecker(copyistLo.statusImage, "Copyist not valid"); + registerChecker(copyPlaceLo.statusImage, "Copyist not valid"); + registerChecker(patronageLo.statusImage,"Patron not valid"); + + } + + @Override + public void reset(){ + super.reset(); + this.entity = new Entity(Node.TYPE_ABOX, WITNESS, false); + this.studiedByList = new EntityList(PERSON, "name_translit", "Studied by"); + this.possibleExamplerOfList = new EntityList(TEXT, "full_title_translit", "Possible titles"); + + this.codicesOverviewRendered = false; + this.codicesAll = new ArrayList<CodexForList>(); + + this.titles_list = new ArrayList<SelectItem>(); + this.selectedTitleId = null; + this.selectTitleRendered = false; + this.selectPersonType = ""; + + this.persons_list = new ArrayList<SelectItem>(); + this.selectedPersonId = null; + this.selectPersonRendered = false; + this.restrictedByRole = true; + + if(titleLo != null) + this.titleLo.reset(); + + this.valueTitle = ""; + + // WITNESS -> has_title_written_as -> ALIAS + this.valueTextWritten = ""; + this.suggestedTitlesWritten = new ArrayList<SelectItem>(); + this.valueTitleSelectedId = null; + + // WITNESS -> has_author_written_as -> ALIAS + this.valueAuthorWritten = ""; + this.suggestedAuthorsWritten = new ArrayList<SelectItem>(); + this.valueAuthorSelectedId = null; + + // WITNESS -> is_exemplar_of -> TEXT -> was_created_by -> PERSON + if(this.authorLo != null) + this.authorLo.reset(); + this.valueAuthor = ""; + + // WITENSS -> was_copied_by -> PERSON + if(copyistLo != null) + this.copyistLo.reset(); + + // WITENSS -> was_copied_in -> PLACE + if(this.copyPlaceLo != null) + this.copyPlaceLo.reset(); + + // WITNESS -> xx -> PERSON + if(patronageLo != null) + this.patronageLo.reset(); + + //this.citiesWithRepositories = null; + this.foundCodex = false; + + this.lockValueAuthor = true; + this.lockValueTitle = true; + + this.createCodexRendered = false; + this.renderShowAllCodexCandidates = false; + + this.newIdentifier = ""; + + //this.islamicCalCopyDate = new IslamicCalendar(); + this.copyDate = new Calendar(); + } + + @Override + public String save() { + super.save(); + try { + + User user = getSessionUser(); + + if(!isCodexIdentifierSet(user.getEmail())){ + return "SAVE_ERROR"; + } + + if(!isWitnessConsistentBeforeSave()){ + return "SAVE_ERROR"; + } + + //checking if some LO is not OK. + CheckResults cr = getCheckResults(); + if (cr.hasErrors){ + getSessionBean().setErrorMessages(cr); + getSessionBean().setDisplayError(true); + this.setSelectedSaveAsNew(false); + return "SAVE_ERROR"; + } + + getAttributes().put("creation_date", this.copyDate.toJSONString()); + + this.entity = this.updateEntityAttributes(this.entity); + + // WITNESS -> is_part_of -> CODEX + this.entity.replaceSourceRelation(getCodexLo().entity, CODEX, is_part_of); + + // WITNESS -> is_exemplar_of -> TEXT -> was_created_by -> PERSON + //replaceSourceRelation(this.entity, this.author, PERSON, was_created_by); + + // WITENSS -> was_copied_by -> PERSON + this.entity.replaceSourceRelation(this.copyistLo.entity, PERSON, rel_was_copied_by); + + //WITENSS -> was_copied_in -> PLACE + this.entity.replaceSourceRelation(this.copyPlaceLo.entity, PLACE, "was_copied_in"); + + //REFERENCE -> is_reference_of -> WITNESS + //this.entity = this.prepareReferencesToSave(this.entity); + this.prepareEndNoteRefs2Save(); + + //WITNESS -> was studied by manyToMany -> PERSON + this.entity.removeAllSourceRelationsByName(rel_was_studied_by); + for(Entity target : this.studiedByList.getEntities()){ + Entity target0 = getWrapper().getEntityByIdWithContent(target.getId()); + Relation wasStudiedBy = new Relation(this.entity, target0, rel_was_studied_by); + } + + // WITNESS -> had_patron -> PERSON + this.entity.replaceSourceRelation(this.patronageLo.entity, PERSON, rel_had_patron); + + + // WITNESS -> is_exemplar_of -> TEXT + this.entity.replaceSourceRelation(this.titleLo.entity, TEXT, is_exemplar_of); + + this.entity.removeAllSourceRelationsByName(is_possible_exemplar_of); + this.entity.removeAllSourceRelations(rel_has_title_written_as, ALIAS); + this.entity.removeAllSourceRelations(rel_has_author_written_as, ALIAS); + + if(textUnknown){ + for(Entity target : this.possibleExamplerOfList.getEntities()){ + Entity target0 = getWrapper().getEntityByIdWithContent(target.getId()); + Relation tmp = new Relation(this.entity, target0, is_possible_exemplar_of); + } + }else{ + this.saveIndirectedAliases(); + } + + // WITNESS -> is_part_of_codex + if(this.isSelectedSaveAsNew()){ + this.entity = getWrapper().saveEntityAsNew(this.entity, user.getEmail()); + }else{ + this.entity = getWrapper().saveEntity(this.entity, user.getEmail()); + } + this.setEntity(this.entity); + + logger.info("Entity saved - Time = " + (System.currentTimeMillis() - start) + ", " + entity); + this.printSuccessSavingEntity(); + + this.setSelectedSaveAsNew(false); + } catch (Exception e) { + logger.error(e.getMessage(), e); + e.printStackTrace(); + this.printInternalError(e); + } + + saveEnd(); + return PAGE_EDITOR; + } + + private void saveIndirectedAliases() throws Exception{ + + User user = getSessionUser(); + + //WITNESS -> has_title_written_as -> ALIAS + if(StringUtils.isNotEmpty(valueTextWritten)){ + Entity alias = null; + if(this.suggestedTitlesWritten != null){ + for(SelectItem item : this.suggestedTitlesWritten){ + Long id = (Long)item.getValue(); + if(id != null){ + Entity candidate = getWrapper().getEntityById(id); + if(candidate != null && valueTextWritten.equals(candidate.getOwnValue())){ + alias = candidate; + break; + } + } + } + } + + if(alias == null){ + alias = new Entity(Node.TYPE_ABOX, ALIAS, false); + alias.addAttribute(new Attribute(ALIAS, "text", valueTextWritten)); + alias = getWrapper().saveEntity(alias, user.getEmail()); + Relation rel = new Relation(alias, this.titleLo.getEntity(), "is_alias_title_of"); + alias = getWrapper().saveEntity(alias, user.getEmail()); + } + if(alias.isLightweight()){ + alias = getWrapper().getEntityByIdWithContent(alias.getId()); + } + this.entity.replaceSourceRelation(alias, ALIAS, rel_has_title_written_as); + } + + + if(StringUtils.isNotEmpty(this.valueAuthorWritten)){ + Entity alias = null; + if(suggestedAuthorsWritten != null){ + for(SelectItem item : this.suggestedAuthorsWritten){ + Long id = (Long)item.getValue(); + if(id != null){ + Entity candidate = getWrapper().getEntityById(id); + if(candidate != null && valueAuthorWritten.equals(candidate.getOwnValue())){ + alias = candidate; + break; + } + } + } + } + + if(alias == null){ + alias = new Entity(Node.TYPE_ABOX, ALIAS, false); + alias.addAttribute(new Attribute(ALIAS, "text", valueAuthorWritten)); + alias = getWrapper().saveEntity(alias, user.getEmail()); + Relation rel = new Relation(alias, this.authorLo.getEntity(), "is_alias_name_of"); + alias = getWrapper().saveEntity(alias, user.getEmail()); + } + if(alias.isLightweight()){ + alias = getWrapper().getEntityByIdWithContent(alias.getId()); + } + this.entity.replaceSourceRelation(alias, ALIAS, rel_has_author_written_as); + } + } + + public String saveAsNewEntity() { + this.setSelectedSaveAsNew(true); + return save(); + } + + /* rich + public void patronageChangeListener(ValueChangeEvent event) { + //patronageLo = changeListener(event, patronageLo, PERSON, "name"); + patronageLo = changeValuePersonByRole(event, patronageLo, "Patron"); + + } + + public void copyistChangeListener(ValueChangeEvent event) { + copyistLo = changeValuePersonByRole(event, copyistLo, "Copyist"); + } + + public void copyPlacesChangeListener(ValueChangeEvent event) { + copyPlaceLo = changeListener(event, copyPlaceLo,"PLACE", "name"); + }*/ + + public void updateTitle(){ + + if(titleLo.entity != null && titleLo.entity.isPersistent()){ + + this.textUnknown = UNKNOWN.equals(titleLo.entity.getOwnValue()); + + List<Entity> targets = getWrapper().getTargetsForSourceRelation(titleLo.getEntity(), rel_was_created_by, PERSON, 1); + if(targets.size() > 0){ + this.authorLo.setEntityAndAttribute0(targets.get(0)); + + }else{ + this.authorLo.reset(); + /* rich + this.authorLo.setEntityAndAttribute(null, name_translit); + this.authorLo.statusImage.setStatus(StatusImage.STATUS_UNSET); + */ + + } + this.suggestedAuthorsWritten = getAuthorAliases(authorLo.entity); + this.suggestedTitlesWritten = getTitleAliases(titleLo.entity); + } + } + + public void updateAuthor(){ + + if(authorLo.getEntity() != null && authorLo.getEntity().isPersistent()){ + + this.titleLo.reset(); + + List <Entity> sources = getWrapper().getSourcesForTargetRelation(authorLo.getEntity(), rel_was_created_by, TEXT, -1); + + ArrayList<SelectItem> options = new ArrayList<SelectItem>(); + for (Entity title : sources){ + options.add(new SelectItem(title.getId(), title.getOwnValue() + " [" + title.getId() + "]")); + } + + titles_list = options; + this.suggestedAuthorsWritten = getAuthorAliases(authorLo.entity); + this.suggestedTitlesWritten = getTitleAliases(null); + } + } + + + private List<SelectItem> getTitleAliases(Entity title) { + List<SelectItem> items = new ArrayList<SelectItem>(); + this.valueTextWritten = null; + if(title != null && title.isPersistent()){ + items.add(new SelectItem(new Long(-1), "-- choose --")); + List<Entity> aliasTitleList = getWrapper().getSourcesForTargetRelation(title, is_alias_title_of, ALIAS, -1); + for(Entity alias : aliasTitleList){ + items.add(new SelectItem(alias.getId(), alias.getOwnValue())); + } + + List<Entity> primeAliasTitleList = getWrapper().getSourcesForTargetRelation(title, is_prime_alias_title_of, ALIAS, -1); + for(Entity alias : primeAliasTitleList){ + items.add(new SelectItem(alias.getId(), alias.getOwnValue())); + } + } + + return items; + } + private List<SelectItem> getAuthorAliases(Entity author) { + List<SelectItem> items = new ArrayList<SelectItem>(); + this.valueAuthorWritten = null; + if(author != null && author.isPersistent()){ + //items.add(new SelectItem(null, "-- choose --")); + List<Entity> aliasAuthorList = getWrapper().getSourcesForTargetRelation(author, is_alias_name_of, ALIAS, -1); + for(Entity alias : aliasAuthorList){ + items.add(new SelectItem(alias.getId(), alias.getOwnValue())); + } + + List<Entity> primeAliasAuthorList = getWrapper().getSourcesForTargetRelation(author, is_prime_alias_name_of, ALIAS, -1); + for(Entity alias : primeAliasAuthorList){ + items.add(new SelectItem(alias.getId(), alias.getOwnValue())); + } + } + return items; + + } + + @Override + public void setEntity(Entity witness) { + this.reset(); + this.entity = witness; + + if(this.entity.isPersistent()){ + if (witness.isLightweight()) { + witness = getWrapper().getEntityContent(witness); + } + + Attribute attCreationDate = this.entity.getAttributeByName("creation_date"); + if(attCreationDate != null && StringUtils.isNotEmpty(attCreationDate.getOwnValue())){ + this.copyDate = new Calendar(attCreationDate.getOwnValue()); + }else{ + this.copyDate = new Calendar(); + } + + // Loading attributes + this.loadAttributes(this.entity); + + // Loading the relations + // TODO loading target's relations + for (Relation rel : witness.getSourceRelations()) { + Entity target = null; + if (rel.getOwnValue().equals(is_exemplar_of)) { + + // WITNESS -> is_exemplar_of -> TEXT + target = getTargetRelation(rel); + titleLo.setEntityAndAttribute0(target); + this.updateTitle(); + + } else if (rel.getOwnValue().equals(is_possible_exemplar_of)) { + // WITNESS -> is_possible_exemplar_of -> TEXT + target = getTargetRelation(rel); + possibleExamplerOfList.add(target); + } else if (rel.getOwnValue().equals(rel_was_studied_by)) { + target = getTargetRelation(rel); + studiedByList.add(target); + } else if (rel.getOwnValue().equals(rel_was_copied_by)) { + // WITENSS -> was_copied_by -> PERSON + target = getTargetRelation(rel); + copyistLo.setEntityAndAttribute0(target); + } else if (rel.getOwnValue().equals("was_copied_in")) { + // WITENSS -> was_copied_in -> PLACE + target = getTargetRelation(rel); + copyPlaceLo.setEntityAndAttribute0(target); + } else if (rel.getOwnValue().equals(rel_had_patron)) { + // WITNESS -> had_patron -> PERSON + target = getTargetRelation(rel); + patronageLo.setEntityAndAttribute(target, name_translit); + } else if (rel.getOwnValue().equals(is_part_of)) { + // WITNESS -> had_patron -> PERSON + if(rel.getTargetObjectClass().equals(CODEX)){ + target = getTargetRelation(rel); + this.setCodex(target); + } + } else if (rel.getOwnValue().equals(rel_has_author_written_as)) { + //TODO this relation is no in the definitions + Entity target2 = getTargetRelation(rel); + Attribute alias = getTargetAttribute(target2, "alias"); + this.valueAuthorWritten = (alias != null) ? alias.getValue() : null; + + } else if (rel.getOwnValue().equals(rel_has_title_written_as)) { + //TODO this relation is no in the definitions + target = getTargetRelation(rel); + //this.textWritten = target; + Attribute alias = getTargetAttribute(target, "alias"); + this.valueTextWritten = (alias != null) ? alias.getValue() : null; + } + } + + //this.loadReferences(this.entity); + this.loadEndNoteRefs(); + + this.setCurrentId(this.entity.getId().toString()); + this.checkConsistencyFromCountryToCodex(); + + this.displayUrl = generateDisplayUrl(authorLo.entity, titleLo.entity, witness, getAppBean().getRoot()); + } + } + + /** + * Loads the given codex without reset of the variables, which could cause problem in CurrentWitness Class + * @param codex + */ + public void setCodex(Entity codex){ + this.getCodexLo().setEntityAndAttribute(codex, "identifier"); + + if(this.getCodexLo().entity != null && this.getCodexLo().entity.isPersistent()){ + + List<Entity> list = getWrapper().getTargetsForSourceRelation(codex, is_part_of, COLLECTION, 1); + if(list.size() > 0){ + this.setCollection(list.get(0)); + } + } + } + + public String getValueAuthor() { + return valueAuthor; + } + + public void setValueAuthor(String valueAuthor) { + if(!lockValueAuthor) + this.valueAuthor = valueAuthor; + this.lockValueAuthor = false; + } + + public void setValueTitle(String valueTitle) { + if(!lockValueTitle) + this.valueTitle = valueTitle; + this.lockValueTitle = false; + } + + public String getValueTitle() { + return valueTitle; + } + + public List<SelectItem> getTitles_list() { + return titles_list; + } + + public void setTitles_list(List<SelectItem> titlesList) { + titles_list = titlesList; + } + + public void setFoundCodex(boolean foundCodex) { + this.foundCodex = foundCodex; + } + + public boolean isFoundCodex() { + return foundCodex; + } + + public void listenerCreateTitleAlias(ValueChangeEvent event) { + this.valueTextWritten = (String)event.getNewValue(); + } + + public void listenerChooseTitleAlias(ValueChangeEvent event) { + if (event.getNewValue() != null) { + Long aliasId = (Long) event.getNewValue(); + if(aliasId != null){ + if(aliasId.equals(-1)){ + this.valueTextWritten = null; + }else{ + Entity alias = getWrapper().getEntityByIdWithContent(aliasId); + if(alias != null){ + this.valueTextWritten = alias.getOwnValue(); + } + } + } + } + } + + public void listenerCreateAuthorAlias(ValueChangeEvent event) { + this.valueAuthorWritten = (String)event.getNewValue(); + } + + public void listenerChooseAuthorAlias(ValueChangeEvent event) { + if (event.getNewValue() != null) { + Long aliasId = (Long) event.getNewValue(); + if(aliasId != null){ + if(aliasId.equals(-1)){ + this.valueAuthorWritten = null; + }else{ + Entity alias = getWrapper().getEntityByIdWithContent(aliasId); + if(alias != null){ + this.valueAuthorWritten = alias.getOwnValue(); + } + } + } + } + } + + @Override + public void identifierChangedListener(ValueChangeEvent event) { + super.identifierChangedListener(event); + + if (StringUtils.isEmpty(getCodexLo().attribute.getValue())){ + renderShowAllCodexCandidates = false; + this.checkConsistencyFromCountryToCodex(); + return; + } + + List<Entity> entities = getWrapper().getEntitiesByAtt(CODEX, getCodexLo().getAttName(), getCodexLo().attribute.getValue(), 10000, false); + + if (entities.size()>1){ + if ((getCollectionLo().attribute==null || getCollectionLo().getAttribute().getValue().equals("")) && + (getRepositoryLo().getAttribute()==null || getRepositoryLo().getAttribute().getValue().equals(""))){ + showAllCodexCandidates(entities); + renderShowAllCodexCandidates = true; + } + else + //renderShowAllCodexCandidates = false; + renderShowAllCodexCandidates = true; // i want to keep the selection field now + } + else + //renderShowAllCodexCandidates = false; + renderShowAllCodexCandidates = true; //i want to keep the selection field now + } + + public void searchInCurrentRepository(ActionEvent event) { + + ValueChangeEvent ne = new ValueChangeEvent((UIComponent) event + .getComponent(), "", getCollectionLo().getAttribute().getOwnValue()); + identifierChangedListener(ne); + + } + + /* rich + public String insertAuthorAction() { + return "insert"; + + }*/ + + public String showOtherTextsByAuthorAction() { + if (authorLo.entity == null || !authorLo.entity.isPersistent()) + return ""; + + List<SelectItem> options = new ArrayList<SelectItem>(); + List<Entity> titles = getWrapper().getSourcesForTargetRelation(authorLo.entity, "was_created_by", TEXT, -1); + for (Entity title: titles){ + options.add( + new SelectItem(title.getId(), title.getOwnValue() + " [" + title.getId() + "]")); + } + titles_list = options; + setSelectTitleRendered(true); + return ""; + } + + /** + * Gebe moegliche andere Codices aus. Das ist notwendig, weil nach dem jetzigen Stand der Daten ein Codex + * mehrfach im Datensatz auftachen kann. + * @return + */ + public String showAllCodexCandidates(List<Entity> entities){ + if (entities != null) { + for (Entity entity : entities) { + CodexForList entForList = getCodexData(entity); + codicesAll.add(entForList); + } + } + setCodicesOverviewRendered(true); + return ""; + } + + public String showAllTextsAction() { + titles_list = new ArrayList<SelectItem>(); + titles_list = getAppBean().getAllTexts(); + this.selectTitleRendered = true; + return ""; + } + + public void listenerSelectTitle(ActionEvent event){ + if(this.selectedTitleId != null){ + Entity title = getWrapper().getEntityById(this.selectedTitleId); + if(title != null){ + this.titleLo.setEntityAndAttribute0(title); + this.updateTitle(); + setSelectTitleRendered(false); + } + } + } + + public void listenerCancelPpSelectTitle(ActionEvent event){ + System.out.println("listenerCancelPpSelectTitle"); + this.selectTitleRendered = false; + } + + public void setSelectTitleRendered(Boolean selectTitleRendered) { + this.selectTitleRendered = selectTitleRendered; + } + + public Boolean getSelectTitleRendered() { + return selectTitleRendered; + } + + public List<SelectItem> getPersons_list() { + return persons_list; + } + + public void setPersons_list(List<SelectItem> personsList) { + persons_list = personsList; + } + + public Boolean getSelectPersonRendered() { + return selectPersonRendered; + } + + public void setSelectPersonRendered(Boolean selectPersonRendered) { + this.selectPersonRendered = selectPersonRendered; + } + + public Boolean getRestrictedByRole() { + return restrictedByRole; + } + + public void setRestrictedByRole(Boolean restrictedByRole) { + this.restrictedByRole = restrictedByRole; + } + + private void updatePersonList(){ + if (!this.restrictedByRole) + //persons_list = ((AllPersonsBean) this.getBean("AllPersons")) + // .getPersonsSelectItems(); + persons_list = getCache().getAllPersons(); + else { + //persons_list = ((AllPersonsBean) this.getBean("AllPersons")) + // .getPersonsSelectItemsByRole(this.selectPersonType); + persons_list = getCache().getPersonsByRole(selectPersonType); + } + } + + public String showAllCopyistsAction() { + this.setSelectPersonType("Copyist"); + this.updatePersonList(); + this.selectPersonRendered = true; + return ""; + } + + public String showAllPatronsAction() { + this.setSelectPersonType("Patron"); + this.updatePersonList(); + this.selectPersonRendered = true; + return ""; + } + + public String showAllAuthorsAction() { + this.setSelectPersonType("Author"); + this.updatePersonList(); + this.selectPersonRendered = true; + return ""; + } + + public void listenerCancelPpSelectAuthor(ActionEvent event){ + this.selectPersonRendered = false; + } + + public void listenerSelectPerson(ActionEvent event){ + String role = getSelectPersonType(); + if(this.selectedPersonId != null){ + Entity selectedPerson = getWrapper().getEntityByIdWithContent(selectedPersonId); + if(selectedPerson != null){ + if (role.equals("Copyist")) { + copyistLo.setEntityAndAttribute0(selectedPerson); + } else if (role.equals("Patron")) { + patronageLo.setEntityAndAttribute0(selectedPerson); + } else if (role.equals("Author")) { + authorLo.setEntityAndAttribute0(selectedPerson); + this.updateAuthor(); + } + setSelectPersonRendered(false); + } + } + } + + public void setSelectPersonType(String selectPersonType) { + this.selectPersonType = selectPersonType; + } + + public String getSelectPersonType() { + return selectPersonType; + } + + public void restrictedByRoleChange(ValueChangeEvent event) { + if (event.getNewValue().equals(event.getOldValue())) + return; + try{ + Boolean val = (Boolean) event.getNewValue(); + this.setRestrictedByRole(val); + this.updatePersonList(); + }catch(Exception ex){ + ex.printStackTrace(); + } + } + + public void listenerConvertCreationDate(ActionEvent event) { + /* + try{ + + String newDate = this.islamicCalCopyDate.islamic2Gregorian(); + String newJulianDate = this.islamicCalCopyDate.islamic2Julian(); + + getAttributes().put("creation_date_ce", newDate); + getAttributes().put("creation_date_julian", newJulianDate); + + }catch(Exception e){ + e.printStackTrace(); + addGeneralMsg("Error converting date!"); + addGeneralMsg("The islamic calendar begins on Friday, July 16th, 622 C.E. in the Julian calendar."); + addGeneralMsg("The date must be equals or bigger than yawm al-jum'a, 1.Muharram.1 (5.1.1.1)"); + } + */ + } + + + public void selectCodexFromOverviewAction(ActionEvent ae){ + /* rich + + HtmlCommandButton cp = (HtmlCommandButton)ae.getComponent(); + Long id = (Long) cp.getValue(); + //juc Entity ent = getOntology().getEntityById(id); + Entity ent = getWrapper().getEntityById(id); + this.getCodexLo().setEntityAndAttribute(ent, "identifier"); + //changeValueAttCodex(this.getCodexLo().getAttribute().getOwnValue()); + setCodicesOverviewRendered(false); + + */ + + + } + + public String closeCodicesOverview(){ + setCodicesOverviewRendered(false); + return "CLOSE"; + + } + + + private boolean isCodexIdentifierSet(String user){ + try { + + if(StatusImage.STATUS_OK.equals(getCodexLo().getStatus())){ + return true; + } + + String identifier = getNewIdentifier(); + + if(!StatusImage.STATUS_OK.equals(getCollectionLo().getStatus()) || + StringUtils.isEmpty(identifier)){ + //we can not save the witness + if(!StatusImage.STATUS_OK.equals(getCollectionLo().getStatus())){ + addErrorMsg("The Collection is not valid."); + } + if(StringUtils.isEmpty(identifier)){ + addErrorMsg("The Codex does not have an valid identifier."); + } + addErrorMsg("The Witness could not be saved."); + return false; + }else { + //two possibilities: + //1. there exist a codex with the same id + //2. there is no a codex with this id, it should be saved. + + if(StringUtils.isNotEmpty(identifier)){ + List<Entity> codexListOfCollection = + getWrapper().getSourcesForTargetRelation(getCollectionLo().getEntity(), + is_part_of, CODEX, -1); + for(Entity possibleCodex : codexListOfCollection){ + //juc Attribute att = getWrapper().getAttributeByName(possibleCodex, "identifier"); + Attribute att = getWrapper().getAttributeByName(possibleCodex.getId(), "identifier"); + if(att != null && identifier.equals(att.getValue())){ + getCodexLo().setEntityAndAttribute(possibleCodex, "identifier"); + return true; + } + } + } + } + + //if the Collection Status == OK && the Codex.identifier != null + Entity newCodex = new Entity(Node.TYPE_ABOX, CODEX, false); + newCodex.addAttribute(new Attribute("identifier", TEXT, identifier)); + getWrapper().saveEntity(newCodex, user); + Relation isPartOf = new Relation(newCodex, getCollectionLo().getEntity(), is_part_of); + getWrapper().saveRelationAsNode(isPartOf, user); + getCodexLo().setEntityAndAttribute(newCodex, "identifier"); + + } catch (Exception e) { + logger.error(e.getMessage(), e); + return false; + } + return true; + } + + public boolean isCreateCodexRendered() { + return createCodexRendered; + } + + public void setCreateCodexRendered(boolean createCodexRendered) { + this.createCodexRendered = createCodexRendered; + } + + @Override + public String loadCloneEntity(){ + this.setCodex(getCloneEntity()); + this.setRenderUnityCheckerDialog(false); + this.checkConsistencyFromCountryToCodex(); + return PAGE_EDITOR; + } + + public List<CodexForList> getCodicesAll() { + return codicesAll; + } + + public void setCodicesAll(List<CodexForList> codicesAll) { + this.codicesAll = codicesAll; + } + + public void setCodicesOverviewRendered(Boolean codicesOverviewRendered) { + this.codicesOverviewRendered = codicesOverviewRendered; + } + + public Boolean getCodicesOverviewRendered() { + return codicesOverviewRendered; + } + + /** + * Teste ob es Codices mit gleichem identifier gibt! + * @return + */ + public Boolean getRenderShowAllCodexCandidates(){ + return renderShowAllCodexCandidates; + } + + + + public List<SelectItem> getSuggestedTitlesWritten() { + return suggestedTitlesWritten; + } + + public void setSuggestedTitlesWritten(List<SelectItem> suggestedTitlesWritten) { + this.suggestedTitlesWritten = suggestedTitlesWritten; + } + + public List<SelectItem> getSuggestedAuthorsWritten() { + return suggestedAuthorsWritten; + } + + public void setSuggestedAuthorsWritten(List<SelectItem> suggestedAuthorsWritten) { + this.suggestedAuthorsWritten = suggestedAuthorsWritten; + } + + public void codexCodexChangeListener(ValueChangeEvent event) { + if (event.getNewValue() == null) { + return; + } + if (event.getNewValue().equals(event.getOldValue())) { + return; + } + this.getCodexLo().statusImage.setStatus(StatusImage.STATUS_UNSET); + this.getCodexLo().attribute.setValue(event.getNewValue().toString()); + } + public Long getValueTitleSelectedId() { + return valueTitleSelectedId; + } + + public void setValueTitleSelectedId(Long valueTitleSelectedId) { + this.valueTitleSelectedId = valueTitleSelectedId; + } + + public ListenerObject getCopyistLo() { + return copyistLo; + } + + public void setCopyistLo(ListenerObject copyistLo) { + this.copyistLo = copyistLo; + } + + public ListenerObject getCopyPlaceLo() { + return copyPlaceLo; + } + + public void setCopyPlaceLo(ListenerObject copyPlaceLo) { + this.copyPlaceLo = copyPlaceLo; + } + + public ListenerObject getPatronageLo() { + return patronageLo; + } + + public void setPatronageLo(ListenerObject patronageLo) { + this.patronageLo = patronageLo; + } + + public ListenerObject getTitleLo() { + return titleLo; + } + + public void setTitleLo(ListenerObject titleLo) { + this.titleLo = titleLo; + } + + public ListenerObject getAuthorLo() { + return authorLo; + } + + public String getNewIdentifier() { + return newIdentifier; + } + + public void setNewIdentifier(String newIdentifier) { + this.newIdentifier = newIdentifier; + } + + public EntityList getStudiedByList() { + return studiedByList; + } + + public Calendar getCopyDate() { + return copyDate; + } + + public void setCopyDate(Calendar copyDate) { + this.copyDate = copyDate; + } + + public void setStudiedByList(EntityList studiedByList) { + this.studiedByList = studiedByList; + } + public Long getValueAuthorSelectedId() { + return valueAuthorSelectedId; + } + + public void setValueAuthorSelectedId(Long valueAuthorSelectedId) { + this.valueAuthorSelectedId = valueAuthorSelectedId; + } + + public String getValueTextWritten() { + return valueTextWritten; + } + + public void setValueTextWritten(String valueTextWritten) { + //this.valueTextWritten = valueTextWritten; + } + + public String getValueAuthorWritten() { + return valueAuthorWritten; + } + + public void setValueAuthorWritten(String valueAuthorWritten) { + //this.valueAuthorWritten = valueAuthorWritten; + } + + public void setAuthorLo(ListenerObject authorLo) { + this.authorLo = authorLo; + } + + public Long getSelectedTitleId() { + return selectedTitleId; + } + + public void setSelectedTitleId(Long selectedTitleId) { + this.selectedTitleId = selectedTitleId; + } + public Long getSelectedPersonId() { + return selectedPersonId; + } + + public void setSelectedPersonId(Long selectedPersonId) { + this.selectedPersonId = selectedPersonId; + } + + public boolean isTextUnknown() { + return textUnknown; + } + + public void setTextUnknown(boolean textUnknown) { + this.textUnknown = textUnknown; + } + + public EntityList getPossibleExamplerOfList() { + return possibleExamplerOfList; + } + + public void setPossibleExamplerOfList(EntityList possibleExamplerOfList) { + this.possibleExamplerOfList = possibleExamplerOfList; + } + +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/DigiListBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,172 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.event.AjaxBehaviorEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.utils.templates.DigitalizationTemplate; + +public class DigiListBean extends AbstractBean{ + private static final long serialVersionUID = 8982550339613012125L; + private static Logger logger = Logger.getLogger(DigiListBean.class); + + + private static List<SelectItem> codexFilter; + + private static int ALL = 0; + private static int WITH_CODEX = 1; + private static int WITHOUT_CODEX = 2; + private int selectedFilter = ALL; + + static{ + codexFilter = new ArrayList<SelectItem>(); + codexFilter.add(new SelectItem(ALL, "All")); + codexFilter.add(new SelectItem(WITH_CODEX, "With codex")); + codexFilter.add(new SelectItem(WITHOUT_CODEX, "Without codex")); + } + + private List<DigitalizationTemplate> allList; + private List<DigitalizationTemplate> list; + private List<String> suggestionList; + private String filterTerm; + + public DigiListBean(WrapperService om){ + reset(om); + } + + + /* + public void listenerDigiFilter(ValueChangeEvent event){ + //System.out.println("listenerDigiFilter"); + //System.out.println(event.getNewValue()); + this.filterTerm = event.getNewValue() + ""; + filter(); + }*/ + + public void eventFilter(AjaxBehaviorEvent event){ + //System.out.println("AjaxBehaviorEvent: " + this.filterTerm); + if(StringUtils.isNotEmpty(filterTerm)){ + filter(); + }else{ + reset(getAppBean().getWrapper()); + } + } + + private void filter(){ + //System.out.println(this.allList.size()); + this.list = new ArrayList<DigitalizationTemplate>(); + this.suggestionList = new ArrayList<String>(); + + for(DigitalizationTemplate digi : this.allList){ + if(StringUtils.containsIgnoreCase(digi.getEntity().getOwnValue(), filterTerm)){ + addDigi(digi); + } + } + //System.out.println(this.list.size()); + Collections.sort(list); + } + + private void reset(WrapperService om){ + //System.out.println("Reset"); + list = new ArrayList<DigitalizationTemplate>(); + allList = new ArrayList<DigitalizationTemplate>(); + suggestionList = new ArrayList<String>(); + filterTerm = null; + + long start = System.currentTimeMillis(); + List<Entity> entList = om.getEntitiesByDef("DIGITALIZATION"); + for(Entity digi : entList){ + DigitalizationTemplate d = new DigitalizationTemplate(digi, om); + d.init(); + if(selectedFilter == ALL){ + //list.add(d); + this.addDigi(d); + }else if(selectedFilter == WITH_CODEX && d.isHasCodex()){ + //list.add(d); + this.addDigi(d); + }else if(selectedFilter == WITHOUT_CODEX && !d.isHasCodex()){ + //list.add(d); + this.addDigi(d); + } + } + Collections.sort(list); + this.allList = new ArrayList<DigitalizationTemplate>(list); + + long diff = System.currentTimeMillis() - start; + logger.info("DigitalizationList Generation - Time[ms] = " + diff); + } + + private void addDigi(DigitalizationTemplate d){ + this.list.add(d); + if(!suggestionList.contains(d.getEntity().getOwnValue())){ + this.suggestionList.add(d.getEntity().getOwnValue()); + } + } + + public int getListSize(){ + return this.list.size(); + } + + public void listenerRefresh(ActionEvent event){ + System.out.println("listenerRefresh"); + reset(getAppBean().getWrapper()); + } + + public String actionEditDigi(){ + DigitalizationTemplate digi = (DigitalizationTemplate)getRequestBean("digi"); + if(digi != null){ + getSessionBean().editEntity(digi.getEntity()); + return "entry_edit_entity"; + } + return null; + } + + public String actionEditWitness(){ + Entity entity = (Entity)getRequestBean("witness"); + if(entity != null){ + getSessionBean().editEntity(entity); + return "entry_edit_entity"; + } + return null; + } + + public List<DigitalizationTemplate> getList() { + return list; + } + + public int getSelectedFilter() { + return selectedFilter; + } + + public void setSelectedFilter(int selectedFilter) { + this.selectedFilter = selectedFilter; + } + + public List<SelectItem> getCodexFilter(){ + return codexFilter; + } + + + public String getFilterTerm() { + return filterTerm; + } + + + public void setFilterTerm(String filterTerm) { + this.filterTerm = filterTerm; + } + + public List<String> getSuggesstionList(){ + return this.suggestionList; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/SessionBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,1131 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.faces.context.ExternalContext; +import javax.faces.context.FacesContext; +import javax.faces.event.ActionEvent; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.security.SecurityService; +import org.mpi.openmind.security.bo.User; +import org.mpiwg.itgroup.escidoc.utils.ESciDocItemDataTable; +import org.mpiwg.itgroup.escidoc.web.ESciDocItemForm; +import org.mpiwg.itgroup.geonames.GeonameForm; +import org.richfaces.event.ItemChangeEvent; + +import de.mpiwg.itgroup.ismi.admin.AdminBean; +import de.mpiwg.itgroup.ismi.browse.EntityDetailsBean; +import de.mpiwg.itgroup.ismi.defs.DefinitionForm; +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean.CheckResults; +import de.mpiwg.itgroup.ismi.event.beans.CopyEvent; +import de.mpiwg.itgroup.ismi.event.beans.StudyEvent; +import de.mpiwg.itgroup.ismi.event.beans.TransferEvent; +import de.mpiwg.itgroup.ismi.merge.GeneralMerge; +import de.mpiwg.itgroup.ismi.publicView.DynamicPageEditor; +import de.mpiwg.itgroup.ismi.publicView.PublicCodexBean; +import de.mpiwg.itgroup.ismi.publicView.PublicCodexList; +import de.mpiwg.itgroup.ismi.publicView.PublicCodexView; +import de.mpiwg.itgroup.ismi.publicView.pages.DynamicPage; +import de.mpiwg.itgroup.ismi.search.beans.AdvancedSearchBean; +import de.mpiwg.itgroup.ismi.search.beans.DisplayAuthorBean; +import de.mpiwg.itgroup.ismi.search.beans.DisplayTitleBean; +import de.mpiwg.itgroup.ismi.util.guiComponents.Calendar; +import de.mpiwg.itgroup.ismi.util.guiComponents.EntityList; + +public class SessionBean extends AbstractBean implements Serializable{ + + private static Logger logger = Logger.getLogger(SessionBean.class); + + private DefinitionForm defForm = new DefinitionForm(); + private StudyEvent studyEventForm = new StudyEvent(); + private CopyEvent copyEventForm = new CopyEvent(); + private TransferEvent transferEventForm = new TransferEvent(); + private transient AdvancedSearchBean advancedSearch = new AdvancedSearchBean(); + private GeonameForm geoForm = new GeonameForm(); + + private EntityDetailsBean entDetailsForm = new EntityDetailsBean(); + + + private DisplayAuthorBean displayAuthor = new DisplayAuthorBean(); + private DisplayTitleBean displayTitle = new DisplayTitleBean(); + + private ESciDocItemForm eSciDocForm = new ESciDocItemForm(); + + private ESciDocItemDataTable refDataTable = new ESciDocItemDataTable(null); + + private DynamicPageEditor pageEditor = null; + + + private Calendar currentCalendar = null; + private EntityList currentEntListForCalendar = null; + private Long currentEntIdForCalendar; + + private boolean displayLoginDialog = false; + + private DigiListBean digiList; + + //public + private DynamicPage dynamicPage; + private PublicCodexView publicCodexView; + private PublicCodexBean publicCodexBean; + + public void editCalendar(Calendar cal, EntityList list, Long entId){ + this.currentCalendar = cal; + this.currentEntListForCalendar = list; + this.currentEntIdForCalendar = entId; + } + + public void listenerSaveEditionCalendar(ActionEvent event){ + if(this.currentEntListForCalendar != null && this.currentEntIdForCalendar != null){ + this.currentEntListForCalendar.getCalendarMap().put(currentEntIdForCalendar, currentCalendar); + this.currentCalendar = null; + this.currentEntListForCalendar = null; + this.currentEntIdForCalendar = null; + } + } + + + public static String PAGE_ENTITY_REPOSITORY = "entity_repository"; + public static String PAGE_ENTITY_DETAILS = "entity_details"; + public static String PAGE_ENTRY = "entry_edit_entity"; + public static String PAGE_EVENT_FORM = "event_form"; + public static String PAGE_SIMPLE_SEARCH = "simple_search"; + public static String PAGE_PUBLIC_CODICES = "public_codices"; + public static String PAGE_DISPLAY_TITLE = "display_title"; + public static String PAGE_DISPLAY_AUTHOR = "display_author"; + public static String PAGE_GENERAL_MERGE = "general_merge"; + public static String PAGE_GEO_FORM = "geo_form"; + public static String PAGE_ADMIN = "admin"; + public static String PAGE_PROFILE = "profile"; + public static String PAGE_DEF_EDITOR = "defEditor"; + + private User user = null; + private String username = ""; + private String password = ""; + + //private Entity currentEntity; + + private GeneralMerge generalMerge; + + //private String last_action; + //private Date time_of_lastAction; + + private String remoteAddr; + + private static final long serialVersionUID = 1L; + + //Entities tabs + public static String WITNESS_TAB = "Witness"; + public static String CODEX_TAB = "Codex"; + public static String COLLECTION_TAB = "Collection"; + public static String REPOSITORY_TAB = "Repository"; + public static String CITY_TAB = "Place"; + public static String TEXT_TAB = "Text"; + public static String PERSON_TAB = "Person"; + public static String ALIAS_TAB = "Alias"; + public static String SUBJECT_TAB = "Subject"; + public static String ROLE_TAB = "Role"; + public static String DIGI_TAB = "Digi"; + + //Events tabs + public static String WITNESS_STUDY_EVENT_TAB = "Study"; + public static String COPY_EVENT_TAB = "Copy"; + public static String TRANSFER_EVENT_TAB = "Transfer"; + + private String selectedTab = WITNESS_TAB; + private String selectedEventTab = WITNESS_STUDY_EVENT_TAB; + private String selectedAdvancedSearchTab = "01"; + + + private Long editFormCurrentEntId; + + private boolean displayError = false; + private ArrayList<String> errorMessages; + + public String getOCByTabIndex(){ + if(selectedTab != null){ + if(selectedTab.equals(WITNESS_TAB)){ + return AbstractISMIBean.WITNESS; + }else if(selectedTab.equals(CODEX_TAB)){ + return AbstractISMIBean.CODEX; + }else if(selectedTab.equals(COLLECTION_TAB)){ + return AbstractISMIBean.COLLECTION; + }else if(selectedTab.equals(REPOSITORY_TAB)){ + return AbstractISMIBean.REPOSITORY; + }else if(selectedTab.equals(CITY_TAB)){ + return AbstractISMIBean.PLACE; + }else if(selectedTab.equals(TEXT_TAB)){ + return AbstractISMIBean.TEXT; + }else if(selectedTab.equals(PERSON_TAB)){ + return AbstractISMIBean.PERSON; + }else if(selectedTab.equals(ALIAS_TAB)){ + return AbstractISMIBean.ALIAS; + }else if(selectedTab.equals(SUBJECT_TAB)){ + return AbstractISMIBean.SUBJECT; + }else if(selectedTab.equals(ROLE_TAB)){ + return AbstractISMIBean.ROLE; + }else if(selectedTab.equals(DIGI_TAB)){ + return AbstractISMIBean.DIGITALIZATION; + } + } + return null; + } + + public void listenerOpenESciDocForm(ActionEvent event){ + this.refDataTable.open(); + } + + //************************************ + //************************************ + //************************************ + public SessionBean() { + if(StringUtils.isBlank(this.remoteAddr)){ + this.getRemoteAddr(); + } + logger.info(" [remoteAddr=" + remoteAddr + "]"); + } + + private void autoLogin(){ + /* + this.username = "jurzua@mpiwg-berlin.mpg.de"; + this.password = "221082"; + this.login(); + */ + } + + public void getRemoteAddr(){ + try{ + HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); + this.remoteAddr = httpServletRequest.getRemoteAddr(); + }catch (Exception ex) {} + } + + + public void listenerLogin(ActionEvent event) { + this.login(); + } + + public String actionLogin(){ + this.login(); + return new String(); + } + + public void listenerDisplayLoginDialog(ActionEvent event) { + if(user == null){ + this.displayLoginDialog = true; + }else{ + this.displayLoginDialog = false; + } + } + + public String actionLoginCancel(){ + this.displayLoginDialog = false; + return PAGE_SIMPLE_SEARCH; + } + + private void login(){ + user = null; + // this.loginMsg = ""; + + if (StringUtils.isNotEmpty(username) + && StringUtils.isNotEmpty(password)) { + user = getSecurityService().getUserByPassword(username, password); + } + + if (user == null) { + addErrorMsg("The system does not find the account!"); + this.displayLoginDialog = false; + } else { + if(StringUtils.isBlank(this.remoteAddr)){ + this.getRemoteAddr(); + } + logger.info("login " + username + " [remoteAddr=" + remoteAddr + "]"); + this.setUser(user); + this.generalMerge = new GeneralMerge(); + this.defForm = new DefinitionForm(); + // refresh the editor of Dirk + addSessionBean("CurrentWitness", new CurrentWitnessBean()); + addSessionBean("CurrentCodex", new CurrentCodexBean()); + addSessionBean("CurrentText", new CurrentTextBean()); + addSessionBean("CurrentPerson", new CurrentPersonBean()); + addSessionBean("CurrentAlias", new CurrentAliasBean()); + addSessionBean("CurrentCollection", new CurrentCollectionBean()); + addSessionBean("CurrentRepository", new CurrentRepositoryBean()); + addSessionBean("CurrentCity", new CurrentCityBean()); + addSessionBean("CurrentDigi", new CurrentDigitalizationBean()); + editFormCurrentEntId = null; + this.displayLoginDialog = false; + } + } + + public String logout() { + if(StringUtils.isBlank(this.remoteAddr)){ + this.getRemoteAddr(); + } + logger.info("logout " + username + " [remoteAddr=" + remoteAddr + "]"); + this.username = ""; + this.password = ""; + this.user = null; + this.generalMerge = null; + this.defForm = null; + return PAGE_PUBLIC_CODICES; + } + + public boolean isCanDelete() { + return isAdmin(); + } + + public boolean isCanMerge() { + if (getUser() != null) { + String role = getUser().getRole(); + if (StringUtils.isNotEmpty(role)) { + if (AdminBean.Administrator.equals(role) + || AdminBean.Researcher.equals(role)) { + return true; + } + } + } + return false; + } + + public boolean isCanCreate() { + if (getUser() != null) { + String role = getUser().getRole(); + if (StringUtils.isNotEmpty(role)) { + if (AdminBean.Administrator.equals(role) + || AdminBean.Researcher.equals(role) + || AdminBean.Student.equals(role)) { + return true; + } + } + } + return false; + } + + public boolean isCanEdit() { + if (getUser() != null) { + String role = getUser().getRole(); + if (StringUtils.isNotEmpty(role)) { + if (AdminBean.Administrator.equals(role) + || AdminBean.Researcher.equals(role)) { + return true; + } + } + } + return false; + } + + public boolean isAdmin() { + if (getUser() != null) { + String role = getUser().getRole(); + if (StringUtils.isNotEmpty(role)) { + if (AdminBean.Administrator.equals(role)) { + return true; + } + } + } + return false; + } + + private List<String> generalMsgList = new ArrayList<String>(); + private List<String> errorMsgList = new ArrayList<String>(); + + public List<String> getErrorMsgList() { + return errorMsgList; + } + + public void setErrorMsgList(List<String> errorMsgList) { + this.errorMsgList = errorMsgList; + } + + public List<String> getGeneralMsgList() { + return generalMsgList; + } + + public void setGeneralMsgList(List<String> generalMsgList) { + this.generalMsgList = generalMsgList; + } + + public void addErrorMsg(String msg) { + if (this.errorMsgList == null) + this.errorMsgList = new ArrayList<String>(); + if (StringUtils.isNotEmpty(msg)) { + this.errorMsgList.add(msg); + } + } + + public void addGeneralMsg(String msg) { + if (this.generalMsgList == null) + this.generalMsgList = new ArrayList<String>(); + if (StringUtils.isNotEmpty(msg)) { + this.generalMsgList.add(msg); + } + } + + public void actionCloseErrorMsgDialog(ActionEvent event) { + this.errorMsgList = new ArrayList<String>(); + } + + public void actionCloseGeneralMsgDialog(ActionEvent event) { + this.generalMsgList = new ArrayList<String>(); + } + + protected SecurityService getSecurityService() { + return getAppBean().getSecurityService(); + } + + public void setSelectedTab(String tab) { + this.selectedTab = tab; + } + + public String closeErrorWindowAction() { + setDisplayError(false); + return "close_error"; + } + + public void editEntity(Long id) { + Entity entity = getWrapper().getEntityById(id); + this.editEntity(entity); + } + + public void editEntity(String id) { + try{ + Long entityId = Long.parseLong(id); + this.editEntity(entityId); + }catch (Exception e) { + e.printStackTrace(); + } + } + + /* + public void setPlaceInGeoForm(String id){ + try { + Long placeId = new Long(id); + Entity place = getWrapper().getEntityById(placeId); + if(place != null){ + this.geoForm.loadPlace(place); + } + } catch (Exception e) { + e.printStackTrace(); + } + }*/ + + + public void editEntity(Entity entity) { + logger.info("[" + this.getUsername() + "] Edit Entity= " + entity); + + entity = getWrapper().getEntityContent(entity); + + this.editFormCurrentEntId = entity.getId(); + if (entity.getObjectClass().equals("WITNESS")) { + this.editWitness(entity); + selectedTab = WITNESS_TAB; + } else if (entity.getObjectClass().equals("TEXT")) { + this.editText(entity); + selectedTab = TEXT_TAB; + } else if (entity.getObjectClass().equals("REPOSITORY")) { + this.editRepository(entity); + selectedTab = REPOSITORY_TAB; + } else if (entity.getObjectClass().equals("PERSON")) { + this.editPerson(entity); + selectedTab = PERSON_TAB; + } else if (entity.getObjectClass().equals("COLLECTION")) { + this.editCollection(entity); + selectedTab = COLLECTION_TAB; + } else if (entity.getObjectClass().equals("CODEX")) { + this.editCodex(entity); + selectedTab = CODEX_TAB; + } else if (entity.getObjectClass().equals("PLACE")) { + this.editPlace(entity); + selectedTab = CITY_TAB; + } else if (entity.getObjectClass().equals("ALIAS")) { + this.editAlias(entity); + selectedTab = ALIAS_TAB; + } else if (entity.getObjectClass().equals("SUBJECT")) { + this.editSubject(entity); + selectedTab = SUBJECT_TAB; + } else if (entity.getObjectClass().equals("ROLE")) { + this.editRole(entity); + selectedTab = ROLE_TAB; + } else if (entity.getObjectClass().equals("DIGITALIZATION")) { + this.editDigi(entity); + selectedTab = DIGI_TAB; + } else if (entity.getObjectClass().equals(StudyEvent.OC)) { + this.editWitnessStudyEvent(entity); + selectedEventTab = WITNESS_STUDY_EVENT_TAB; + } else if (entity.getObjectClass().equals(CopyEvent.OC)) { + this.editCopyEvent(entity); + selectedEventTab = COPY_EVENT_TAB; + } else if (entity.getObjectClass().equals(TransferEvent.OC)) { + this.editTransferEvent(entity); + selectedEventTab = TRANSFER_EVENT_TAB; + } else { + addErrorMsg("Form not implemented for these entities [" + entity.getObjectClass() + "]"); + } + } + + //*************************** + //*************************** + //*************************** + //*************************** + //*************************** + private void editText(Entity text) { + CurrentTextBean bean = (CurrentTextBean)getSessionBean(ApplicationBean.CURRENT_TEXT); + if(bean == null){ + bean = new CurrentTextBean(); + addSessionBean(ApplicationBean.CURRENT_TEXT, bean); + } + try { + bean.setEntity(text); + } catch (Exception e) { + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + private void editRepository(Entity repository) { + CurrentRepositoryBean bean = (CurrentRepositoryBean)getSessionBean(ApplicationBean.CURRENT_REPOSITORY); + if(bean == null){ + bean = new CurrentRepositoryBean(); + addSessionBean(ApplicationBean.CURRENT_REPOSITORY, bean); + } + try { + bean.setEntity(repository); + } catch (Exception e) { + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + private void editPerson(Entity person) { + CurrentPersonBean bean = (CurrentPersonBean)getSessionBean(ApplicationBean.CURRENT_PERSON); + if(bean == null){ + bean = new CurrentPersonBean(); + addSessionBean(ApplicationBean.CURRENT_PERSON, bean); + } + try { + bean.setEntity(person); + } catch (Exception e) { + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + private void editCollection(Entity collection) { + CurrentCollectionBean bean = (CurrentCollectionBean) getSessionBean(ApplicationBean.CURRENT_COLLECTION); + if (bean == null) { + bean = new CurrentCollectionBean(); + addSessionBean(ApplicationBean.CURRENT_COLLECTION, bean); + } + try { + bean.setEntity(collection); + } catch (Exception e) { + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + private void editCodex(Entity codex) { + CurrentCodexBean bean = (CurrentCodexBean) getSessionBean(ApplicationBean.CURRENT_CODEX); + if (bean == null) { + bean = new CurrentCodexBean(); + addSessionBean(ApplicationBean.CURRENT_CODEX, bean); + } + try { + bean.setEntity(codex); + } catch (Exception e) { + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + private void editPlace(Entity place) { + CurrentCityBean bean = (CurrentCityBean) getSessionBean(ApplicationBean.CURRENT_CITY); + if (bean == null) { + bean = new CurrentCityBean(); + addSessionBean(ApplicationBean.CURRENT_CITY, bean); + } + try { + bean.setEntity(place); + } catch (Exception e) { + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + private void editAlias(Entity alias) { + CurrentAliasBean bean = (CurrentAliasBean) getSessionBean(ApplicationBean.CURRENT_ALIAS); + if (bean == null) { + bean = new CurrentAliasBean(); + addSessionBean(ApplicationBean.CURRENT_ALIAS, bean); + } + try { + bean.setEntity(alias); + } catch (Exception e) { + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + private void editSubject(Entity subject) { + CurrentSubjectBean bean = (CurrentSubjectBean) getSessionBean(ApplicationBean.CURRENT_SUBJECT); + if (bean == null) { + bean = new CurrentSubjectBean(); + addSessionBean(ApplicationBean.CURRENT_SUBJECT, bean); + } + try { + bean.setEntity(subject); + } catch (Exception e) { + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + private void editRole(Entity role) { + CurrentRoleBean bean = (CurrentRoleBean) getSessionBean(ApplicationBean.CURRENT_ROLE); + if (bean == null) { + bean = new CurrentRoleBean(); + addSessionBean(ApplicationBean.CURRENT_ROLE, bean); + } + try { + bean.setEntity(role); + } catch (Exception e) { + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + + private void editDigi(Entity digi) { + CurrentDigitalizationBean bean = (CurrentDigitalizationBean) getSessionBean(ApplicationBean.CURRENT_DIGI); + if (bean == null) { + bean = new CurrentDigitalizationBean(); + addSessionBean(ApplicationBean.CURRENT_DIGI, bean); + } + try { + bean.setEntity(digi); + } catch (Exception e) { + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + + + private void editWitness(Entity witness) { + CurrentWitnessBean bean = (CurrentWitnessBean) getSessionBean(ApplicationBean.CURRENT_WITNESS); + if (bean == null) { + bean = new CurrentWitnessBean(); + addSessionBean(ApplicationBean.CURRENT_WITNESS, bean); + } + try { + bean.setEntity(witness); + } catch (Exception e) { + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + private void editWitnessStudyEvent(Entity event){ + this.studyEventForm = new StudyEvent(event); + } + + public void listenerCreateStudyEvent(ActionEvent event){ + this.studyEventForm = new StudyEvent(); + } + + private void editCopyEvent(Entity event){ + this.copyEventForm = new CopyEvent(event); + } + + public void listenerCreateCopyEvent(ActionEvent event){ + this.copyEventForm = new CopyEvent(); + } + + private void editTransferEvent(Entity event){ + this.transferEventForm = new TransferEvent(event); + } + + public void listenerCreateTransferEvent(ActionEvent event){ + this.transferEventForm = new TransferEvent(); + } + + + public Long getEditFormCurrentEntId() { + return editFormCurrentEntId; + } + + public void setEditFormCurrentEntId(Long editFormCurrentEntId) { + this.editFormCurrentEntId = editFormCurrentEntId; + } + + + public void updateCurrent(ItemChangeEvent event) { + System.out.println(event.getNewItemName()); + } + + public void listenerEntityTabChange(ItemChangeEvent event) { + String url = "?formIndex=" + this.selectedTab; + this.redirect(null, url); + } + + public void listenerEventTabChange(ItemChangeEvent event) { + String url = "?formIndex=" + this.selectedEventTab; + this.redirect(null, url); + } + + public void listenerAdvancedSearchTabChange(ItemChangeEvent event) { + String url = "?searchForm=" + this.selectedAdvancedSearchTab; + this.redirect(null, url); + } + + protected void redirect(String redirectPath, String parameters){ + FacesContext fc = FacesContext.getCurrentInstance(); + ExternalContext ec = fc.getExternalContext(); + String contextPath = ec.getRequestContextPath(); + if(StringUtils.isEmpty(redirectPath)){ + redirectPath = ec.getRequestServletPath(); + } + try { + ec.redirect(ec.encodeActionURL(contextPath + redirectPath + parameters)); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + public Entity getDefinition(Entity assertion) { + return getWrapper().getDefinition(assertion.getObjectClass()); + } + + public String toProfile(){ + return PAGE_PROFILE; + } + + public String toSimpleSearch() { + return PAGE_SIMPLE_SEARCH; + } + + public String toDefinitionEditor(){ + if(this.defForm != null){ + this.defForm.loadDefinitions(); + return PAGE_DEF_EDITOR; + } + return ""; + } + + public String toGeoForm(){ + this.geoForm.loadPlaces(null); + return PAGE_GEO_FORM; + } + + public String displayByAttribute() { + Attribute att = (Attribute) getRequestBean("attribute"); + logger.info(att); + if (att != null) { + Entity ent = getWrapper().getEntityById(att.getSourceId()); + if (ent.getObjectClass().equals("TEXT")) { + this.displayTitle.showTitle(ent.getId()); + return PAGE_DISPLAY_TITLE; + } else if (ent.getObjectClass().equals("PERSON")) { + this.displayAuthor.showAuthor(ent.getId()); + return PAGE_DISPLAY_AUTHOR; + } + } + + return ""; + } + + public void displayAuthorSetPerson(String personId){ + try{ + Long id = new Long(personId); + Entity person = getWrapper().getEntityById(id); + if(person != null){ + person = getWrapper().getEntityContent(person); + if (person.getObjectClass().equals("PERSON")) { + this.displayAuthor.showAuthor(person.getId()); + } + } + }catch(Exception e){ + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + public void displayAuthorSetTitle(String textId){ + try{ + Long id = new Long(textId); + this.displayAuthor.showTitle(id); + }catch(Exception e){ + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + public void displayAuthorSetWitness(String witnessId){ + try{ + Long id = new Long(witnessId); + this.displayAuthor.showWitness(id); + }catch(Exception e){ + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + public void displayTitleSetTitle(String textId){ + try{ + Long id = new Long(textId); + Entity ent = getWrapper().getEntityById(id); + if(ent != null){ + ent = getWrapper().getEntityContent(ent); + if (ent.getObjectClass().equals("TEXT")) { + //this.editText(ent); + this.displayTitle.showTitle(id); + } + } + }catch(Exception e){ + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + public void displayTitleSetWitness(String witnessId){ + try{ + Long id = new Long(witnessId); + this.displayTitle.showWitness(id); + + }catch(Exception e){ + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + public void displayTitleFromWitness(String witnessId){ + try{ + Long longWitnessId = new Long(witnessId); + + List<Entity> textList = + getWrapper().getTargetsForSourceRelation(longWitnessId, "is_exemplar_of", "TEXT", 1); + if(textList.size() > 0){ + this.displayTitle.showTitle(textList.get(0).getId()); + this.displayTitle.showWitness(longWitnessId); + } + + }catch(Exception e){ + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + public void displayAuthorFromWitness(String witnessId){ + try{ + Long longWitnessId = new Long(witnessId); + + List<Entity> titleList = + getWrapper().getTargetsForSourceRelation(longWitnessId, "is_exemplar_of", "TEXT", 1); + if(titleList.size() > 0){ + Entity title = titleList.get(0); + List<Entity> authorList = + getWrapper().getTargetsForSourceRelation(title.getId(), "was_created_by", "PERSON", 1); + if(authorList.size() > 0){ + this.displayAuthor.showAuthor(authorList.get(0).getId()); + this.displayAuthor.showTitle(title.getId()); + this.displayAuthor.showWitness(longWitnessId); + } + } + + }catch(Exception e){ + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + public void displayAuthorFromTitles(String titleId){ + try{ + Long longTitleId = new Long(titleId); + + List<Entity> authorList = + getWrapper().getTargetsForSourceRelation(longTitleId, "was_created_by", "PERSON", 1); + if(authorList.size() > 0){ + this.displayAuthor.showAuthor(authorList.get(0).getId()); + this.displayAuthor.showTitle(longTitleId); + } + + }catch(Exception e){ + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + + public String editByAttribute() { + Attribute att = (Attribute) getRequestBean("attribute"); + logger.info(att); + if (att != null) { + Entity ent = getWrapper().getEntityById(att.getSourceId()); + if (ent != null) { + this.editEntity(ent); + return PAGE_ENTRY; + } + } + + return ""; + } + + public void setIdEntityDetails(String id){ + try{ + Long idLong = new Long(id); + Entity e = getWrapper().getEntityById(idLong); + this.entDetailsForm.setEntity(e); + }catch(Exception e){ + logger.error("[U=" + this.getUsername() + "]" + e.getMessage(), e); + } + } + + public String editByEntity() { + Entity ent = (Entity) getRequestBean("entity"); + if (ent != null) { + if (ent != null) { + this.editEntity(ent); + return PAGE_ENTRY; + } + } + return ""; + } + + public void setErrorMessages(CheckResults cr) { + + errorMessages = new ArrayList<String>(); + for (String err : cr.errors) { + errorMessages.add(err); + } + + } + + public void setDisplayError(boolean b) { + displayError = b; + + } + + public boolean getDisplayError() { + return displayError; + } + + public ArrayList<String> getErrorMessages() { + return errorMessages; + } + + public User getUser() { + if(user == null){ + autoLogin(); + } + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public GeneralMerge getGeneralMerge() { + return generalMerge; + } + + public void setGeneralMerge(GeneralMerge generalMerge) { + this.generalMerge = generalMerge; + } + + public DefinitionForm getDefForm() { + return defForm; + } + + public void setDefForm(DefinitionForm defForm) { + this.defForm = defForm; + } + + public StudyEvent getStudyEventForm() { + return studyEventForm; + } + + public void setStudyEventForm(StudyEvent studyEventForm) { + this.studyEventForm = studyEventForm; + } + + public CopyEvent getCopyEventForm() { + return copyEventForm; + } + + public void setCopyEventForm(CopyEvent copyEventForm) { + this.copyEventForm = copyEventForm; + } + + public TransferEvent getTransferEventForm() { + return transferEventForm; + } + + public void setTransferEventForm(TransferEvent transferEventForm) { + this.transferEventForm = transferEventForm; + } + + public String getSelectedEventTab() { + return selectedEventTab; + } + + public void setSelectedEventTab(String selectedEventTab) { + this.selectedEventTab = selectedEventTab; + } + + public AdvancedSearchBean getAdvancedSearch() { + return advancedSearch; + } + + public void setAdvancedSearch(AdvancedSearchBean advancedSearch) { + this.advancedSearch = advancedSearch; + } + + public DisplayAuthorBean getDisplayAuthor() { + return displayAuthor; + } + + public void setDisplayAuthor(DisplayAuthorBean displayAuthor) { + this.displayAuthor = displayAuthor; + } + + public DisplayTitleBean getDisplayTitle() { + return displayTitle; + } + + public void setDisplayTitle(DisplayTitleBean displayTitle) { + this.displayTitle = displayTitle; + } + + public Calendar getCurrentCalendar() { + return currentCalendar; + } + + public void setCurrentCalendar(Calendar currentCalendar) { + this.currentCalendar = currentCalendar; + } + + public EntityList getCurrentEntListForCalendar() { + return currentEntListForCalendar; + } + + public void setCurrentEntListForCalendar(EntityList currentEntListForCalendar) { + this.currentEntListForCalendar = currentEntListForCalendar; + } + + public Long getCurrentEntIdForCalendar() { + return currentEntIdForCalendar; + } + + public void setCurrentEntIdForCalendar(Long currentEntIdForCalendar) { + this.currentEntIdForCalendar = currentEntIdForCalendar; + } + + public boolean isDisplayLoginDialog() { + return displayLoginDialog; + } + + public boolean isDisplayLoginDialog4PrivatePage(){ + return displayLoginDialog || this.user == null; + } + + public boolean isDisplayLoginDialog4PublicPage(){ + return displayLoginDialog; + } + + public EntityDetailsBean getEntDetailsForm() { + return entDetailsForm; + } + + public void setEntDetailsForm(EntityDetailsBean entDetailsForm) { + this.entDetailsForm = entDetailsForm; + } + + public ESciDocItemForm geteSciDocForm() { + return eSciDocForm; + } + + public void seteSciDocForm(ESciDocItemForm eSciDocForm) { + this.eSciDocForm = eSciDocForm; + } + + public ESciDocItemDataTable getRefDataTable() { + return refDataTable; + } + + public void setRefDataTable(ESciDocItemDataTable refDataTable) { + this.refDataTable = refDataTable; + } + + public GeonameForm getGeoForm() { + return geoForm; + } + + public String getSelectedTab() { + return selectedTab; + } + + public String getSelectedAdvancedSearchTab() { + return selectedAdvancedSearchTab; + } + + public void setSelectedAdvancedSearchTab(String selectedAdvancedSearchTab) { + this.selectedAdvancedSearchTab = selectedAdvancedSearchTab; + } + + + public DynamicPageEditor getPageEditor(){ + if(this.pageEditor == null){ + this.pageEditor = new DynamicPageEditor(); + } + return this.pageEditor; + } + + public DigiListBean getDigiList() { + if(digiList == null){ + digiList = new DigiListBean(getWrapper()); + } + + return digiList; + } + + public DynamicPage getDynamicPage() { + if(dynamicPage == null){ + this.dynamicPage = new DynamicPage(); + } + return dynamicPage; + } + + public void setDynamicPage(DynamicPage dynamicPage) { + this.dynamicPage = dynamicPage; + } + + public PublicCodexView getPublicCodexView(){ + if(publicCodexView == null){ + this.publicCodexView = new PublicCodexView(); + } + return this.publicCodexView; + } + + public PublicCodexBean getPublicCodexBean() { + if(publicCodexBean == null){ + this.publicCodexBean = new PublicCodexBean(); + } + return publicCodexBean; + } + + public void setPublicCodexBean(PublicCodexBean publicCodexBean) { + this.publicCodexBean = publicCodexBean; + } + + + +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/UnityChecker.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,116 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; + +public class UnityChecker extends AbstractISMIBean{ + + /** + * + */ + private static final long serialVersionUID = -5727416233789954800L; + private Entity cloneEntity; + private String unityCheckerMsg; + private boolean renderUnityCheckerDialog; + + @Override + public void reset(){ + super.reset(); + this.renderUnityCheckerDialog = false; + } + + private boolean checkUnity(String unityName, Long id, String objectClass, Entity target, String relationName, String attName){ + this.cloneEntity = null; + unityName = unityName.toLowerCase(); + + if(target != null && target.isPersistent()){ + for (Entity src : getWrapper().getSourcesForTargetRelation(target, relationName, objectClass, -1)) { + if(id == null || id.longValue() != src.getId().longValue()){ + if(StringUtils.isEmpty(attName)){ + if(unityName.equals(src.getOwnValue().toLowerCase())){ + this.cloneEntity = src; + return false; + } + }else{ + Attribute att = getWrapper().getAttributeByName(src.getId(), attName); + if(att != null && unityName.equals(att.getValue().toLowerCase())){ + this.cloneEntity = src; + return false; + } + } + } + } + } + + return true; + } + + public String hideUnityCheckerDialog(){ + this.renderUnityCheckerDialog = false; + return PAGE_EDITOR; + } + + public void renderUnityCheckerDialog(){ + if(cloneEntity != null && cloneEntity.isPersistent()){ + if(cloneEntity.getObjectClass().equals(CODEX)){ + this.unityCheckerMsg = "There is already an object with the same identifier. "; + }else{ + this.unityCheckerMsg = "There is already an object with the same name. "; + } + + this.unityCheckerMsg += "The ID of the " + cloneEntity.getObjectClass().toLowerCase() + + " found is " + cloneEntity.getId() + "."; + + this.unityCheckerMsg += + "\nDo you want to load the existing " + + cloneEntity.getObjectClass().toLowerCase() + "?"; + this.renderUnityCheckerDialog = true; + } + } + + public String loadCloneEntity(){ + if(cloneEntity != null && cloneEntity.isPersistent()){ + getSessionBean().editEntity(cloneEntity); + } + return PAGE_EDITOR; + } + + public boolean checkUnityCollection(String collectionName, Long id, Entity repository){ + return this.checkUnity(collectionName, id, COLLECTION, repository, is_part_of, null); + } + + public boolean checkUnityRepository(String repositoryName, Long id, Entity city){ + return this.checkUnity(repositoryName, id, REPOSITORY, city, is_in, null); + } + + public boolean checkUnityCity(String cityName, Long id, Entity country){ + return this.checkUnity(cityName, id, PLACE, country, is_part_of, null); + } + + public boolean checkUnityCodex(String identifier, Long id, Entity collection){ + return this.checkUnity(identifier, id, CODEX, collection, is_part_of, "identifier"); + } + + public Entity getCloneEntity() { + return cloneEntity; + } + + public void setCloneEntity(Entity cloneEntity) { + this.cloneEntity = cloneEntity; + } + public String getUnityCheckerMsg() { + return unityCheckerMsg; + } + + public void setUnityCheckerMsg(String unityCheckerMsg) { + this.unityCheckerMsg = unityCheckerMsg; + } + public boolean isRenderUnityCheckerDialog() { + return renderUnityCheckerDialog; + } + + public void setRenderUnityCheckerDialog(boolean renderUnityCheckerDialog) { + this.renderUnityCheckerDialog = renderUnityCheckerDialog; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/beans/myDateTimeConverter.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,28 @@ +package de.mpiwg.itgroup.ismi.entry.beans; + +import javax.faces.component.UIComponent; +import javax.faces.context.FacesContext; +import javax.faces.convert.Converter; + + + +public class myDateTimeConverter implements Converter { + + public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) { + // TODO Auto-generated method stub + return null; + } + + public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) { + /* rich + if (SelectInputDate.class.isInstance(arg1)){ + SelectInputDate sd = (SelectInputDate)arg1; + String val = (String)sd.getSubmittedValue(); + + return val; + } + */ + return null; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/dataBeans/AbstractCache.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,20 @@ +package de.mpiwg.itgroup.ismi.entry.dataBeans; + +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.services.ServiceRegistry; + +public class AbstractCache { + + private ServiceRegistry sr; + + public AbstractCache(ServiceRegistry sr){ + this.sr = sr; + this.reset(); + } + + public void reset(){} + + protected WrapperService getWrapper(){ + return sr.getWrapper(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/dataBeans/RoleCache.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,69 @@ +package de.mpiwg.itgroup.ismi.entry.dataBeans; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Relation; +import org.mpi.openmind.repository.services.ServiceRegistry; + +public class RoleCache extends AbstractCache{ + Map<String, List<Long>> roleMap = null; + + public RoleCache(ServiceRegistry sr) { + super(sr); + } + + @Override + public void reset(){ + super.reset(); + loadRoleMap(); + } + + private void loadRoleMap(){ + roleMap = new HashMap<String, List<Long>>(); + //List<Entity> roles = getOtl().getLightweightAssertions("ROLE", null, -1); + List<Entity> roles = getWrapper().getEntitiesByDef("ROLE"); + for(Entity role : roles){ + if(StringUtils.isNotEmpty(role.getOwnValue())){ + String roleLowCase = role.getOwnValue().toLowerCase(); + getRoleMap().put(roleLowCase, new ArrayList<Long>()); + List<Relation> relList = getWrapper().getTargetRelations(role, "has_role", "PERSON", -1); + for(Relation hasRole : relList){ + getRoleMap().get(roleLowCase).add(hasRole.getSourceId()); + } + }else{ + System.err.println("****************"); + System.err.println("Entity Role without Label: " + role); + System.err.println("****************"); + } + } + } + + public List<String> getRoleList(Long id){ + List<String> list = new ArrayList<String>(); + for(String roleName : this.getRoleMap().keySet()){ + if(this.getRoleMap().get(roleName).contains(id)){ + list.add(roleName); + + } + } + return list; + } + + public Map<String, List<Long>> getRoleMap() { + if(roleMap == null) + loadRoleMap(); + return roleMap; + } + + public boolean roleContainsPersonId(String role, Long id){ + if(StringUtils.isEmpty(role) || this.getRoleMap().get(role.toLowerCase()) == null) + return false; + + return this.getRoleMap().get(role.toLowerCase()).contains(id); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/dataBeans/SimpleSearchCache.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,141 @@ +package de.mpiwg.itgroup.ismi.entry.dataBeans; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.faces.model.SelectItem; + +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.services.ServiceRegistry; + +public class SimpleSearchCache extends RoleCache{ + + private boolean mapDirty; + private Map<Attribute, Entity> attResultMap = new HashMap<Attribute, Entity>(); + + private Map<Long, Attribute> attMap = new HashMap<Long, Attribute>(); + private Map<Long, Entity> entMap = new HashMap<Long, Entity>(); + private Map<String, String> descriptionMap = new HashMap<String, String>(); + private List<Long> ignoredAttIdList = new ArrayList<Long>(); + + + public SimpleSearchCache(ServiceRegistry sr){ + super(sr); + } + + @Override + public void reset(){ + super.reset(); + this.attResultMap = new HashMap<Attribute, Entity>(); + this.mapDirty = true; + this.attMap = new HashMap<Long, Attribute>(); + this.entMap = new HashMap<Long, Entity>(); + //this.ignoredIdList = new ArrayList<Long>(); + } + + public List<SelectItem> getAllPersons(){ + List<SelectItem> list = new ArrayList<SelectItem>(); + for(Entity ent : getWrapper().getEntitiesByDef("PERSON")){ + list.add( + new SelectItem(ent.getId(), ent.getOwnValue() + +" [" + ent.getId() + "]")); + } + return list; + } + + public List<SelectItem> getPersonsByRole(String role){ + List<SelectItem> list = new ArrayList<SelectItem>(); + for(Entity ent : getWrapper().getEntitiesByDef("PERSON")){ + if(roleContainsPersonId(role, ent.getId())){ + list.add( + new SelectItem( + ent.getId(), + ent.getOwnValue() +" [" + ent.getId() + "]")); + } + } + return list; + } + + public List<Entity> getPersonListByRole(String role){ + List<Entity> list = new ArrayList<Entity>(); + for(Entity ent : getWrapper().getEntitiesByDef("PERSON")){ + if(roleContainsPersonId(role, ent.getId())){ + list.add(ent); + } + } + return list; + } + + + public Attribute getAttById(Long id){ + for(Attribute att : attResultMap.keySet()){ + if(att.getId().compareTo(id) == 0) + return att; + } + return null; + } + + public boolean isMapDirty() { + return mapDirty; + } + + public void setMapDirty(boolean mapDirty) { + this.reset(); + this.mapDirty = mapDirty; + } + + public Map<Attribute, Entity> getAttResultMap() { + return attResultMap; + } + + public void setAttResultMap(Map<Attribute, Entity> map) { + this.reset(); + this.attResultMap = map; + this.mapDirty = false; + } + + public boolean containsAttribute(Attribute att){ + return this.attMap.containsKey(att.getId()); + } + + public void setTuple(Entity ent, Attribute att, String description){ + this.attMap.put(att.getId(), att); + this.entMap.put(att.getId(), ent); + this.descriptionMap.put(att.getId() + "-" + ent.getId(), description); + } + + public boolean ignoreAttribute(Attribute att){ + return this.getIgnoredAttIdList().contains(att.getId()); + } + + public Map<Long, Attribute> getAttMap() { + return attMap; + } + + public void setAttMap(Map<Long, Attribute> attMap) { + this.attMap = attMap; + } + + public Map<Long, Entity> getEntMap() { + return entMap; + } + + public void setEntMap(Map<Long, Entity> entMap) { + this.entMap = entMap; + } + + public Map<String, String> getDescriptionMap() { + return descriptionMap; + } + + public void setDescriptionMap(Map<String, String> descriptionMap) { + this.descriptionMap = descriptionMap; + } + + public List<Long> getIgnoredAttIdList() { + return this.ignoredAttIdList; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/entry/utils/PrivacityUtils.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,191 @@ +package de.mpiwg.itgroup.ismi.entry.utils; + +import java.util.ArrayList; +import java.util.List; + +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Relation; + +public class PrivacityUtils { + + + public static List<Entity> changePrivacity4Person(Entity person, Boolean isPublic, WrapperService wrapper){ + List<Entity> saveList = new ArrayList<Entity>(); + + if(person.isLightweight()){ + person = wrapper.getEntityContent(person); + } + + boolean privacity = false; + if(isPublic == null){ + privacity = !person.getIsPublic(); + }else{ + privacity = isPublic; + } + + person.setIsPublic(privacity); + saveList.add(person); + + List<Relation> relList = null; + //loading relations + if(privacity){ + relList = new ArrayList<Relation>(person.getSourceRelations()); + for (Relation rel : relList) { + String relName = rel.getOwnValue(); + if (relName.equals("was_born_in") || + relName.equals("lived_in") || + relName.equals("was_student_of") || + relName.equals("has_role") || + relName.equals("died_in")) { + Entity target = wrapper.getEntityById(rel.getTargetId()); + //target = wrapper.getEntityContent(target); + target.setIsPublic(privacity); + saveList.add(target); + } + } + } + + relList = new ArrayList<Relation>(person.getTargetRelations()); + for (Relation rel : relList) { + String relName = rel.getOwnValue(); + //title were be not included into this list + if (relName.equals("is_alias_name_of") || relName.equals("is_prime_alias_name_of")) { + Entity source = wrapper.getEntityById(rel.getSourceId()); + //source = wrapper.getEntityContent(source); + source.setIsPublic(privacity); + saveList.add(source); + } + } + + return saveList; + } + + public static List<Entity> changePrivacity4Title(Entity title, Boolean isPublic, WrapperService wrapper){ + List<Entity> saveList = new ArrayList<Entity>(); + + /* + if(title.isLightweight()){ + title = wrapper.getEntityContent(title); + }*/ + + boolean privacity = false; + if(isPublic == null){ + privacity = !title.getIsPublic(); + }else{ + privacity = isPublic; + } + + title.setIsPublic(privacity); + saveList.add(title); + + if(privacity){ + for(Entity ent : wrapper.getTargetsForSourceRelation(title, "has_subject", "SUBJECT", 1)){ + //if(ent.isLightweight()) + // ent = wrapper.getEntityContent(ent); + ent.setIsPublic(privacity); + saveList.add(ent); + } + + for(Entity ent : wrapper.getTargetsForSourceRelation(title, "was_created_in", "PLACE", 1)){ + //if(ent.isLightweight()) + // ent = wrapper.getEntityContent(ent); + ent.setIsPublic(privacity); + saveList.add(ent); + } + } + + for(Entity ent : wrapper.getSourcesForTargetRelation(title, "is_alias_title_of", "ALIAS", -1)){ + //if(ent.isLightweight()) + // ent = wrapper.getEntityContent(ent); + ent.setIsPublic(privacity); + saveList.add(ent); + } + + return saveList; + } + + + /** + * 437080 + * al-Taḏkiraẗ fī ʿilm al-hayʾaẗ + * BIT(1) + * create: + * ALTER TABLE `openmind`.`node` ADD COLUMN `public` BIT(1) AFTER `possible_value`; + * modify: + * ALTER TABLE `openmind`.`node` MODIFY COLUMN `public` BIT(1) NOT NULL DEFAULT false; + * @param witness + * @param isPublic + * @param wrapper + * @return + */ + public static List<Entity> changePrivacity4Witness(Entity witness, Boolean isPublic, WrapperService wrapper){ + List<Entity> saveList = new ArrayList<Entity>(); + /* + if(witness.isLightweight()){ + witness = wrapper.getEntityContent(witness); + } + */ + boolean privacity = false; + if(isPublic == null){ + privacity = !witness.getIsPublic(); + }else{ + privacity = isPublic; + } + + witness.setIsPublic(privacity); + saveList.add(witness); + + //changing references + List<Entity> refEntities = wrapper.getSourcesForTargetRelation(witness.getId(), "is_reference_of", "REFERENCE", -1); + for(Entity ref : refEntities){ + if(ref.isLightweight()){ + ref = wrapper.getEntityContent(ref); + } + ref.setIsPublic(privacity); + saveList.add(ref); + } + + //only if the witness is done public, the related entities will be changed. + if(privacity){ + List<Entity> list = + wrapper.getTargetsForSourceRelation(witness.getId(),"is_part_of", "CODEX", 1); + if (list.size() > 0) { + Entity codex = list.get(0); + codex.setIsPublic(privacity); + saveList.add(codex); + + list = wrapper.getTargetsForSourceRelation(codex.getId(), "is_part_of", "COLLECTION", 1); + if (list.size() > 0) { + Entity collection = list.get(0); + collection.setIsPublic(privacity); + saveList.add(collection); + + list = wrapper.getTargetsForSourceRelation(collection.getId(), "is_part_of", "REPOSITORY", 1); + if (list.size() > 0) { + Entity repository = list.get(0); + repository.setIsPublic(privacity); + saveList.add(repository); + + list = wrapper.getTargetsForSourceRelation(repository.getId(), "is_in", "PLACE", 1); + if(list.size() > 0){ + Entity city = list.get(0); + city.setIsPublic(privacity); + saveList.add(city); + + list = wrapper.getTargetsForSourceRelation(city.getId(), "is_part_of", "PLACE", 1); + if(list.size() > 0){ + Entity country = list.get(0); + country.setIsPublic(privacity); + saveList.add(country); + } + } + } + } + } + } + + return saveList; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/event/beans/AbstractEvent.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,199 @@ +package de.mpiwg.itgroup.ismi.event.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.event.AjaxBehaviorEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.log4j.Logger; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.auxObjects.lo.EventTextLO; +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; +import de.mpiwg.itgroup.ismi.entry.beans.SessionBean; +import de.mpiwg.itgroup.ismi.util.guiComponents.Calendar; + +public class AbstractEvent extends AbstractISMIBean implements Serializable{ + + + /** + * + */ + private static final long serialVersionUID = 6080984991162765794L; + + protected static Logger logger = Logger.getLogger(AbstractEvent.class); + + public static String was_studied_by = "was_studied_by"; + public static String was_studied_in = "was_studied_in"; + public static String is_a_study_of = "is_a_study_of"; + public static String was_advised_by = "was_advised_by"; + public static String was_copied_for = "was_copied_for"; + public static String has_person_copying_text = "has_person_copying_text"; + public static String was_copied_in = "was_copied_in"; + public static String is_a_copy_of = "is_a_copy_of"; + public static String is_a_transfer_of = "is_a_transfer_of"; + public static String was_transferred_from = "was_transferred_from"; + public static String was_transferred_to = "was_transferred_to"; + public static String has_original_location = "has_original_location"; + public static String has_new_location = "has_new_location"; + public static String was_transferred_in = "was_transferred_in"; + + protected EventTextLO textLo = new EventTextLO(TEXT, full_title_translit, this); + protected Entity witness; + protected Long witnessId; + protected List<SelectItem> witnessList; + protected Calendar date; + + protected ListenerObject placeLo = new ListenerObject(PLACE, name); + + public AbstractEvent(Entity event){ + this.setEvent(event); + } + + protected Entity event; + /* + public void listenerChangeText(ValueChangeEvent event) { + this.text = changeListener(event, text, TEXT, full_title_translit); + this.witness = null; + if(text.entity != null && text.entity.isPersistent()){ + refreshWitnesses(text.entity); + }else{ + this.witnessList = new ArrayList<SelectItem>(); + } + }*/ + + public void refreshWitnesses(Entity text){ + this.witnessList = new ArrayList<SelectItem>(); + List<Entity> list = getWrapper().getSourcesForTargetRelation(text, is_exemplar_of, WITNESS, -1); + System.out.println("Found " + list.size() + " witnesses"); + if(list.isEmpty()){ + witnessList.add(new SelectItem(null, "This text has no witness associated")); + }else{ + witnessList.add(new SelectItem(null, "-- choose witness --")); + for(Entity ent : list){ + witnessList.add(new SelectItem(ent.getId(), ent.getOwnValue() + " ID: " + ent.getId())); + } + } + } + + public void listenerChangeWitness(ValueChangeEvent event) { + if(event.getNewValue() != null){ + try{ + Long id = (Long)event.getNewValue(); + this.witness = getWrapper().getEntityById(id); + }catch (Exception e) { + e.printStackTrace(); + } + }else{ + this.witness = null; + } + } + + protected Entity getTextOfWitness(Entity witness){ + Entity text = null; + List<Entity> list = getWrapper().getTargetsForSourceRelation(witness, is_exemplar_of, TEXT, 1); + if(list.size() > 0){ + text = list.get(0); + } + return text; + } + /* + public void listenerChangePlace(ValueChangeEvent event) { + this.place = changeListener(event, place, PLACE, name); + }*/ + + public Entity getEvent() { + return event; + } + + public void setEvent(Entity event) { + this.reset(); + this.event = event; + } + + public String getSessionUserName() { + SessionBean bean = getSessionBean(); + if(bean != null){ + return bean.getUsername(); + } + return null; + } + + public EventTextLO getTextLo() { + return textLo; + } + + public void setTextLo(EventTextLO textLo) { + this.textLo = textLo; + } + + public Entity getWitness() { + return witness; + } + + public void setWitness(Entity witness) { + this.witness = witness; + } + + public Calendar getDate() { + return date; + } + + public void setDate(Calendar date) { + this.date = date; + } + + public List<SelectItem> getWitnessList() { + return witnessList; + } + + public void setWitnessList(List<SelectItem> witnessList) { + this.witnessList = witnessList; + } + + public Long getWitnessId() { + return witnessId; + } + + public void setWitnessId(Long witnessId) { + this.witnessId = witnessId; + } + + + + public ListenerObject getPlaceLo() { + return placeLo; + } + + public void setPlaceLo(ListenerObject placeLo) { + this.placeLo = placeLo; + } + + public void test(AjaxBehaviorEvent e){ + System.out.println("test(ActionEvent e)"); + + } + + @Override + public String save(){ + logger.info("*************** START Saving "+ this.defObjectClass + " [ID=" + event.getId() +", user"+ getUserName() +"] *********************"); + this.start = System.currentTimeMillis(); + return null; + } + + @Override + protected void saveEnd(){ + logger.info("*************** END Saving "+ this.defObjectClass + " [ID=" + event.getId() +", user"+ getUserName() +"] *********************\n"); + } + + @Override + protected void printSuccessSavingEntity(){ + this.addGeneralMsg("The entity was successfully saved!"); + this.addGeneralMsg("Its ID is " + this.event.getId()); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/event/beans/CopyEvent.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,235 @@ +package de.mpiwg.itgroup.ismi.event.beans; + +import java.io.Serializable; +import java.util.ArrayList; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Node; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.auxObjects.lo.EventTextLO; +import de.mpiwg.itgroup.ismi.util.guiComponents.Calendar; + +public class CopyEvent extends AbstractEvent implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 1545705063133894571L; + + public static String OC = "COPY_EVENT"; + + private ListenerObject personCopiedForLo = new ListenerObject(PERSON, name_translit); + private ListenerObject personCopyingTextLo = new ListenerObject(PERSON, name_translit); + private ListenerObject repositoryLo = new ListenerObject(REPOSITORY, name); + + private Calendar date; + + @Override + public void setEvent(Entity ev){ + reset(); + event = ev; + if(event != null && event.isPersistent()){ + if(event.isLightweight()){ + event = getWrapper().getEntityContent(event); + } + + this.loadAttributes(this.event); + this.date = updateCalendar(this.event.getAttributeByName("date")); + + for (Relation rel : event.getSourceRelations()) { + Entity target = null; + if (rel.getOwnValue().equals(was_copied_for)) { + //EVENT was_studied_by PERSON + target = getTargetRelation(rel); + personCopiedForLo.setEntityAndAttribute0(target); + }else if (rel.getOwnValue().equals(has_person_copying_text)) { + //EVENT was_advised_by PERSON + target = getTargetRelation(rel); + personCopyingTextLo.setEntityAndAttribute0(target); + + } else if (rel.getOwnValue().equals(was_copied_in)) { + target = getTargetRelation(rel); + if(target.getObjectClass().equals(PLACE)){ + //EVENT was_studied_in PLACE + placeLo.setEntityAndAttribute0(target); + }else if(target.getObjectClass().equals(REPOSITORY)){ + //EVENT was_studied_in REPOSITORY + repositoryLo.setEntityAndAttribute0(target); + } + } else if (rel.getOwnValue().equals(is_a_copy_of)) { + //EVENT study_of WITNESS + //WITNESS is_exemplar_of TEXT + this.witness = getTargetRelation(rel); + if(witness != null && witness.isPersistent()){ + witnessId = witness.getId(); + this.textLo.setEntityAndAttribute0( getTextOfWitness(witness)); + refreshWitnesses(textLo.entity); + } + } + } + } + } + + @Override + public void reset(){ + super.reset(); + this.defObjectClass = OC; + + if(textLo != null){ + textLo.reset(); + }else{ + textLo = new EventTextLO(TEXT, full_title_translit, this); + } + + if(personCopiedForLo != null){ + personCopiedForLo.reset(); + }else{ + personCopiedForLo = new ListenerObject(PERSON, name_translit); + } + + if(personCopyingTextLo != null){ + personCopyingTextLo.reset(); + }else{ + personCopyingTextLo = new ListenerObject(PERSON, name_translit); + } + + if(placeLo != null){ + placeLo.reset(); + }else{ + placeLo = new ListenerObject(PLACE, name); + } + + + if(repositoryLo != null){ + repositoryLo.reset(); + }else{ + repositoryLo = new ListenerObject(REPOSITORY, name); + } + + + + this.date = new Calendar(); + this.witnessList = new ArrayList<SelectItem>(); + } + + /* + public void listenerChangePersonCopyingText(ValueChangeEvent event) { + this.personCopyingText = changeListener(event, personCopyingText, PERSON, name_translit); + } + + public void listenerChangePersonCopiedFor(ValueChangeEvent event) { + this.personCopiedFor = changeListener(event, personCopiedFor, PERSON, name_translit); + } + + public void listenerChangePlace(ValueChangeEvent event) { + this.place = changeListener(event, place, PLACE, name); + } + + public void listenerChangeRepository(ValueChangeEvent event) { + this.repository = changeListener(event, repository, REPOSITORY, name); + }*/ + + public void listenerSave(ActionEvent event) { + this.save(); + } + + @Override + public String save(){ + super.save(); + if(!checkConsistency()){ + addGeneralMsg("Either the Witness, the Person or the Place is empty."); + addGeneralMsg("The event could not be saved."); + return null; + } + + try{ + getAttributes().put("date", this.date.toJSONString()); + event = updateEntityAttributes(event); + + // EVENT -> was_copied_for -> PERSON + event.replaceSourceRelation(personCopiedForLo.entity, PERSON, was_copied_for); + + // EVENT -> has_person_copying_text -> PERSON + event.replaceSourceRelation(personCopyingTextLo.entity, PERSON, has_person_copying_text); + + // EVENT -> was_copied_in -> REPOSITORY + event.replaceSourceRelation(repositoryLo.entity, REPOSITORY, was_copied_in); + + // EVENT -> was_copied_in -> PLACE + event.replaceSourceRelation(placeLo.entity, PLACE, was_copied_in); + + // EVENT -> is_a_copy_of -> WITNESS + if(witness.isLightweight()){ + this.witness = getWrapper().getEntityByIdWithContent(witness.getId()); + } + event.replaceSourceRelation(witness, WITNESS, is_a_copy_of); + + getWrapper().saveEntity(event, getSessionUserName()); + + printSuccessSavingEntity(); + + }catch (Exception e) { + addGeneralMsg(e.getMessage()); + logger.error(e.getMessage(), e); + } + saveEnd(); + return null; + } + + public boolean checkConsistency(){ + if(this.witness == null || + this.textLo.entity == null || + this.repositoryLo.entity == null || + this.personCopiedForLo.entity == null || + this.personCopyingTextLo.entity == null){ + return false; + } + return true; + } + + public CopyEvent(Entity event) { + super(event); + } + + public CopyEvent(){ + super(new Entity(Node.TYPE_ABOX, OC, false)); + } + + public ListenerObject getPersonCopiedForLo() { + return personCopiedForLo; + } + + public void setPersonCopiedForLo(ListenerObject personCopiedForLo) { + this.personCopiedForLo = personCopiedForLo; + } + + public ListenerObject getPersonCopyingTextLo() { + return personCopyingTextLo; + } + + public void setPersonCopyingTextLo(ListenerObject personCopyingTextLo) { + this.personCopyingTextLo = personCopyingTextLo; + } + + public ListenerObject getRepositoryLo() { + return repositoryLo; + } + + public void setRepositoryLo(ListenerObject repositoryLo) { + this.repositoryLo = repositoryLo; + } + + public Calendar getDate() { + return date; + } + + public void setDate(Calendar date) { + this.date = date; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/event/beans/StudyEvent.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,245 @@ +package de.mpiwg.itgroup.ismi.event.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Node; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.auxObjects.lo.EventTextLO; +import de.mpiwg.itgroup.ismi.util.guiComponents.Calendar; + +public class StudyEvent extends AbstractEvent implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 2242991945890055323L; + + public static String OC = "STUDY_EVENT"; + + private ListenerObject personLo = new ListenerObject(PERSON, name_translit); + private ListenerObject advisorLo = new ListenerObject(PERSON, name_translit); + private ListenerObject repositoryLo = new ListenerObject(REPOSITORY, name); + + private List<SelectItem> suggestedEngagementOptions = new ArrayList<SelectItem>(); + + public StudyEvent(){ + super(new Entity(Node.TYPE_ABOX, OC, false)); + refreshEngagementOptions(); + } + + public StudyEvent(Entity event){ + super(event); + refreshEngagementOptions(); + } + + public void listenerRefreshEngagementOptions(ActionEvent event){ + this.refreshEngagementOptions(); + } + + private void refreshEngagementOptions(){ + this.suggestedEngagementOptions = new ArrayList<SelectItem>(); + suggestedEngagementOptions.add(new SelectItem(null, "--choose--")); + Attribute binding = getWrapper().getDefAttributeByOwnValue(OC, "options_for_engagement"); + if(binding != null){ + for(String s : binding.getPossibleValuesList()){ + this.suggestedEngagementOptions.add(new SelectItem(s)); + } + } + } + + @Override + public void setEvent(Entity ev){ + reset(); + event = ev; + if(event != null && event.isPersistent()){ + if(event.isLightweight()){ + event = getWrapper().getEntityContent(event); + } + + this.loadAttributes(this.event); + this.date = updateCalendar(this.event.getAttributeByName("date")); + + for (Relation rel : event.getSourceRelations()) { + Entity target = null; + if (rel.getOwnValue().equals(was_studied_by)) { + //EVENT was_studied_by PERSON + target = getTargetRelation(rel); + personLo.setEntityAndAttribute0(target); + }else if (rel.getOwnValue().equals(was_advised_by)) { + //EVENT was_advised_by PERSON + target = getTargetRelation(rel); + advisorLo.setEntityAndAttribute0(target); + + } else if (rel.getOwnValue().equals(was_studied_in)) { + target = getTargetRelation(rel); + if(target.getObjectClass().equals(PLACE)){ + //EVENT was_studied_in PLACE + placeLo.setEntityAndAttribute0(target); + }else if(target.getObjectClass().equals(REPOSITORY)){ + //EVENT was_studied_in REPOSITORY + repositoryLo.setEntityAndAttribute0(target); + } + } else if (rel.getOwnValue().equals(is_a_study_of)) { + //EVENT study_of WITNESS + //WITNESS is_exemplar_of TEXT + this.witness = getTargetRelation(rel); + if(witness != null && witness.isPersistent()){ + witnessId = witness.getId(); + this.textLo.setEntityAndAttribute0( getTextOfWitness(witness)); + refreshWitnesses(textLo.entity); + } + } + } + } + } + + public void listenerSave(ActionEvent event) { + this.save(); + } + + @Override + public String save(){ + super.save(); + if(!checkConsistency()){ + addGeneralMsg("Either the Witness, the Person or the Place is empty."); + addGeneralMsg("The event could not be saved."); + return null; + } + + try{ + getAttributes().put("date", this.date.toJSONString()); + event = updateEntityAttributes(event); + + // EVENT -> was_studied_by -> PERSON + event.replaceSourceRelation(personLo.entity, PERSON, was_studied_by); + + // EVENT -> was_advised_by -> PERSON + event.replaceSourceRelation(advisorLo.entity, PERSON, was_advised_by); + + // EVENT -> was_studied_in -> REPOSITORY + event.replaceSourceRelation(repositoryLo.entity, REPOSITORY, was_studied_in); + //event.replaceSourceRelation(getRepositoryLo().entity, REPOSITORY, was_studied_in); + + // EVENT -> was_studied_in -> PLACE + event.replaceSourceRelation(placeLo.entity, PLACE, was_studied_in); + + // EVENT -> was_studied_by -> WITNESS + if(witness.isLightweight()){ + witness = getWrapper().getEntityByIdWithContent(witness.getId()); + } + event.replaceSourceRelation(witness, WITNESS, is_a_study_of); + + getWrapper().saveEntity(event, getSessionUserName()); + + printSuccessSavingEntity(); + + }catch (Exception e) { + addGeneralMsg(e.getMessage()); + logger.error(e.getMessage(), e); + } + saveEnd(); + return null; + } + + /* + public void listenerChangePerson(ValueChangeEvent event) { + this.person = changeListener(event, person, PERSON, name_translit); + } + + public void listenerChangeAdvisor(ValueChangeEvent event) { + this.advisor = changeListener(event, advisor, PERSON, name_translit); + } + + public void listenerChangeRepository(ValueChangeEvent event) { + this.repository = changeListener(event, repository, REPOSITORY, name); + } + */ + @Override + public void reset(){ + super.reset(); + this.defObjectClass = OC; + if(personLo != null){ + personLo.reset(); + }else{ + personLo = new ListenerObject(PERSON, name_translit); + } + + if(advisorLo != null){ + advisorLo.reset(); + }else{ + advisorLo = new ListenerObject(PERSON, name_translit); + } + + if(textLo != null){ + textLo.reset(); + }else{ + textLo = new EventTextLO(TEXT, full_title_translit, this); + } + if(placeLo != null){ + placeLo.reset(); + }else{ + placeLo = new ListenerObject(PLACE, name); + } + + if(repositoryLo != null){ + repositoryLo.reset(); + }else{ + repositoryLo = new ListenerObject(REPOSITORY, name); + } + + this.date = new Calendar(); + this.witnessList = new ArrayList<SelectItem>(); + this.refreshEngagementOptions(); + } + + public boolean checkConsistency(){ + if(this.witness == null || this.textLo.entity == null || this.repositoryLo.entity == null || this.personLo.entity == null){ + return false; + } + return true; + } + + public ListenerObject getPersonLo() { + return personLo; + } + + public void setPersonLo(ListenerObject personLo) { + this.personLo = personLo; + } + + public ListenerObject getAdvisorLo() { + return advisorLo; + } + + public void setAdvisorLo(ListenerObject advisorLo) { + this.advisorLo = advisorLo; + } + + public ListenerObject getRepositoryLo() { + return repositoryLo; + } + + public void setRepositoryLo(ListenerObject repositoryLo) { + this.repositoryLo = repositoryLo; + } + + public List<SelectItem> getSuggestedEngagementOptions() { + return suggestedEngagementOptions; + } + + public void setSuggestedEngagementOptions( + List<SelectItem> suggestedEngagementOptions) { + this.suggestedEngagementOptions = suggestedEngagementOptions; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/event/beans/TransferEvent.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,432 @@ +package de.mpiwg.itgroup.ismi.event.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Node; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.auxObjects.lo.EventTextLO; +import de.mpiwg.itgroup.ismi.util.guiComponents.Calendar; + +public class TransferEvent extends AbstractEvent implements Serializable{ + + private static final long serialVersionUID = -3606229569295260209L; + + public static String OC = "TRANSFER_EVENT"; + + private boolean selectedPersonFrom; + private ListenerObject personFromLo = new ListenerObject(PERSON, name_translit); + private ListenerObject repositoryFromLo = new ListenerObject(REPOSITORY, name); + + private boolean selectedPersonTo; + private ListenerObject personToLo = new ListenerObject(PERSON, name_translit); + private ListenerObject repositoryToLo = new ListenerObject(REPOSITORY, name); + + private boolean selectedPlaceOriginalLocation; + private ListenerObject placeOriginalLocationLo = new ListenerObject(PLACE, name); + private ListenerObject repositoryOriginalLocationLo = new ListenerObject(REPOSITORY, name); + + private boolean selectedPlaceNewLocation; + private ListenerObject placeNewLocationLo = new ListenerObject(PLACE, name); + private ListenerObject repositoryNewLocationLo = new ListenerObject(REPOSITORY, name); + + private List<SelectItem> suggestedTransferOptions = new ArrayList<SelectItem>(); + + public TransferEvent(Entity event) { + super(event); + this.refreshTransferOptions(); + } + + public TransferEvent(){ + super(new Entity(Node.TYPE_ABOX, OC, false)); + this.refreshTransferOptions(); + } + + @Override + public void setEvent(Entity ev){ + reset(); + event = ev; + if(event != null && event.isPersistent()){ + if(event.isLightweight()){ + event = getWrapper().getEntityContent(event); + } + + this.loadAttributes(this.event); + this.date = updateCalendar(this.event.getAttributeByName("date")); + + for (Relation rel : event.getSourceRelations()) { + Entity target = null; + if (rel.getOwnValue().equals(was_transferred_from)) { + // EVENT -> was_transferred_from -> PERSON/REPOSITORY + target = getTargetRelation(rel); + if(target.getObjectClass().equals(PERSON)){ + personFromLo.setEntityAndAttribute0(target); + selectedPersonFrom = true; + }else{ + repositoryFromLo.setEntityAndAttribute0(target); + selectedPersonFrom = false; + } + + }else if (rel.getOwnValue().equals(was_transferred_to)) { + // EVENT -> was_transferred_to -> PERSON/REPOSITORY + target = getTargetRelation(rel); + if(target.getObjectClass().equals(PERSON)){ + personToLo.setEntityAndAttribute0(target); + selectedPersonTo = true; + }else{ + repositoryToLo.setEntityAndAttribute0(target); + selectedPersonTo = false; + } + } else if (rel.getOwnValue().equals(has_original_location)) { + // EVENT -> has_original_location -> PLACE/REPOSITORY + target = getTargetRelation(rel); + if(target.getObjectClass().equals(PLACE)){ + placeOriginalLocationLo.setEntityAndAttribute0(target); + selectedPlaceOriginalLocation = true; + }else{ + repositoryOriginalLocationLo.setEntityAndAttribute0(target); + selectedPlaceOriginalLocation = false; + } + } else if (rel.getOwnValue().equals(has_new_location)) { + // EVENT -> has_new_location -> PLACE/REPOSITORY + target = getTargetRelation(rel); + if(target.getObjectClass().equals(PLACE)){ + placeNewLocationLo.setEntityAndAttribute0(target); + selectedPlaceNewLocation = true; + }else{ + repositoryNewLocationLo.setEntityAndAttribute0(target); + selectedPlaceNewLocation = false; + } + } else if (rel.getOwnValue().equals(is_a_transfer_of)) { + //EVENT study_of WITNESS + //WITNESS is_exemplar_of TEXT + this.witness = getTargetRelation(rel); + if(witness != null && witness.isPersistent()){ + witnessId = witness.getId(); + this.textLo.setEntityAndAttribute0( getTextOfWitness(witness)); + refreshWitnesses(textLo.entity); + } + } else if (rel.getOwnValue().equals(was_transferred_in)) { + target = getTargetRelation(rel); + this.placeLo.setEntityAndAttribute0(target); + } + } + } + } + + /* + public void listenerChangePersonFrom(ValueChangeEvent event) { + this.personFrom = changeListener(event, personFrom, PERSON, name_translit); + } + + public void listenerChangePersonTo(ValueChangeEvent event) { + this.personTo = changeListener(event, personTo, PERSON, name_translit); + } + + public void listenerChangeRepositoryFrom(ValueChangeEvent event) { + this.repositoryFrom = changeListener(event, repositoryFrom, REPOSITORY, name); + } + + public void listenerChangeRepositoryTo(ValueChangeEvent event) { + this.repositoryTo = changeListener(event, repositoryTo, REPOSITORY, name); + }*/ + + public void listenerChangeSelectionFrom(ActionEvent event){ + this.selectedPersonFrom = !selectedPersonFrom; + } + + public void listenerChangeSelectionTo(ActionEvent event){ + this.selectedPersonTo = !selectedPersonTo; + } + /* + public void listenerChangePlaceOriginalLocation(ValueChangeEvent event){ + this.placeOriginalLocation = changeListener(event, placeOriginalLocation, PLACE, name); + } + + public void listenerChangePlaceNewLocation(ValueChangeEvent event){ + this.placeNewLocation = changeListener(event, placeNewLocation, PLACE, name); + } + + public void listenerChangeRepositoryOriginalLocation(ValueChangeEvent event){ + this.repositoryOriginalLocation = changeListener(event, repositoryOriginalLocation, REPOSITORY, name); + } + + public void listenerChangeRepositoryNewLocation(ValueChangeEvent event){ + this.repositoryNewLocation = changeListener(event, repositoryNewLocation, REPOSITORY, name); + } + */ + public void listenerChangeSelectionNewLocation(ActionEvent event){ + this.selectedPlaceNewLocation = !selectedPlaceNewLocation; + } + + public void listenerChangeSelectionOriginalLocation(ActionEvent event){ + this.selectedPlaceOriginalLocation = !selectedPlaceOriginalLocation; + } + + @Override + public void reset(){ + super.reset(); + this.selectedPersonFrom = true; + this.selectedPersonTo = true; + this.selectedPlaceOriginalLocation = true; + this.selectedPlaceNewLocation = true; + + this.defObjectClass = OC; + this.personFromLo = new ListenerObject(PERSON, name_translit); + this.repositoryFromLo = new ListenerObject(REPOSITORY, name); + this.personToLo = new ListenerObject(PERSON, name_translit); + this.repositoryToLo = new ListenerObject(REPOSITORY, name); + + if(textLo != null){ + textLo.reset(); + }else{ + textLo = new EventTextLO(TEXT, full_title_translit, this); + } + + if(placeLo != null){ + placeLo.reset(); + }else{ + placeLo = new ListenerObject(PLACE, name); + } + + + this.date = new Calendar(); + this.witnessList = new ArrayList<SelectItem>(); + + this.placeNewLocationLo = new ListenerObject(PLACE, name); + this.repositoryNewLocationLo = new ListenerObject(REPOSITORY, name); + this.personToLo = new ListenerObject(PERSON, name_translit); + this.repositoryToLo = new ListenerObject(REPOSITORY, name); + this.placeOriginalLocationLo = new ListenerObject(PLACE, name); + this.repositoryOriginalLocationLo = new ListenerObject(REPOSITORY, name); + /* + this.repositoryFromLo.reset(); + this.repositoryToLo.reset(); + this.placeNewLocationLo.reset(); + this.placeOriginalLocationLo.reset(); + this.repositoryNewLocationLo.reset(); + this.repositoryOriginalLocationLo.reset(); + */ + } + + + public void listenerRefreshTransferOptions(ActionEvent event){ + this.refreshTransferOptions(); + } + + private void refreshTransferOptions(){ + this.suggestedTransferOptions = new ArrayList<SelectItem>(); + suggestedTransferOptions.add(new SelectItem(null, "--choose--")); + Attribute binding = getWrapper().getDefAttributeByOwnValue(OC, "options_for_transfer"); + if(binding != null){ + for(String s : binding.getPossibleValuesList()){ + this.suggestedTransferOptions.add(new SelectItem(s)); + } + } + } + + public void listenerSave(ActionEvent event) { + this.save(); + } + + @Override + public String save(){ + super.save(); + if(!checkConsistency()){ + addGeneralMsg("Either the Witness, the Person or the Place is empty."); + addGeneralMsg("The event could not be saved."); + return null; + } + + try{ + getAttributes().put("date", this.date.toJSONString()); + event = updateEntityAttributes(event); + + // EVENT -> was_studied_by -> WITNESS + if(witness.isLightweight()){ + this.witness = getWrapper().getEntityByIdWithContent(witness.getId()); + } + event.replaceSourceRelation(witness, WITNESS, is_a_transfer_of); + + // EVENT -> was_transferred_from -> PERSON/REPOSITORY + if(isSelectedPersonFrom()){ + event.replaceSourceRelation(personFromLo.entity, PERSON, was_transferred_from); + event.removeAllSourceRelations(was_transferred_from, REPOSITORY); + }else{ + event.replaceSourceRelation(repositoryFromLo.entity, REPOSITORY, was_transferred_from); + event.removeAllSourceRelations(was_transferred_from, PERSON); + } + + // EVENT -> was_transferred_to -> PERSON/REPOSITORY + if(isSelectedPersonTo()){ + event.replaceSourceRelation(personToLo.entity, PERSON, was_transferred_to); + event.removeAllSourceRelations(was_transferred_to, REPOSITORY); + }else{ + event.replaceSourceRelation(repositoryToLo.entity, REPOSITORY, was_transferred_to); + event.removeAllSourceRelations(was_transferred_to, PERSON); + } + + // EVENT -> has_original_location -> PLACE/REPOSITORY + if(isSelectedPlaceOriginalLocation()){ + event.replaceSourceRelation(placeOriginalLocationLo.entity, PLACE, has_original_location); + event.removeAllSourceRelations(has_original_location, REPOSITORY); + }else{ + event.replaceSourceRelation(repositoryOriginalLocationLo.entity, REPOSITORY, has_original_location); + event.removeAllSourceRelations(has_original_location, PLACE); + } + + // EVENT -> has_new_location -> PLACE/REPOSITORY + if(isSelectedPlaceNewLocation()){ + event.replaceSourceRelation(placeNewLocationLo.entity, PLACE, has_new_location); + event.removeAllSourceRelations(has_new_location, REPOSITORY); + }else{ + event.replaceSourceRelation(repositoryNewLocationLo.entity, REPOSITORY, has_new_location); + event.removeAllSourceRelations(has_new_location, PLACE); + } + + // EVENT -> was_transferred_in -> PLACE + event.replaceSourceRelation(placeLo.entity, PLACE, was_transferred_in); + + getWrapper().saveEntity(event, getSessionUserName()); + + printSuccessSavingEntity(); + + }catch (Exception e) { + addGeneralMsg(e.getMessage()); + logger.error(e.getMessage(), e); + } + saveEnd(); + return null; + } + + public boolean checkConsistency(){ + //TODO + if(this.witness == null || this.textLo.entity == null ){ + return false; + } + return true; + } + + + + public boolean isSelectedPersonFrom() { + return selectedPersonFrom; + } + + public boolean isSelectedPersonTo() { + return selectedPersonTo; + } + + public List<SelectItem> getSuggestedTransferOptions() { + return suggestedTransferOptions; + } + + public void setSuggestedTransferOptions( + List<SelectItem> suggestedTransferOptions) { + this.suggestedTransferOptions = suggestedTransferOptions; + } + + public boolean isSelectedPlaceOriginalLocation() { + return selectedPlaceOriginalLocation; + } + + + + public boolean isSelectedPlaceNewLocation() { + return selectedPlaceNewLocation; + } + + public ListenerObject getPersonFromLo() { + return personFromLo; + } + + public void setPersonFromLo(ListenerObject personFromLo) { + this.personFromLo = personFromLo; + } + + public ListenerObject getRepositoryFromLo() { + return repositoryFromLo; + } + + public void setRepositoryFromLo(ListenerObject repositoryFromLo) { + this.repositoryFromLo = repositoryFromLo; + } + + public ListenerObject getPersonToLo() { + return personToLo; + } + + public void setPersonToLo(ListenerObject personToLo) { + this.personToLo = personToLo; + } + + public ListenerObject getRepositoryToLo() { + return repositoryToLo; + } + + public void setRepositoryToLo(ListenerObject repositoryToLo) { + this.repositoryToLo = repositoryToLo; + } + + public ListenerObject getPlaceOriginalLocationLo() { + return placeOriginalLocationLo; + } + + public void setPlaceOriginalLocationLo(ListenerObject placeOriginalLocationLo) { + this.placeOriginalLocationLo = placeOriginalLocationLo; + } + + public ListenerObject getRepositoryOriginalLocationLo() { + return repositoryOriginalLocationLo; + } + + public void setRepositoryOriginalLocationLo( + ListenerObject repositoryOriginalLocationLo) { + this.repositoryOriginalLocationLo = repositoryOriginalLocationLo; + } + + public ListenerObject getPlaceNewLocationLo() { + return placeNewLocationLo; + } + + public void setPlaceNewLocationLo(ListenerObject placeNewLocationLo) { + this.placeNewLocationLo = placeNewLocationLo; + } + + public ListenerObject getRepositoryNewLocationLo() { + return repositoryNewLocationLo; + } + + public void setRepositoryNewLocationLo(ListenerObject repositoryNewLocationLo) { + this.repositoryNewLocationLo = repositoryNewLocationLo; + } + + public void setSelectedPersonFrom(boolean selectedPersonFrom) { + this.selectedPersonFrom = selectedPersonFrom; + } + + public void setSelectedPersonTo(boolean selectedPersonTo) { + this.selectedPersonTo = selectedPersonTo; + } + + public void setSelectedPlaceOriginalLocation( + boolean selectedPlaceOriginalLocation) { + this.selectedPlaceOriginalLocation = selectedPlaceOriginalLocation; + } + + public void setSelectedPlaceNewLocation(boolean selectedPlaceNewLocation) { + this.selectedPlaceNewLocation = selectedPlaceNewLocation; + } + + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/jsf/DelegatingNavigationHandlerProxy.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,171 @@ +package de.mpiwg.itgroup.ismi.jsf; + +import java.io.IOException; + +import javax.faces.FacesException; +import javax.faces.application.NavigationCase; +import javax.faces.application.NavigationHandler; +import javax.faces.application.ViewHandler; +import javax.faces.component.UIViewRoot; +import javax.faces.context.ExternalContext; +import javax.faces.context.FacesContext; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.repository.bo.Entity; + +import com.sun.faces.application.NavigationHandlerImpl; + +import de.mpiwg.itgroup.ismi.browse.EntityDetailsBean; +import de.mpiwg.itgroup.ismi.browse.EntityRepositoryBean; +import de.mpiwg.itgroup.ismi.entry.beans.SessionBean; +import de.mpiwg.itgroup.ismi.search.beans.SimpleSearchBean; + +public class DelegatingNavigationHandlerProxy extends NavigationHandlerImpl { + + NavigationHandler _base; + + public DelegatingNavigationHandlerProxy(NavigationHandler base) { + super(); + _base = base; + } + + private EntityRepositoryBean getEntityRepository(FacesContext context) { + EntityRepositoryBean bean = (EntityRepositoryBean) context + .getExternalContext().getSessionMap().get("EntityRepository"); + if (bean == null) { + bean = new EntityRepositoryBean(); + context.getExternalContext().getSessionMap() + .put("EntityRepository", bean); + } + return bean; + } + + private SessionBean getSessionBean(FacesContext context) { + SessionBean bean = (SessionBean) context.getExternalContext() + .getSessionMap().get("Session"); + if (bean == null) { + bean = new SessionBean(); + context.getExternalContext().getSessionMap().put("Session", bean); + } + return bean; + } + + @Override + public void handleNavigation(FacesContext facesContext, String fromAction, + String outcome) { + if (outcome == null) { + // stay on current ViewRoot + return; + } + NavigationCase navigationCase = getNavigationCase(facesContext, fromAction, outcome); + if (navigationCase != null) { + if (navigationCase.isRedirect() + /*&& (!PortletUtil.isPortletRequest(facesContext))*/) { + ExternalContext externalContext = facesContext + .getExternalContext(); + ViewHandler viewHandler = facesContext.getApplication() + .getViewHandler(); + String redirectPath = viewHandler.getActionURL(facesContext, + navigationCase.getToViewId(facesContext)); + + try { + + if (outcome.equals("entity_repository")) { + EntityRepositoryBean bean = getEntityRepository(facesContext); + if(EntityRepositoryBean.MODE_ALL.equals(bean.getResultMode())){ + redirectPath += "?oc=" + + bean.getObjectClass() + + "&resultMode=" + + bean.getResultMode() + + "&cpage="; + + if(EntityRepositoryBean.MODE_ALL.equals(bean.getResultMode())){ + redirectPath += (bean.getPaginator().getCurrentPage() + 1); + }else if(EntityRepositoryBean.MODE_ADVANCED.equals(bean.getResultMode())){ + //redirectPath += bean.getCurrentPageAdvancedSearch(); + }else{ + redirectPath += 0; + } + } + + } else if(outcome.equals("entity_details")){ + EntityDetailsBean bean = (EntityDetailsBean) facesContext.getExternalContext().getSessionMap().get("EntityDetails"); + if(bean == null){ + bean = new EntityDetailsBean(); + facesContext.getExternalContext().getSessionMap().put("EntityDetails", bean); + } + if(StringUtils.isNotEmpty(bean.getCurrentEntityId())){ + redirectPath += "?eid=" + bean.getCurrentEntityId(); + } + } else if(outcome.equals("simple_seach")){ + /* + SimpleSearchBean bean = (SimpleSearchBean) facesContext.getExternalContext().getSessionMap().get("SimpleSearch"); + redirectPath += "?term=" + + bean.getSearchTerm() + + "&md=" + + bean.getSelectedMode(); + */ + } else if(outcome.equals("display_title") || outcome.equals("display_author")){ + //Entity bean = (Entity) facesContext.getExternalContext().getRequestMap().get("entity"); + //redirectPath += "?eid=" + bean.getId(); + } else if(outcome.equals("entry_edit_entity")){ + SessionBean session = (SessionBean) facesContext.getExternalContext().getSessionMap().get("Session"); + if(session != null){ + redirectPath += "?formIndex=" + session.getSelectedTab(); + Long entId = session.getEditFormCurrentEntId(); + if(entId != null && entId != 0){ + redirectPath += "&eid=" + entId; + } + } + } + externalContext.redirect(externalContext.encodeActionURL(redirectPath)); + + } catch (IOException e) { + throw new FacesException(e.getMessage(), e); + } + } else { + ViewHandler viewHandler = facesContext.getApplication() + .getViewHandler(); + // create new view + String newViewId = navigationCase.getToViewId(facesContext); + UIViewRoot viewRoot = viewHandler.createView(facesContext, + newViewId); + facesContext.setViewRoot(viewRoot); + facesContext.renderResponse(); + } + } else { + // no navigationcase found, stay on current ViewRoot + } + } + + /* + * @Override public void handleNavigation(FacesContext fc, String + * currentMethod, String currentAction) { /* + * System.out.println("currentMethod: " + currentMethod + + * " currentAction: " + currentAction); System.out.println(); + * System.out.println(); for(String key : + * fc.getViewRoot().getAttributes().keySet()){ System.out.println(key + "/t" + * + fc.getViewRoot().getAttributes().get(key)); } + * System.out.println();System.out.println(); + * + * if(new String("simple_search").equals(currentAction)){ String path = + * getViewId(fc, "", currentAction) + "?chao=chao"; + * System.out.println("fc.getViewRoot().getViewId(); " + + * fc.getViewRoot().getViewId()); //fc.getViewRoot().setViewId(path); + * fc.getViewRoot().setViewId("/entry/login.jsp"); + * + * }else{ + * + * } _base.handleNavigation(fc, currentMethod, currentAction); } + */ + + /* + public String getViewId(FacesContext context, String fromAction, + String outcome) { + String view = super.getViewId(context, fromAction, outcome); + System.out.println("VIEW: " + view); + return view; + + }*/ + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/jsf/PhaseTracker.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,140 @@ +package de.mpiwg.itgroup.ismi.jsf; + +import java.util.Map; + +import javax.faces.context.FacesContext; +import javax.faces.event.PhaseEvent; +import javax.faces.event.PhaseId; +import javax.faces.event.PhaseListener; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpServletResponseWrapper; + +import org.apache.commons.lang.StringUtils; + +import de.mpiwg.itgroup.ismi.entry.beans.SessionBean; + +public class PhaseTracker implements PhaseListener { + + private static final long serialVersionUID = -1L; + + public void beforePhase(PhaseEvent event) { + + Map<String, String> parameters = event.getFacesContext().getExternalContext().getRequestParameterMap(); + + String servletPath = event.getFacesContext().getExternalContext().getRequestServletPath(); + + if(StringUtils.isNotEmpty(servletPath) && event.getPhaseId() == PhaseId.RESTORE_VIEW){ + + if(StringUtils.endsWith(parameters.get("login"), "true")){ + getSessionBean(event.getFacesContext()).listenerDisplayLoginDialog(null); + } + + if(servletPath.equals("/browse/entityDetails.xhtml")){ + String entityId = parameters.get("eid"); + if(StringUtils.isNotEmpty(entityId)){ + setIdToEntityDetails(event.getFacesContext(), entityId); + } + } else if(servletPath.equals("/browse/entityRepository.xhtml")){ + //setEntityRepositoryState(parameters, event.getFacesContext()); + + } else if(servletPath.equals("/search/simpleSearch.xhtml")){ + //String term = parameters.get("term"); + //String mode = parameters.get("md"); + //getSessionBean(event.getFacesContext()).setSimpleSearchState(term, mode); + } else if(servletPath.equals("/search/displayAuthor.xhtml")){ + String personId = parameters.get("personId"); + String textId = parameters.get("textId"); + String witnessId = parameters.get("witnessId"); + + if(StringUtils.isNotEmpty(personId)){ + getSessionBean(event.getFacesContext()).displayAuthorSetPerson(personId); + if(StringUtils.isNotEmpty(textId)){ + getSessionBean(event.getFacesContext()).displayAuthorSetTitle(textId); + if(StringUtils.isNotEmpty(witnessId)){ + getSessionBean(event.getFacesContext()).displayAuthorSetWitness(witnessId); + } + } + }else if(StringUtils.isNotEmpty(textId)){ + getSessionBean(event.getFacesContext()).displayAuthorFromTitles(textId); + if(StringUtils.isNotEmpty(witnessId)){ + getSessionBean(event.getFacesContext()).displayAuthorSetWitness(witnessId); + } + }else if(StringUtils.isNotEmpty(witnessId)){ + getSessionBean(event.getFacesContext()).displayAuthorFromWitness(witnessId); + } + + + }else if(servletPath.equals("/search/displayTitle.xhtml")){ + String textId = parameters.get("textId"); + String witnessId = parameters.get("witnessId"); + if(StringUtils.isNotEmpty(textId)){ + getSessionBean(event.getFacesContext()).displayTitleSetTitle(textId); + if(StringUtils.isNotEmpty(witnessId)){ + getSessionBean(event.getFacesContext()).displayTitleSetWitness(witnessId); + } + }else if(StringUtils.isNotEmpty(witnessId)){ + getSessionBean(event.getFacesContext()).displayTitleFromWitness(witnessId); + } + }else if(servletPath.equals("/entry/createEntity.xhtml")){ + String entityId = parameters.get("eid"); + String formIndex = parameters.get("formIndex"); + if(StringUtils.isEmpty(entityId) && StringUtils.isNotEmpty(formIndex)){ + //set tabIndex + getSessionBean(event.getFacesContext()).setSelectedTab(formIndex); + }else if(StringUtils.isNotEmpty(entityId) && !entityId.equals("0")){ + //set entity to edit + getSessionBean(event.getFacesContext()).editEntity(entityId); + } + }else if(servletPath.equals("/public/dynamicPage.xhtml")){ + String entId = parameters.get("eid"); + if(StringUtils.isNotEmpty(entId)){ + getSessionBean(event.getFacesContext()).getDynamicPage().load(entId); + } + + }else if(servletPath.equals("/public/publicCodexOverview.xhtml")){ + String entId = parameters.get("eid"); + if(StringUtils.isNotEmpty(entId)){ + getSessionBean(event.getFacesContext()).getPublicCodexView().load(entId); + } + + }/* else if(servletPath.equals("/entry/geonameForm.xhtml")){ + } + String placeId = parameters.get("placeId"); + if(StringUtils.isNotEmpty(placeId)){ + getSessionBean(event.getFacesContext()).setPlaceInGeoForm(placeId); + } + }*/ + } + } + + + private SessionBean getSessionBean(FacesContext context){ + SessionBean bean = (SessionBean)context.getExternalContext().getSessionMap().get("Session"); + if(bean == null){ + bean = new SessionBean(); + context.getExternalContext().getSessionMap().put("Session", bean); + } + return bean; + } + + private void setIdToEntityDetails(FacesContext context, String id){ + getSessionBean(context).setIdEntityDetails(id); + } + + + + + public void afterPhase(PhaseEvent event) { + } + + public PhaseId getPhaseId() { + return PhaseId.ANY_PHASE; + } + + + class PrettyUrlResponseWrapper extends HttpServletResponseWrapper { + public PrettyUrlResponseWrapper(HttpServletResponse response) { + super(response); + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/jsf/exceptions/MyExceptionHandler.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,70 @@ +package de.mpiwg.itgroup.ismi.jsf.exceptions; + +import java.util.Iterator; + +import javax.faces.FacesException; +import javax.faces.application.ViewExpiredException; +import javax.faces.context.ExceptionHandler; +import javax.faces.context.ExceptionHandlerWrapper; +import javax.faces.context.ExternalContext; +import javax.faces.context.FacesContext; +import javax.faces.event.ExceptionQueuedEvent; +import javax.faces.event.ExceptionQueuedEventContext; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; + +public class MyExceptionHandler extends ExceptionHandlerWrapper{ + + private static Logger logger = Logger.getLogger(MyExceptionHandler.class); + + private ExceptionHandler wrapped; + + public MyExceptionHandler(ExceptionHandler wrapped) { + this.wrapped = wrapped; + } + + public javax.faces.context.ExceptionHandler getWrapped() { + return wrapped; + } + + public void handle() throws FacesException { + Iterator<ExceptionQueuedEvent> events = getUnhandledExceptionQueuedEvents().iterator(); + + //Iterate through the queued exceptions + while (events.hasNext()) { + ExceptionQueuedEvent event = (ExceptionQueuedEvent) events.next(); + ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource(); + Throwable t = context.getException(); + + //See if it's an exception I'm interested in + if (t instanceof ViewExpiredException) { + try { + + String path = getContextPath(); + logger.info("ViewExpiredException detected. Redirecting to " + path); + + ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext(); + ctx.redirect(path); + + } catch (Exception e){ + logger.error(e.getMessage(), e); + } finally { + //remove it if you processed it + events.remove(); + } + } + + //Let the next ExceptionHandler(s) deal with the others + getWrapped().handle(); + } + } + + public String getContextPath(){ + HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); + String port = (StringUtils.equals(request.getLocalPort() + "", "80")) ? "" : (":" + request.getLocalPort()); + String path = request.getScheme() + "://" + request.getLocalName() + port + request.getContextPath(); + return path; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/jsf/exceptions/MyExceptionHandlerFactory.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,17 @@ +package de.mpiwg.itgroup.ismi.jsf.exceptions; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.ExceptionHandlerFactory; + +public class MyExceptionHandlerFactory extends ExceptionHandlerFactory { + + ExceptionHandlerFactory delegateFactory; + + public MyExceptionHandlerFactory(ExceptionHandlerFactory delegateFactory) { + this.delegateFactory = delegateFactory; + } + + public ExceptionHandler getExceptionHandler() { + return new MyExceptionHandler(delegateFactory.getExceptionHandler()); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/json/utils/JSONUtils.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,401 @@ +package de.mpiwg.itgroup.ismi.json.utils; + +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +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.utils.RomanizationLoC; + +public class JSONUtils { + + private static Logger logger = Logger.getLogger(JSONUtils.class); + + //data structure + public static String ENT = "ent"; + public static String SRC_RELS = "src_rels"; + public static String TAR_RELS = "tar_rels"; + public static String ATTS = "atts"; + public static String OV = "ov"; + public static String NOV = "nov"; + public static String LW = "lw"; + public static String ID = "id"; + public static String OC = "oc"; + public static String NODE_TYPE = "node_type"; + public static String NAME = "name"; + public static String CONTENT_TYPE = "content_type"; + public static String SRC_ID = "src_id"; + public static String SRC_OC = "src_oc"; + public static String TAR_ID = "tar_id"; + public static String TAR_OC = "tar_oc"; + public static String SRC = "src"; + public static String TAR = "tar"; + public static String POSSIBLE_VALUES = "possible_values"; + public static String ROMANIZATION = "romanization"; + + //methods + public static String METHOD = "method"; + public static String M_GET_ENT = "get_ent"; + public static String M_GET_ENTS= "get_ents"; + public static String M_GET_ENTS_SIZE = "get_ents_size"; + public static String M_GET_DEF = "get_def"; + public static String M_GET_DEFS = "get_defs"; + public static String M_GET_SRC_RELS = "get_src_rels"; + public static String M_GET_TAR_RELS = "get_tar_rels"; + public static String M_GET_ATTS = "get_atts"; + public static String M_GET_TARS_4_SRC_REL = "get_tars_4_src_rel"; + public static String M_GET_SRCS_4_TAR_REL = "get_srcs_4_tar_rel"; + public static String M_EXIST_RELATION = "exist_rel"; + public static String M_GET_RELS = "get_rels"; + public static String M_SEARCH = "search"; + public static String M_GET_PUBLIC_CODICES = "get_public_codices"; + public static String M_WITNESSES_4_CODEX = "get_witnisses_4_codex"; + + //parameters + public static String P_METHOD = "method"; + public static String P_MR = "max_results"; + public static String P_INCLUDE = "include_content"; + public static String P_DEPTH = "depth"; + public static String P_ID = "id"; + public static String P_MPIWGID = "mpiwg_id"; + public static String P_IDS = "ids"; + public static String P_OC = "oc"; + public static String P_REL_NAME = "rel_name"; + public static String P_SRC_OC = "src_oc"; + public static String P_TAR_OC = "tar_oc"; + public static String P_SRC_ID = "src_id"; + public static String P_TAR_ID = "tar_id"; + public static String P_INCL_ENTS = "include_ents"; + public static String P_INCL_ROMANIZATION = "include_romanization"; + + //returns + public static String R_ENTS = "ents"; + public static String R_DEF = "def"; + public static String R_DEFS = "defs"; + public static String R_ENTS_SIZE = "ents_size"; + public static String R_ATTS = "att_array"; + public static String R_RELS = "rels"; + public static String R_RELS_SIZE = "rels_size"; + public static String R_SRC_RELS = "src_rels"; + public static String R_TAR_RELS = "tar_rels"; + public static String R_EXIST_REL = "exist_rel"; + + public static JSONObject entityToJSON( + Entity entity, + List<Attribute> attList, + List<Relation> srcList, + List<Relation> tarList, + boolean includeRomanization) throws JSONException{ + + JSONObject json = entityToJSON(entity, includeRomanization); + + JSONArray attArray = new JSONArray(); + for(Attribute att : attList){ + if(StringUtils.isNotEmpty(att.getOwnValue())){ + attArray.put(attributeToJSON(att, includeRomanization)); + } + } + json.put(ATTS, attArray); + + JSONArray srcRel = new JSONArray(); + for(Relation rel : srcList){ + srcRel.put(relationToJSON(rel, includeRomanization)); + } + json.put(SRC_RELS, srcRel); + + JSONArray tarRel = new JSONArray(); + for(Relation rel : tarList){ + tarRel.put(relationToJSON(rel, includeRomanization)); + } + json.put(TAR_RELS, tarRel); + + return json; + } + + public static JSONObject entityToJSONWithAtts(Entity entity, List<Attribute> atts, boolean includeRomanization) throws JSONException{ + JSONObject json = new JSONObject(); + + json.put(OV, entity.getOwnValue()); + json.put(NOV, entity.getNormalizedOwnValue()); + json.put(LW, true); + json.put(ID, entity.getId()); + json.put(OC, entity.getObjectClass()); + json.put(NODE_TYPE, entity.getType()); + + JSONArray attArray = new JSONArray(); + for(Attribute att : atts){ + if(StringUtils.isNotEmpty(att.getOwnValue())){ + attArray.put(attributeToJSON(att, includeRomanization)); + } + } + json.put(ATTS, attArray); + return json; + } + + public static JSONObject entityToJSON(Entity entity, int depth, WrapperService ws, boolean includeRomanization) throws JSONException{ + JSONObject json = new JSONObject(); + + json.put(OV, entity.getOwnValue()); + json.put(NOV, entity.getNormalizedOwnValue()); + json.put(LW, entity.isLightweight()); + json.put(ID, entity.getId()); + json.put(OC, entity.getObjectClass()); + json.put(NODE_TYPE, entity.getType()); + + + if(!entity.isLightweight()){ + JSONArray attArray = new JSONArray(); + for(Attribute att : entity.getAttributes()){ + if(StringUtils.isNotEmpty(att.getOwnValue())){ + attArray.put(attributeToJSON(att, includeRomanization)); + } + } + json.put(ATTS, attArray); + + JSONArray srcRel = new JSONArray(); + for(Relation rel : entity.getSourceRelations()){ + srcRel.put(relationToJSON(rel, depth, ws, includeRomanization)); + } + json.put(SRC_RELS, srcRel); + + JSONArray tarRel = new JSONArray(); + for(Relation rel : entity.getTargetRelations()){ + tarRel.put(relationToJSON(rel, depth, ws, includeRomanization)); + } + json.put(TAR_RELS, tarRel); + } + + return json; + } + + public static Entity jsonToEntity(JSONObject json) throws JSONException{ + Entity ent = new Entity(); + + ent.setOwnValue(json.getString(OV)); + ent.setNormalizedOwnValue(json.getString(NOV)); + ent.setLightweight(json.getBoolean(LW)); + ent.setId(json.getLong(ID)); + ent.setObjectClass(json.getString(OC)); + ent.setType(json.getString(NODE_TYPE)); + + if(json.has(ATTS)){ + JSONArray jsonAtts = json.getJSONArray(ATTS); + for(int i=0; i<jsonAtts.length(); i++){ + ent.getAttributes().add(jsonToAttribute(jsonAtts.getJSONObject(i))); + } + } + + if(json.has(SRC_RELS)){ + JSONArray srcRels = json.getJSONArray(SRC_RELS); + for(int i=0; i<srcRels.length(); i++){ + //TODO ent.getSourceRelations().add(e); + } + } + + if(json.has(TAR_RELS)){ + JSONArray tarRels = json.getJSONArray(TAR_RELS); + for(int i=0; i<tarRels.length(); i++){ + //TODO ent.getTargetRelations().add(e); + } + } + + return ent; + } + + public static JSONObject entityToJSON(Entity entity, boolean includeRomanization) throws JSONException{ + JSONObject json = new JSONObject(); + + json.put(OV, entity.getOwnValue()); + json.put(NOV, entity.getNormalizedOwnValue()); + json.put(LW, entity.isLightweight()); + json.put(ID, entity.getId()); + json.put(OC, entity.getObjectClass()); + json.put(NODE_TYPE, entity.getType()); + if(includeRomanization){ + json.put(ROMANIZATION, RomanizationLoC.convert(entity.getOwnValue())); + } + + + if(!entity.isLightweight()){ + JSONArray attArray = new JSONArray(); + for(Attribute att : entity.getAttributes()){ + if(StringUtils.isNotEmpty(att.getOwnValue())){ + attArray.put(attributeToJSON(att, includeRomanization)); + } + } + json.put(ATTS, attArray); + + JSONArray srcRel = new JSONArray(); + for(Relation rel : entity.getSourceRelations()){ + srcRel.put(relationToJSON(rel, includeRomanization)); + } + json.put(SRC_RELS, srcRel); + + JSONArray tarRel = new JSONArray(); + for(Relation rel : entity.getTargetRelations()){ + tarRel.put(relationToJSON(rel, includeRomanization)); + } + json.put(TAR_RELS, tarRel); + } + + return json; + } + + public static JSONObject attributeToJSON(Attribute att, boolean includeRomanization) throws JSONException{ + JSONObject json = new JSONObject(); + + json.put(NAME, att.getName()); + json.put(OV, att.getOwnValue()); + json.put(NOV, att.getNormalizedOwnValue()); + json.put(SRC_ID, att.getSourceId()); + json.put(ID, att.getId()); + json.put(CONTENT_TYPE, att.getContentType()); + json.put(NODE_TYPE, att.getType()); + json.put(POSSIBLE_VALUES, att.getPossibleValues()); + if(includeRomanization){ + json.put(ROMANIZATION, RomanizationLoC.convert(att.getOwnValue())); + } + + return json; + } + + public static Attribute jsonToAttribute(JSONObject json) throws JSONException{ + + Attribute att = new Attribute(); + + att.setName(json.getString(NAME)); + + if(json.has(OV)) + att.setOwnValue(json.getString(OV)); + + if(json.has(NOV)) + att.setNormalizedOwnValue(json.getString(NOV)); + + att.setSourceId(json.getLong(SRC_ID)); + att.setId(json.getLong(ID)); + att.setContentType(json.getString(CONTENT_TYPE)); + att.setType(json.getString(NODE_TYPE)); + if(json.has(POSSIBLE_VALUES)) + att.setPossibleValues(json.getString(POSSIBLE_VALUES)); + + return att; + } + + public static JSONObject relationToJSON(Relation rel, + Entity src, + Entity tar, + List<Attribute> srcAtts, + List<Attribute> tarAtts, + boolean includeRomanization) throws JSONException{ + + JSONObject json = new JSONObject(); + + json.put(NAME, rel.getOwnValue()); + json.put(ID, rel.getId()); + + json.put(SRC_ID, rel.getSourceId()); + json.put(SRC_OC, rel.getSourceObjectClass()); + + json.put(TAR_ID, rel.getTargetId()); + json.put(TAR_OC, rel.getTargetObjectClass()); + + json.put(SRC, entityToJSONWithAtts(src, srcAtts, includeRomanization)); + json.put(TAR, entityToJSONWithAtts(tar, tarAtts, includeRomanization)); + + JSONArray attArray = new JSONArray(); + for(Attribute att : rel.getAttributes()){ + attArray.put(attributeToJSON(att, includeRomanization)); + } + json.put(ATTS, attArray); + + return json; + } + + + public static JSONObject relationToJSON(Relation rel, boolean includeRomanization) throws JSONException{ + JSONObject json = new JSONObject(); + + json.put(NAME, rel.getOwnValue()); + json.put(ID, rel.getId()); + + json.put(SRC_ID, rel.getSourceId()); + json.put(SRC_OC, rel.getSourceObjectClass()); + + json.put(TAR_ID, rel.getTargetId()); + json.put(TAR_OC, rel.getTargetObjectClass()); + + JSONArray attArray = new JSONArray(); + for(Attribute att : rel.getAttributes()){ + if(StringUtils.isNotEmpty(att.getOwnValue())){ + attArray.put(attributeToJSON(att, includeRomanization)); + } + } + json.put(ATTS, attArray); + + return json; + } + + public static JSONObject relationToJSON(Relation rel, int depth, WrapperService ws, boolean includeRomanization) throws JSONException{ + JSONObject json = new JSONObject(); + + json.put(NAME, rel.getOwnValue()); + json.put(ID, rel.getId()); + + json.put(SRC_ID, rel.getSourceId()); + json.put(SRC_OC, rel.getSourceObjectClass()); + + json.put(TAR_ID, rel.getTargetId()); + json.put(TAR_OC, rel.getTargetObjectClass()); + + if(depth > 0){ + Entity src = ws.getEntityByIdWithContent(rel.getSourceId()); + Entity tar = ws.getEntityByIdWithContent(rel.getTargetId()); + if(src != null && tar != null){ + json.put(SRC, entityToJSON(src, depth - 1, ws, includeRomanization)); + json.put(TAR, entityToJSON(tar, depth - 1, ws, includeRomanization)); + }else{ + try { + throw new Exception("Inconsistency. Relation has either no source or target. " + rel.toString()); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + } + } + + JSONArray attArray = new JSONArray(); + for(Attribute att : rel.getAttributes()){ + if(StringUtils.isNotEmpty(att.getOwnValue())){ + attArray.put(attributeToJSON(att, includeRomanization)); + } + } + json.put(ATTS, attArray); + + return json; + } + + public static boolean getBoolean(JSONObject json, String name){ + try { + if(json.has(name)){ + return json.getBoolean(name); + } + } catch (Exception e) { + } + return false; + } + + public static String getString(JSONObject json, String name){ + try { + if(json.has(name)){ + return json.getString(name); + } + } catch (Exception e) { + } + return ""; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/merge/GeneralMerge.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,587 @@ +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 javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +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 de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; + +public class GeneralMerge extends AbstractISMIBean implements Serializable{ + + private static Logger logger = Logger.getLogger(GeneralMerge.class); + + private static final long serialVersionUID = 1L; + public static String FIRST_VALUE = "first value"; + public static String SECOND_VALUE = "second value"; + public static String IGNORE = "ignore"; + public static String TAKE = "take"; + + private boolean showAttributeMapping = false; + private boolean showSrcRelationMapping = false; + private boolean showTarRelationMapping = false; + + private boolean entitiesLoaded = false; + + private Map<String, String> firstAttMap = new HashMap<String, String>(); + private Map<String, String> secondAttMap = new HashMap<String, String>(); + + private Entity firstEntity; + private Entity secondEntity; + + private String firstId; + private String secondId; + + private Entity entResult; + private List<Attribute> resultAtts; + private List<Relation> resultSrcRels; + private List<Relation> resultTarRels; + + private List<String> attLabels; + private Map<String, String> selectedAtts; + + Map<Long, String> selectedFirstSrcRelations; + Map<Long, String> selectedSecondSrcRelations; + Map<Long, String> selectedFirstTarRelations; + Map<Long, String> selectedSecondTarRelations; + + public GeneralMerge(){} + + public void loadFirstEntity(ActionEvent event){ + reset(); + try{ + Long id = new Long(this.firstId); + this.firstEntity = getWrapper().getEntityById(id); + if(this.firstEntity == null){ + addErrorMsg("Entity no found."); + } + else{ + if(this.secondEntity != null){ + if(this.firstEntity.getObjectClass().equals(this.secondEntity.getObjectClass())){ + this.deployDifferences(); + }else{ + addErrorMsg("The class of the first entity is: " + firstEntity.getObjectClass() + + " and class of the second one is: " + secondEntity.getObjectClass() +". They must be equal!"); + } + } + } + }catch(Exception e){ + addErrorMsg("The first entity could no be loaded."); + } + } + + public void loadSecondEntity(ActionEvent event){ + reset(); + try{ + Long id = new Long(this.secondId); + this.secondEntity = getWrapper().getEntityById(id); + if(this.secondEntity == null){ + addErrorMsg("Entity no found."); + } + else{ + if(this.firstEntity != null){ + if(this.firstEntity.getObjectClass().equals(this.secondEntity.getObjectClass())){ + this.deployDifferences(); + }else{ + addErrorMsg("The class of the first entity is: " + firstEntity.getObjectClass() + + " and class of the second one is: " + secondEntity.getObjectClass() +". They must be equal"); + } + + } + } + }catch(Exception e){ + addErrorMsg( "The second entity could no be loaded."); + } + } + + @Override + public void reset(){ + this.attLabels = new ArrayList<String>(); + this.selectedAtts = new HashMap<String, String>(); + this.selectedFirstSrcRelations = new HashMap<Long, String>(); + this.selectedSecondSrcRelations = new HashMap<Long, String>(); + this.selectedFirstTarRelations = new HashMap<Long, String>(); + this.selectedSecondTarRelations = new HashMap<Long, String>(); + this.entResult = null; + + this.entitiesLoaded = false; + this.showAttributeMapping = false; + this.showSrcRelationMapping = false; + this.showTarRelationMapping = false; + } + + public void listenerExecuteMerge(){ + this.executeMerge(); + getAppBean().getSimpleSearchCache().setMapDirty(true); + } + + private void deployDifferences(){ + this.showAttributeMapping = true; + this.showSrcRelationMapping = true; + this.showTarRelationMapping = true; + this.entitiesLoaded = true; + if(this.firstEntity != null && this.secondEntity != null){ + if(firstEntity.isLightweight()){ + this.firstEntity = getWrapper().getEntityContent(this.firstEntity); + } + if(secondEntity.isLightweight()){ + this.secondEntity = getWrapper().getEntityContent(this.secondEntity); + } + + this.firstEntity = (Entity)firstEntity.clone(); + this.secondEntity = (Entity) secondEntity.clone(); + + //attributes + this.attLabels = new ArrayList<String>(); + this.selectedAtts = new HashMap<String, String>(); + this.firstAttMap = new HashMap<String, String>(); + this.secondAttMap = new HashMap<String, String>(); + + for(Attribute att : this.firstEntity.getAttributes()){ + firstAttMap.put(att.getName(), att.getValue()); + if(!attLabels.contains(att.getName())){ + attLabels.add(att.getName()); + selectedAtts.put(att.getName(), FIRST_VALUE); + } + } + + for(Attribute att : this.secondEntity.getAttributes()){ + secondAttMap.put(att.getName(), att.getValue()); + if(!attLabels.contains(att.getName())){ + attLabels.add(att.getName()); + selectedAtts.put(att.getName(), FIRST_VALUE); + } + } + + //source relations + this.selectedFirstSrcRelations = new HashMap<Long, String>(); + this.selectedSecondSrcRelations = new HashMap<Long, String>(); + + for(Relation rel : this.firstEntity.getSourceRelations()){ + rel.setTarget(getWrapper().getEntityById(rel.getTargetId())); + selectedFirstSrcRelations.put(rel.getId(), TAKE); + } + + + for(Relation rel : this.secondEntity.getSourceRelations()){ + rel.setTarget(getWrapper().getEntityById(rel.getTargetId())); + selectedSecondSrcRelations.put(rel.getId(), TAKE); + } + + //target relations + this.selectedFirstTarRelations = new HashMap<Long, String>(); + this.selectedSecondTarRelations = new HashMap<Long, String>(); + + for(Relation rel : this.firstEntity.getTargetRelations()){ + rel.setSource(getWrapper().getEntityById(rel.getSourceId())); + selectedFirstTarRelations.put(rel.getId(), TAKE); + } + + for(Relation rel : this.secondEntity.getTargetRelations()){ + rel.setSource(getWrapper().getEntityById(rel.getSourceId())); + selectedSecondTarRelations.put(rel.getId(), TAKE); + } + + + } + } + + public void preview(ActionEvent event){ + this.generateResultEntity(); + } + + private void executeMerge(){ + + logger.info("Starting merge execution " + firstEntity.getObjectClass() + + " ["+ getUserName() +"]" + + "[firstEntity=" + firstEntity.getId() + + ", secondEntity=" + secondEntity.getId() + "]"); + + try { + this.generateResultEntity(); + if(this.entResult != null){ + + this.printMergeInfo(entResult); + + this.getWrapper().saveEntity(this.entResult, getSessionUser().getEmail() + "_merge"); + + this.getWrapper().removeCurrentVersionEntity(this.firstEntity); + this.getWrapper().removeCurrentVersionEntity(this.secondEntity); + + //the old relations should be removed, before... + this.generateSecundaryOW(this.entResult, getSessionUser().getEmail() + "_merge"); + + this.printMergeInfo(entResult); + + logger.info("Merge execution 'successful' " + + firstEntity.getObjectClass() + + " ["+ getUserName() +"]" + + "[firstEntity=" + firstEntity.getId() + + ", secondEntity=" + secondEntity.getId() + + ", generatedEntity=" + entResult.getId() + "]"); + + this.firstEntity = null; + this.secondEntity = null; + + addGeneralMsg("The entities were merged successfully"); + addGeneralMsg("The new entity has the id " + this.entResult.getId()); + this.reset(); + } + } catch (Exception e) { + printInternalError(e); + logger.error("["+ getUserName() +"] " + e.getMessage(), e); + } + } + + private void printMergeInfo(Entity ent){ + StringBuilder sb = new StringBuilder("\n\n"); + + sb.append("-------------------------------------------"); + sb.append("-----------------------------------------\n"); + sb.append("Merging result [" + getUserName() + "]\n"); + sb.append(ent.toString() + "\n"); + sb.append("Attributes:\n"); + for(Attribute att : ent.getAttributes()){ + sb.append("\t" + att.toString() + "\n"); + } + + sb.append("Src Relations:\n"); + for(Relation src : ent.getSourceRelations()){ + sb.append("\t" + src.toString() + "\n"); + } + + sb.append("Tar Relations:\n"); + for(Relation tar : ent.getTargetRelations()){ + sb.append("\t" + tar.toString() + "\n"); + } + + sb.append("-------------------------------------------"); + sb.append("-----------------------------------------\n"); + logger.info(sb.toString()); + } + + public void actionShowTarRelationMapping(ActionEvent event){ + this.showTarRelationMapping = true; + } + + public void actionHideTarRelationMapping(ActionEvent event){ + this.showTarRelationMapping = false; + } + + public void actionShowSrcRelationMapping(ActionEvent event){ + this.showSrcRelationMapping = true; + } + + public void actionHideSrcRelationMapping(ActionEvent event){ + this.showSrcRelationMapping = false; + } + + public void actionShowAttributeMapping(ActionEvent event){ + this.showAttributeMapping = true; + } + + public void actionHideAttributeMapping(ActionEvent event){ + this.showAttributeMapping = false; + } + + private void generateResultEntity(){ + this.entResult = new Entity(); + this.entResult.setLightweight(false); + this.entResult.setObjectClass(this.firstEntity.getObjectClass()); + + //generating attributes + try{ + for(String attName : this.selectedAtts.keySet()){ + String selected = this.selectedAtts.get(attName); + String value = ""; + if(selected.equals(FIRST_VALUE)){ + value = (firstEntity.getAttributeByName(attName) == null) ? "" : firstEntity.getAttributeByName(attName).getOwnValue(); + }else if(selected.equals(SECOND_VALUE)){ + value = (secondEntity.getAttributeByName(attName) == null) ? "" : secondEntity.getAttributeByName(attName).getOwnValue(); + } + this.entResult.addAttribute(new Attribute(attName, "text", value)); + } + }catch(Exception e){ + e.printStackTrace(); + addErrorMsg("Please inform support of this exception: " + e.getMessage()); + } + + + //generating source relations + for(Relation rel : firstEntity.getSourceRelations()){ + String selectedValue = this.selectedFirstSrcRelations.get(rel.getId()); + if(StringUtils.isNotEmpty(selectedValue) && selectedValue.equals(TAKE)){ + if(!this.entResult.containsSourceRelation(rel.getOwnValue(), rel.getTargetId())){ + this.entResult.addSourceRelation(generateSrcRelation(rel)); + } + } + } + + for(Relation rel : secondEntity.getSourceRelations()){ + String selectedValue = this.selectedSecondSrcRelations.get(rel.getId()); + if(StringUtils.isNotEmpty(selectedValue) && selectedValue.equals(TAKE)){ + if(!this.entResult.containsSourceRelation(rel.getOwnValue(), rel.getTargetId())){ + this.entResult.addSourceRelation(generateSrcRelation(rel)); + } + } + } + + //generating target relations + for(Relation rel : firstEntity.getTargetRelations()){ + String selectedValue = this.selectedFirstTarRelations.get(rel.getId()); + if(StringUtils.isNotEmpty(selectedValue) && selectedValue.equals(TAKE)){ + //ensuring that there is no two equals relations. + if(!this.entResult.containsTargetRelation(rel.getOwnValue(), rel.getSourceId())){ + this.entResult.addTargetRelation(generateTarRelation(rel)); + } + } + } + + for(Relation rel : secondEntity.getTargetRelations()){ + String selectedValue = this.selectedSecondTarRelations.get(rel.getId()); + if(StringUtils.isNotEmpty(selectedValue) && selectedValue.equals(TAKE)){ + if(!this.entResult.containsTargetRelation(rel.getOwnValue(), rel.getSourceId())){ + this.entResult.addTargetRelation(generateTarRelation(rel)); + } + } + } + } + + private Relation generateSrcRelation(Relation rel){ + + Relation newRel = new Relation(); + newRel.setOwnValue(rel.getOwnValue()); + newRel.setTarget(getWrapper().getEntityById(rel.getTargetId())); + + return newRel; + } + + private Relation generateTarRelation(Relation rel){ + Relation newRel = new Relation(); + newRel.setOwnValue(rel.getOwnValue()); + newRel.setSource(getWrapper().getEntityById(rel.getSourceId())); + return newRel; + } + + public List<SelectItem> getAttSelectItems() { + List<SelectItem> items = new ArrayList<SelectItem>(); + items.add(new SelectItem(FIRST_VALUE)); + items.add(new SelectItem(SECOND_VALUE)); + items.add(new SelectItem(IGNORE)); + return items; + } + + public List<SelectItem> getRelSelectItems(){ + List<SelectItem> items = new ArrayList<SelectItem>(); + items.add(new SelectItem(TAKE)); + items.add(new SelectItem(IGNORE)); + return items; + } + + public Entity getEntResult() { + return entResult; + } + + public void setEntResult(Entity entResult) { + this.entResult = entResult; + } + + public List<Attribute> getResultAtts() { + return resultAtts; + } + + public void setResultAtts(List<Attribute> resultAtts) { + this.resultAtts = resultAtts; + } + + public List<Relation> getResultSrcRels() { + return resultSrcRels; + } + + public void setResultSrcRels(List<Relation> resultSrcRels) { + this.resultSrcRels = resultSrcRels; + } + + public List<Relation> getResultTarRels() { + return resultTarRels; + } + + public void setResultTarRels(List<Relation> resultTarRels) { + this.resultTarRels = resultTarRels; + } + + 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 List<String> getAttLabels() { + return attLabels; + } + + public void setAttLabels(List<String> attLabels) { + this.attLabels = attLabels; + } + + public Map<String, String> getFirstAttMap() { + return firstAttMap; + } + + public void setFirstAttMap(Map<String, String> firstAttMap) { + this.firstAttMap = firstAttMap; + } + + public Map<String, String> getSecondAttMap() { + return secondAttMap; + } + + public void setSecondAttMap(Map<String, String> secondAttMap) { + this.secondAttMap = secondAttMap; + } + + public Map<String, String> getSelectedAtts() { + return selectedAtts; + } + + public void setSelectedAtts(Map<String, String> selectedAtts) { + this.selectedAtts = selectedAtts; + } + + public boolean isShowAttributeMapping() { + return showAttributeMapping; + } + + public void setShowAttributeMapping(boolean showAttributeMapping) { + this.showAttributeMapping = showAttributeMapping; + } + + public boolean isEntitiesLoaded() { + return entitiesLoaded; + } + + public void setEntitiesLoaded(boolean entitiesLoaded) { + this.entitiesLoaded = entitiesLoaded; + } + + public Map<Long, String> getSelectedFirstSrcRelations() { + return selectedFirstSrcRelations; + } + + public void setSelectedFirstSrcRelations( + Map<Long, String> selectedFirstSrcRelations) { + this.selectedFirstSrcRelations = selectedFirstSrcRelations; + } + + public Map<Long, String> getSelectedSecondSrcRelations() { + return selectedSecondSrcRelations; + } + + public void setSelectedSecondSrcRelations( + Map<Long, String> selectedSecondSrcRelations) { + this.selectedSecondSrcRelations = selectedSecondSrcRelations; + } + public boolean isShowSrcRelationMapping() { + return showSrcRelationMapping; + } + + public void setShowSrcRelationMapping(boolean showSrcRelationMapping) { + this.showSrcRelationMapping = showSrcRelationMapping; + } + + + public boolean isShowTarRelationMapping() { + return showTarRelationMapping; + } + + public void setShowTarRelationMapping(boolean showTarRelationMapping) { + this.showTarRelationMapping = showTarRelationMapping; + } + + public Map<Long, String> getSelectedFirstTarRelations() { + return selectedFirstTarRelations; + } + + public void setSelectedFirstTarRelations( + Map<Long, String> selectedFirstTarRelations) { + this.selectedFirstTarRelations = selectedFirstTarRelations; + } + + public Map<Long, String> getSelectedSecondTarRelations() { + return selectedSecondTarRelations; + } + + public void setSelectedSecondTarRelations( + Map<Long, String> selectedSecondTarRelations) { + this.selectedSecondTarRelations = selectedSecondTarRelations; + } + /* + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public boolean isShowMsgPopup() { + return showMsgPopup; + } + + public void setShowMsgPopup(boolean showMsgPopup) { + this.showMsgPopup = showMsgPopup; + } + + public String getConfirmMsg() { + return confirmMsg; + } + + public void setConfirmMsg(String confirmMsg) { + this.confirmMsg = confirmMsg; + } + + public boolean isShowConfirmPopup() { + return showConfirmPopup; + } + + public void setShowConfirmPopup(boolean showConfirmPopup) { + this.showConfirmPopup = showConfirmPopup; + } + */ +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/profile/ProfileBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,70 @@ +package de.mpiwg.itgroup.ismi.profile; + +import java.io.Serializable; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.security.bo.User; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; +import de.mpiwg.itgroup.ismi.entry.beans.SessionBean; + +public class ProfileBean extends AbstractISMIBean implements Serializable{ + private static final long serialVersionUID = 8718895052765908194L; + + private String password1; + private String password2; + private String oldPassword; + + + public String actionChangePassword(){ + boolean valid = true; + if(StringUtils.isEmpty(password1) || StringUtils.isEmpty(password2) || !password1.equals(password2)){ + addErrorMsg("The new passwords are different."); + valid = false; + } + + User user = getSecurityService().getUserByPassword(getSessionUser().getEmail(), oldPassword); + if(user == null){ + addErrorMsg("The old password was not correct."); + valid = false; + } + + if(valid){ + user.setPassword(password1); + getSecurityService().saveUser(user); + getSessionBean().setUser(user); + + this.password1 = new String(); + this.password2 = new String(); + this.oldPassword = new String(); + + return SessionBean.PAGE_SIMPLE_SEARCH; + } + return ""; + } + + + + public String getOldPassword() { + return oldPassword; + } + public void setOldPassword(String oldPassword) { + this.oldPassword = oldPassword; + } + public String getPassword1() { + return password1; + } + public void setPassword1(String password1) { + this.password1 = password1; + } + public String getPassword2() { + return password2; + } + public void setPassword2(String password2) { + this.password2 = password2; + } + + + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/publicView/DynamicPageEditor.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,249 @@ +package de.mpiwg.itgroup.ismi.publicView; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.event.AjaxBehaviorEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +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.ViewerAttribute; +import org.mpi.openmind.repository.bo.ViewerPage; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractBean; +import de.mpiwg.itgroup.ismi.utils.SelectableObject; + +public class DynamicPageEditor extends AbstractBean{ + private static final long serialVersionUID = 223061720960235795L; + + private static List<SelectItem> displayModeList = new ArrayList<SelectItem>(); + private static List<SelectItem> suggestedTextAlign = new ArrayList<SelectItem>(); + private static List<SelectItem> contentTypeList = new ArrayList<SelectItem>(); + + private List<SelectItem> definitionList; + + static{ + displayModeList.add(new SelectItem(ViewerAttribute.SHOW_ALWAYS, "Show always")); + displayModeList.add(new SelectItem(ViewerAttribute.SHOW_WITH_CONTENT, "Show only if there is content")); + displayModeList.add(new SelectItem(ViewerAttribute.HIDE, "Hide")); + + suggestedTextAlign.add(new SelectItem(ViewerAttribute.ALIGN_RIGHT)); + suggestedTextAlign.add(new SelectItem(ViewerAttribute.ALIGN_LEFT)); + suggestedTextAlign.add(new SelectItem(ViewerAttribute.ALIGN_CENTER)); + + contentTypeList.add(new SelectItem(ViewerAttribute.CONTENT_TEXT, "Plain text")); + contentTypeList.add(new SelectItem(ViewerAttribute.CONTENT_DATE, "Date")); + } + + private static Logger logger = Logger.getLogger(DynamicPageEditor.class); + + private List<SelectItem> pageList; + + private List<SelectableObject<ViewerAttribute>> attList; + + private Long pageId; + private ViewerPage page; + + + public DynamicPageEditor(){ + logger.info("Init DynamicPageEditor"); + } + + public void load(){ + logger.info("Loading pages!!!"); + Collection<ViewerPage> pages = getWrapper().getViewerPages(); + this.pageList = new ArrayList<SelectItem>(); + this.pageList.add(new SelectItem(new Long(-1), "-- select one --")); + for(ViewerPage page : pages){ + this.pageList.add(new SelectItem(page.getId(), page.getDefinition())); + } + } + + public void listenerCreatePage(ActionEvent event){ + this.page = new ViewerPage(); + } + + public void listenerSavePage(ActionEvent event){ + getWrapper().saveViewerPage(page, getSessionBean().getUsername()); + this.load(); + } + + public void listenerAddAtt(ActionEvent event){ + if(attList == null) + attList = new ArrayList<SelectableObject<ViewerAttribute>>(); + + ViewerAttribute att = new ViewerAttribute(); + att.setIndex(this.attList.size()); + this.attList.add(new SelectableObject<ViewerAttribute>(att)); + } + + public void listenerSelectPage(AjaxBehaviorEvent event){ + try { + //System.out.println("AjaxBehaviorEvent"); + if(this.pageId != null && this.pageId != -1){ + this.page = getWrapper().getViewerPage4Edition(pageId); + List<ViewerAttribute> tmp = getWrapper().getViewerAttributes4Edition(pageId); + this.attList = new ArrayList<SelectableObject<ViewerAttribute>>(); + for(ViewerAttribute att : tmp){ + this.attList.add(new SelectableObject<ViewerAttribute>(att)); + } + }else{ + this.page = null; + this.attList = null; + } + } catch (Exception e) { + e.printStackTrace(); + addException(e); + } + } + + public void listenerRemoveAttributes(ActionEvent event){ + for(SelectableObject<ViewerAttribute> so : new ArrayList<SelectableObject<ViewerAttribute>>(this.attList)){ + if(so.isSelected()){ + if(so.getObj().isPersistent()) + this.getWrapper().removeViewerAnttribute(so.getObj()); + this.attList.remove(so); + } + } + + for(int i=0; i < this.attList.size(); i++){ + this.attList.get(i).getObj().setIndex(i); + } + + } + + public void listenerRemovePage(ActionEvent event){ + if(getWrapper().removeViewerPage(page) > 0){ + getSessionBean().addGeneralMsg("The Page and its attirbutes have been removed successfully!"); + } + } + + public void listenerClean(ActionEvent event){ + this.page = null; + this.attList = null; + } + + public List<SelectItem> getPageList() { + if(this.pageList == null){ + this.load(); + } + return pageList; + } + + public void setPageList(List<SelectItem> pageList) { + this.pageList = pageList; + } + + public ViewerPage getPage() { + return page; + } + + public void setPage(ViewerPage page) { + this.page = page; + } + + public boolean isPagePersistent(){ + return page != null && page.isPersistent(); + } + + public Long getPageId() { + return pageId; + } + + public void setPageId(Long pageId) { + this.pageId = pageId; + } + + public List<SelectableObject<ViewerAttribute>> getAttList() { + return attList; + } + + public void setAttList(List<SelectableObject<ViewerAttribute>> attList) { + this.attList = attList; + } + + + public void listenerSaveAll(ActionEvent event){ + try { + for(int i=0; i<this.attList.size(); i++){ + ViewerAttribute att = this.attList.get(i).getObj(); + att.setIndex(i); + getWrapper().saveViewerAttribute(page, att, getSessionBean().getUsername()); + } + addGeneralMsg("The attributes of the page have been saved successfully!"); + } catch (Exception e) { + e.printStackTrace(); + addException(e); + } + } + + public void listenerUp(ActionEvent event){ + logger.info("listenerUp"); + Object obj = getRequestBean("att"); + if(obj != null){ + SelectableObject<ViewerAttribute> currentAtt = (SelectableObject<ViewerAttribute>)obj; + int index = this.attList.indexOf(currentAtt); + if(index > 0){ + SelectableObject<ViewerAttribute> previousAtt = this.attList.get(index-1); + currentAtt.getObj().setIndex(index-1); + previousAtt.getObj().setIndex(index); + + this.attList.set(index-1, currentAtt); + this.attList.set(index, previousAtt); + } + } + } + + public void listenerDown(ActionEvent event){ + logger.info("listenerDown"); + Object obj = getRequestBean("att"); + if(obj != null){ + SelectableObject<ViewerAttribute> currentAtt = (SelectableObject<ViewerAttribute>)obj; + int index = this.attList.indexOf(currentAtt); + if(index < this.attList.size()-1){ + SelectableObject<ViewerAttribute> nextAtt = this.attList.get(index+1); + currentAtt.getObj().setIndex(index+1); + nextAtt.getObj().setIndex(index); + + this.attList.set(index, nextAtt); + this.attList.set(index+1, currentAtt); + + } + } + + } + + public List<SelectItem> getDisplayModeList(){ + return displayModeList; + } + + public List<SelectItem> getSuggestedTextAlign(){ + return suggestedTextAlign; + } + + public List<SelectItem> getContentTypeList(){ + return contentTypeList; + } + + public List<SelectItem> getDefinitionList(){ + if(definitionList == null){ + this.loadDefinitionList(); + } + return definitionList; + } + + private void loadDefinitionList(){ + this.definitionList = new ArrayList<SelectItem>(); + this.definitionList.add(new SelectItem("-- select one --")); + for(Entity def : getWrapper().getLWDefinitions()){ + this.definitionList.add(new SelectItem(def.getOwnValue())); + } + + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/publicView/PublicCodexBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,69 @@ +package de.mpiwg.itgroup.ismi.publicView; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ActionEvent; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.utils.NormalizerUtils; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractBean; + +public class PublicCodexBean extends AbstractBean{ + private static final long serialVersionUID = 6992265932188217438L; + + private static Logger logger = Logger.getLogger(PublicCodexBean.class); + + private List<Entity> currentCodexList; + private String term; + + public PublicCodexBean(){ + logger.info("Init PublicCodexBean"); + } + + private void load(){ + this.currentCodexList = new ArrayList<Entity>(getAppBean().getPublicCodexList().getCodexList()); + } + + public void listenerSearch(ActionEvent event){ + this.search(); + } + + public void listenerReset(ActionEvent event){ + this.load(); + } + + private void search(){ + if(StringUtils.isEmpty(term)){ + this.load(); + }else{ + this.currentCodexList = new ArrayList<Entity>(); + String term0 = NormalizerUtils.normalize(term); + for(Entity ent : getAppBean().getPublicCodexList().getCodexList()){ + + if(StringUtils.isNotEmpty(ent.getNormalizedOwnValue()) && + ent.getNormalizedOwnValue().contains(term0)){ + this.currentCodexList.add(ent); + } + } + } + } + + public List<Entity> getCurrentCodexList() { + if(currentCodexList == null){ + this.load(); + } + return currentCodexList; + } + + public String getTerm() { + return term; + } + + public void setTerm(String term) { + this.term = term; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/publicView/PublicCodexList.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,203 @@ +package de.mpiwg.itgroup.ismi.publicView; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractBean; +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; + +public class PublicCodexList extends AbstractBean{ + private static final long serialVersionUID = 4576052953031233629L; + + private static Logger logger = Logger.getLogger(PublicCodexList.class); + /* + private static List<Long> codexIdList = new ArrayList<Long>(); + static{ + codexIdList.add(new Long(27543)); + codexIdList.add(new Long(36745)); + codexIdList.add(new Long(58453)); + codexIdList.add(new Long(87298)); + codexIdList.add(new Long(259646)); + codexIdList.add(new Long(35093)); + codexIdList.add(new Long(22863)); + codexIdList.add(new Long(34870)); + codexIdList.add(new Long(36882)); + codexIdList.add(new Long(101488)); + codexIdList.add(new Long(36696)); + codexIdList.add(new Long(31794)); + codexIdList.add(new Long(37240)); + codexIdList.add(new Long(35014)); + codexIdList.add(new Long(35583)); + codexIdList.add(new Long(37025)); + codexIdList.add(new Long(35960)); + codexIdList.add(new Long(172492)); + codexIdList.add(new Long(98286)); + codexIdList.add(new Long(165721)); + codexIdList.add(new Long(260111)); + codexIdList.add(new Long(90980)); + codexIdList.add(new Long(36316)); + codexIdList.add(new Long(260120)); + codexIdList.add(new Long(36241)); + codexIdList.add(new Long(260129)); + codexIdList.add(new Long(260138)); + codexIdList.add(new Long(38860)); + codexIdList.add(new Long(176694)); + codexIdList.add(new Long(72545)); + codexIdList.add(new Long(36185)); + codexIdList.add(new Long(36575)); + codexIdList.add(new Long(260146)); + codexIdList.add(new Long(31672)); + codexIdList.add(new Long(37739)); + codexIdList.add(new Long(89861)); + codexIdList.add(new Long(176778)); + codexIdList.add(new Long(180743)); + codexIdList.add(new Long(86328)); + codexIdList.add(new Long(260150)); + codexIdList.add(new Long(90658)); + codexIdList.add(new Long(58423)); + codexIdList.add(new Long(181058)); + codexIdList.add(new Long(105948)); + codexIdList.add(new Long(35526)); + codexIdList.add(new Long(74078)); + codexIdList.add(new Long(260158)); + codexIdList.add(new Long(181096)); + codexIdList.add(new Long(31606)); + codexIdList.add(new Long(31568)); + codexIdList.add(new Long(27872)); + codexIdList.add(new Long(36938)); + codexIdList.add(new Long(4836)); + codexIdList.add(new Long(34668)); + codexIdList.add(new Long(76866)); + codexIdList.add(new Long(102230)); + codexIdList.add(new Long(76888)); + codexIdList.add(new Long(74070)); + codexIdList.add(new Long(73757)); + codexIdList.add(new Long(182685)); + codexIdList.add(new Long(260162)); + codexIdList.add(new Long(260170)); + codexIdList.add(new Long(1102)); + codexIdList.add(new Long(172888)); + codexIdList.add(new Long(260174)); + codexIdList.add(new Long(34806)); + codexIdList.add(new Long(28088)); + codexIdList.add(new Long(36713)); + codexIdList.add(new Long(37323)); + codexIdList.add(new Long(34551)); + codexIdList.add(new Long(35943)); + codexIdList.add(new Long(98095)); + codexIdList.add(new Long(260178)); + codexIdList.add(new Long(260182)); + codexIdList.add(new Long(182770)); + codexIdList.add(new Long(260186)); + codexIdList.add(new Long(260190)); + codexIdList.add(new Long(260194)); + codexIdList.add(new Long(36114)); + codexIdList.add(new Long(85003)); + codexIdList.add(new Long(31630)); + codexIdList.add(new Long(157290)); + codexIdList.add(new Long(37153)); + codexIdList.add(new Long(37213)); + codexIdList.add(new Long(172952)); + codexIdList.add(new Long(86871)); + codexIdList.add(new Long(64406)); + codexIdList.add(new Long(102590)); + codexIdList.add(new Long(82615)); + codexIdList.add(new Long(58245)); + codexIdList.add(new Long(179791)); + codexIdList.add(new Long(179550)); + codexIdList.add(new Long(12419)); + codexIdList.add(new Long(95861)); + codexIdList.add(new Long(36429)); + codexIdList.add(new Long(36099)); + codexIdList.add(new Long(74237)); + codexIdList.add(new Long(36065)); + codexIdList.add(new Long(74822)); + codexIdList.add(new Long(87549)); + codexIdList.add(new Long(83765)); + codexIdList.add(new Long(36733)); + codexIdList.add(new Long(19259)); + codexIdList.add(new Long(260198)); + codexIdList.add(new Long(34986)); + codexIdList.add(new Long(88041)); + codexIdList.add(new Long(260202)); + codexIdList.add(new Long(36550)); + codexIdList.add(new Long(260206)); + codexIdList.add(new Long(37228)); + codexIdList.add(new Long(39880)); + codexIdList.add(new Long(36318)); + codexIdList.add(new Long(36597)); + codexIdList.add(new Long(35035)); + codexIdList.add(new Long(58328)); + codexIdList.add(new Long(80831)); + codexIdList.add(new Long(58354)); + codexIdList.add(new Long(74277)); + codexIdList.add(new Long(36529)); + codexIdList.add(new Long(36380)); + codexIdList.add(new Long(69450)); + codexIdList.add(new Long(200246)); + codexIdList.add(new Long(260222)); + codexIdList.add(new Long(81178)); + codexIdList.add(new Long(260226)); + codexIdList.add(new Long(199952)); + codexIdList.add(new Long(262557)); + codexIdList.add(new Long(87212)); + codexIdList.add(new Long(99059)); + codexIdList.add(new Long(64270)); + codexIdList.add(new Long(81811)); + codexIdList.add(new Long(65785)); + codexIdList.add(new Long(36645)); + }*/ + + private List<Entity> codexList; + + /* + public void load(){ + logger.info("************* (1) Loading Public Codex List...\n\n\n"); + this.codexList = new ArrayList<Entity>(); + + long start = System.currentTimeMillis(); + + for(Long id : codexIdList){ + Entity codex = getWrapper().getEntityById(id); + if (codex != null){ + this.codexList.add(codex); + } + } + long diff = System.currentTimeMillis() - start; + logger.info("Dif: " + diff + ", elemenst: " + this.codexList.size()); + }*/ + + public void load0(){ + this.codexList = new ArrayList<Entity>(); + + long start = System.currentTimeMillis(); + List<Attribute> attList = getWrapper().getAttributesByDefByAttName("CODEX", "public", "true", -1); + + for(Attribute att : attList){ + Entity codex = getWrapper().getEntityById(att.getSourceId()); + if (codex != null){ + this.codexList.add(codex); + } + } + + long diff = System.currentTimeMillis() - start; + logger.info("Loading Public Codex List - Time[ms]: " + diff + ", elemenst: " + this.codexList.size()); + } + + public List<Entity> getCodexList() { + if(codexList == null){ + this.load0(); + } + return codexList; + } + + public void setCodexList(List<Entity> codexList) { + this.codexList = codexList; + } + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/publicView/PublicCodexView.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,111 @@ +package de.mpiwg.itgroup.ismi.publicView; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.ViewerPage; +import org.mpi.openmind.repository.utils.RomanizationLoC; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractBean; + +public class PublicCodexView extends AbstractBean{ + private static final long serialVersionUID = -3013781647163292966L; + + private Entity codex; + private Entity digi; + private List<WitnessItem> witnessList; + private boolean codexPublic = true; + + private Long dynamicCodexPageId; + private Long dynamicWitnessPageId; + + public void load(String id){ + try { + this.load(Long.parseLong(id)); + } catch (Exception e) { + e.printStackTrace(); + } + } + public void load(Long id){ + this.witnessList = new ArrayList<WitnessItem>(); + this.codex = getWrapper().getEntityById(id); + this.digi = null; + if(codex != null){ + + List<Entity> tmp = getWrapper().getSourcesForTargetRelation(codex, "is_digitalization_of", "DIGITALIZATION", 1); + digi = (tmp.isEmpty()) ? null : tmp.get(0); + + tmp = getWrapper().getSourcesForTargetRelation(codex, "is_part_of", "WITNESS", -1); + + for(Entity witness : tmp){ + + List<Entity> list0 = getWrapper().getTargetsForSourceRelation(witness.getId(), "is_exemplar_of", "TEXT", 1); + //TODO the label should be normalized with the new algorithm of Chantal + String label = (list0.isEmpty()) ? witness.getOwnValue() : list0.get(0).getOwnValue(); + + //calculating the image index for the diva viewer + //String divaImageIndex = this.getDivaImage(digi.getOwnValue(), getWrapper().getAttributeByName(witness.getId(), "start_page")); + this.witnessList.add(new WitnessItem(witness.getId(), label/*, divaImageIndex*/)); + } + + + } + ViewerPage tmp = getWrapper().getViewerPage("Codex"); + this.dynamicCodexPageId = (tmp == null) ? dynamicCodexPageId : tmp.getId(); + + tmp = getWrapper().getViewerPage("Witness"); + this.dynamicWitnessPageId = (tmp == null) ? dynamicWitnessPageId : tmp.getId(); + } + + public boolean isCodexPublic(){ + return this.codexPublic; + } + public Entity getCodex() { + return codex; + } + public void setCodex(Entity codex) { + this.codex = codex; + } + public Entity getDigi() { + return digi; + } + public void setDigi(Entity digi) { + this.digi = digi; + } + public List<WitnessItem> getWitnessList() { + return witnessList; + } + public void setWitnessList(List<WitnessItem> witnessList) { + this.witnessList = witnessList; + } + public void setCodexPublic(boolean codexPublic) { + this.codexPublic = codexPublic; + } + public Long getDynamicCodexPageId() { + return dynamicCodexPageId; + } + public Long getDynamicWitnessPageId() { + return dynamicWitnessPageId; + } + + public class WitnessItem{ + private String label; + private Long id; + + public WitnessItem(Long id, String label){ + this.id = id; + this.label = RomanizationLoC.convert(label); + } + + public String getLabel() { + return label; + } + + public Long getId() { + return id; + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/publicView/pages/CodexDynamicPage.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,86 @@ +package de.mpiwg.itgroup.ismi.publicView.pages; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.utils.templates.WitnessTemplate; + +public class CodexDynamicPage extends JSPDynamicPage{ + + private List<WitnessTemplate> witnessList; + private List<WitnessTemplate> unknownList; + private Integer startPage; + private Boolean imageFullscreen; + + @Override + public void load(Long codexId){ + super.load(codexId); + + witnessList = new ArrayList<WitnessTemplate>(); + unknownList = new ArrayList<WitnessTemplate>(); + + //loading the digitalization object + List<Entity> list0 = getWrapper().getSourcesForTargetRelation(codexId, "is_digitalization_of", "DIGITALIZATION", 1); + this.digi = (list0.size() == 0) ? null : list0.get(0); + + //loading the witnesses + list0 = getWrapper().getSourcesForTargetRelation(codexId, "is_part_of", "WITNESS", -1); + for(Entity witness : list0){ + WitnessTemplate tmp = new WitnessTemplate(witness, getWrapper(), true); + this.witnessList.add(tmp); + if(tmp.isUnknown()){ + this.unknownList.add(tmp); + } + } + Collections.sort(this.witnessList); + Collections.sort(this.unknownList); + } + + public void init(){ + this.startPage = 0; + this.imageFullscreen = false; + try { + + this.load(Long.parseLong(getRequest().getParameter("eid"))); + + try { + this.startPage = Integer.parseInt(getRequest().getParameter("startPage")); + this.imageFullscreen = + (getRequest().getParameter("imgFullscreen") != null) ? Boolean.parseBoolean(getRequest().getParameter("imgFullscreen")) : false; + } catch (Exception e) { + // TODO: handle exception + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + + public Integer getStartPage() { + return startPage; + } + + public Boolean getImageFullscreen() { + return imageFullscreen; + } + + public List<WitnessTemplate> getWitnessList() { + return witnessList; + } + + public void setWitnessList(List<WitnessTemplate> witnessList) { + this.witnessList = witnessList; + } + + public List<WitnessTemplate> getUnknownList() { + return unknownList; + } + + public void setUnknownList(List<WitnessTemplate> unknownList) { + this.unknownList = unknownList; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/publicView/pages/DynamicPage.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,104 @@ +package de.mpiwg.itgroup.ismi.publicView.pages; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.ViewerAttribute; +import org.mpi.openmind.repository.bo.ViewerPage; +import org.mpi.openmind.repository.utils.OMUtils; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractBean; + +public class DynamicPage extends AbstractBean{ + private static final long serialVersionUID = -3539502586578459996L; + + private Long entId; + private ViewerPage page; + private Map<String, List<String>> attMap; + private Map<String, String> attMapTextAlign; + private List<String> labelList; + + + public void load(String entId){ + try { + this.load(Long.parseLong(entId)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void load(Long entId){ + Entity ent = getWrapper().getEntityById(entId); + this.page = null; + + this.attMap = new HashMap<String, List<String>>(); + this.attMapTextAlign = new HashMap<String, String>(); + this.labelList = new ArrayList<String>(); + if(ent != null){ + + this.page = getWrapper().getViewerPage(ent.getObjectClass()); + if(page != null){ + List<ViewerAttribute> attList = getWrapper().getViewerAttributes(page.getId()); + for(ViewerAttribute att : attList){ + try { + + if(att.getDisplayMode() != ViewerAttribute.HIDE){ + this.attMapTextAlign.put(att.getLabel(), att.getTextAlign()); + List<String> values = OMUtils.resolveQuery(entId, att.getQuery(), getWrapper(), att.getContentType()); + + if(values.size() > 0 || att.getDisplayMode() == ViewerAttribute.SHOW_ALWAYS){ + this.attMap.put(att.getLabel(), values); + this.labelList.add(att.getLabel()); + } + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + } + + public Long getEntId() { + return entId; + } + + + public void setEntId(Long entId) { + this.entId = entId; + } + + + public ViewerPage getPage() { + return page; + } + + + public void setPage(ViewerPage page) { + this.page = page; + } + + + public Map<String, List<String>> getAttMap() { + return attMap; + } + + + public void setAttMap(Map<String, List<String>> attMap) { + this.attMap = attMap; + } + + public List<String> getLabels(){ + return this.labelList; + } + + public Map<String, String> getAttMapTextAlign() { + return attMapTextAlign; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/publicView/pages/JSFDynamicPage.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,90 @@ +package de.mpiwg.itgroup.ismi.publicView.pages; + +import java.util.ArrayList; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.ViewerAttribute; +import org.mpi.openmind.repository.bo.ViewerPage; +import org.mpi.openmind.repository.utils.OMUtils; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractBean; + +public class JSFDynamicPage extends AbstractBean{ + + private static final long serialVersionUID = 8946353053956179797L; + + private Long currentEntId; + private ViewerPage page; + private Map<String, List<String>> attMap; + private Map<String, String> attMapTextAlign; + private List<String> labelList; + + public void load(Long currentEntId){ + Entity ent = getWrapper().getEntityById(currentEntId); + this.page = null; + + this.attMap = new HashMap<String, List<String>>(); + this.attMapTextAlign = new HashMap<String, String>(); + this.labelList = new ArrayList<String>(); + if(ent != null){ + + this.page = getWrapper().getViewerPage(ent.getObjectClass()); + if(page != null){ + List<ViewerAttribute> attList = getWrapper().getViewerAttributes(page.getId()); + for(ViewerAttribute att : attList){ + try { + //TODO show always??? + this.attMapTextAlign.put(att.getLabel(), att.getTextAlign()); + List<String> values = OMUtils.resolveQuery(currentEntId, att.getQuery(), getWrapper(), att.getContentType()); + this.attMap.put(att.getLabel(), values); + this.labelList.add(att.getLabel()); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + System.out.println(""); + } + + + public Long getCurrentEntId() { + return currentEntId; + } + + public void setCurrentEntId(Long currentEntId) { + this.currentEntId = currentEntId; + } + + public ViewerPage getPage() { + return page; + } + + + public void setPage(ViewerPage page) { + this.page = page; + } + + + public Map<String, List<String>> getAttMap() { + return attMap; + } + + + public void setAttMap(Map<String, List<String>> attMap) { + this.attMap = attMap; + } + + public List<String> getLabels(){ + return this.labelList; + } + + public Map<String, String> getAttMapTextAlign() { + return attMapTextAlign; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/publicView/pages/JSPDynamicPage.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,131 @@ +package de.mpiwg.itgroup.ismi.publicView.pages; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.ViewerAttribute; +import org.mpi.openmind.repository.bo.ViewerPage; +import org.mpi.openmind.repository.utils.OMUtils; + +import de.mpiwg.itgroup.diva.jsp.AbsJSPWrapper; + +public class JSPDynamicPage extends AbsJSPWrapper{ + + private Long currentEntId; + private ViewerPage page; + private Map<String, List<String>> attMap; + private Map<String, String> attMapTextAlign; + private List<String> labelList; + + private boolean errorLoading; + + protected Entity digi; + + + public void load(String currentEntId){ + try { + this.load(Long.parseLong(currentEntId)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void load(Long newEntId){ + this.currentEntId = newEntId; + Entity ent = getWrapper().getEntityById(currentEntId); + + this.errorLoading = (ent != null) ? true : false; + if(ent == null){ + this.getSessionBean().addGeneralMsg("The entity " + currentEntId + " was not found."); + } + + this.page = null; + + this.attMap = new HashMap<String, List<String>>(); + this.attMapTextAlign = new HashMap<String, String>(); + this.labelList = new ArrayList<String>(); + if(ent != null){ + + this.page = getWrapper().getViewerPage(ent.getObjectClass()); + if(page != null){ + List<ViewerAttribute> attList = getWrapper().getViewerAttributes(page.getId()); + for(ViewerAttribute att : attList){ + try { + + if(att.getDisplayMode() != ViewerAttribute.HIDE){ + this.attMapTextAlign.put(att.getLabel(), att.getTextAlign()); + List<String> values = OMUtils.resolveQuery(currentEntId, att.getQuery(), getWrapper(), att.getContentType()); + + if(values.size() > 0 || att.getDisplayMode() == ViewerAttribute.SHOW_ALWAYS){ + this.attMap.put(att.getLabel(), values); + this.labelList.add(att.getLabel()); + } + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + System.out.println(""); + } + + public Long getCurrentEntId() { + return currentEntId; + } + + public void setCurrentEntId(Long currentEntId) { + this.currentEntId = currentEntId; + } + + public ViewerPage getPage() { + return page; + } + + + public void setPage(ViewerPage page) { + this.page = page; + } + + + public Map<String, List<String>> getAttMap() { + return attMap; + } + + + public void setAttMap(Map<String, List<String>> attMap) { + this.attMap = attMap; + } + + public List<String> getLabels(){ + return this.labelList; + } + + public String getDigiLabel(){ + return (digi == null) ? null : digi.getOwnValue(); + } + + public Long getDigiId(){ + return (digi == null) ? null : digi.getId(); + } + + public Entity getDigi() { + return digi; + } + + public void setDigi(Entity digi) { + this.digi = digi; + } + + public Map<String, String> getAttMapTextAlign() { + return attMapTextAlign; + } + + public boolean isErrorLoading(){ + return this.errorLoading; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/publicView/pages/WitnessDynamicPage.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,121 @@ +package de.mpiwg.itgroup.ismi.publicView.pages; + +import java.util.List; + +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.utils.RomanizationLoC; + +public class WitnessDynamicPage extends JSPDynamicPage{ + + private Long titleId; + private Long authorId; + private String author; + private String title; + private String firstPage; + + @Override + public void load(Long witnessId){ + super.load(witnessId); + + this.titleId = null; + this.title = null; + this.author = null; + this.authorId = null; + + + if(witnessId != null){ + + this.loadFirstPage(); + + //loading the digitalization object + List<Entity> list = getWrapper().getTargetsForSourceRelation(witnessId, "is_part_of", "CODEX", 1); + if (list.size() > 0) { + Entity codex = list.get(0); + List<Entity> list0 = getWrapper().getSourcesForTargetRelation(codex.getId(), "is_digitalization_of", "DIGITALIZATION", 1); + this.digi = (list0.size() == 0) ? null : list0.get(0); + } + + + //loading witness + List<Entity> list0 = getWrapper().getTargetsForSourceRelation(witnessId, "is_exemplar_of", "TEXT", 1); + if (list0.size() > 0) { + + this.titleId = list0.get(0).getId(); + this.title = RomanizationLoC.convert(list0.get(0).getOwnValue()); + System.out.println("&&&&&& " + this.title); + + list0 = getWrapper().getTargetsForSourceRelation(this.titleId, "was_created_by", "PERSON", 1); + if(list0.size() > 0){ + this.authorId = list0.get(0).getId(); + this.author = RomanizationLoC.convert(list0.get(0).getOwnValue()); + } + } + } + } + + /** + * The start_page saves the first page of the witness in the codex. + * start_page can contains number from the 1, however the diva viewer considers that the first page is 0. + * For this reason, if a witness contains this attribute, then we must subtract 1 page. + */ + public void loadFirstPage(){ + Attribute firstPageAtt = getWrapper().getAttributeByName(getCurrentEntId(), "start_page"); + Integer tmp = 0; + + if(firstPageAtt != null){ + try { + tmp = Integer.parseInt(firstPageAtt.getOwnValue()); + tmp = (tmp > 0) ? tmp-1 : tmp; + } catch (Exception e) {} + } + + this.firstPage = tmp.toString(); + } + + public void init(){ + try { + + this.load(Long.parseLong(getRequest().getParameter("eid"))); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + public Long getTitleId() { + return titleId; + } + + public void setTitleId(Long titleId) { + this.titleId = titleId; + } + + public Long getAuthorId() { + return authorId; + } + + public void setAuthorId(Long authorId) { + this.authorId = authorId; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getFirstPage(){ + return this.firstPage; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/search/beans/AbstractQuery.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,152 @@ +package de.mpiwg.itgroup.ismi.search.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map.Entry; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.log4j.Logger; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.search.utils.ResultEntry; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractBean; +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; + +public class AbstractQuery extends AbstractBean implements Serializable{ + + private static final long serialVersionUID = 8640487026954118233L; + + private static Logger logger = Logger.getLogger(AbstractQuery.class); + + protected ApplicationBean appBean; + private boolean searched = false; + private Long timeExecution; + private String exportType = "xml"; + + protected String exportUrlRoot; + private String modeExportDirk; + protected String exportDirkUrl; + protected String idList; + + protected List<?> rs; + + protected int MAX_RS = 20000; + + private static List<SelectItem> modeExportDirkList; + + static{ + modeExportDirkList = new ArrayList<SelectItem>(); + modeExportDirkList.add(new SelectItem("xml")); + modeExportDirkList.add(new SelectItem("tab")); + modeExportDirkList.add(new SelectItem("html")); + //modeExportDirkList.add(new SelectItem("doc")); + } + + public void listenerChangeModeExportDirk(ValueChangeEvent event){ + if(event != null && event.getNewValue() != null){ + this.exportDirkUrl = ApplicationBean.generateExportURL(exportUrlRoot, idList, event.getNewValue().toString()); + } + } + + public AbstractQuery(ApplicationBean appBean){ + this.appBean = appBean; + this.modeExportDirk = "xml"; + } + + public void listenerReset(ActionEvent event){ + this.reset(); + this.modeExportDirk = "xml"; + } + + public void listenerSearch(ActionEvent event){ + try { + long start = System.currentTimeMillis(); + this.search(); + long end = System.currentTimeMillis(); + this.searched = true; + this.timeExecution = end - start; + logger.info(toString() + " time execution=" + (timeExecution)); + } catch (Exception e) { + logger.error(e.getMessage(), e); + printInternalError(e); + } + + } + + public void reset(){ + this.timeExecution = null; + this.searched = false; + } + + protected void search() throws Exception{} + + protected void printRs(List<ResultEntry> rs, WrapperService ws){ + StringBuilder sb = new StringBuilder(); + sb.append("--------------\n"); + for(ResultEntry entry : rs){ + for(Entry<Integer, Long> ent : entry.getEntMap().entrySet()){ + sb.append(ent.getKey() + ") " + ws.getEntityById(ent.getValue()).toSmallString()); + } + sb.append("\n"); + } + logger.info("--------------"); + + logger.info(sb.toString()); + + } + + public boolean isSearched() { + return searched; + } + + public Long getTimeExecution() { + return timeExecution; + } + + public WrapperService getOm(){ + return this.appBean.getWrapper(); + } + + public List<?> getRs() { + return rs; + } + + public Integer getRsSize(){ + if(rs != null){ + return rs.size(); + } + return 0; + } + + public String getExportType() { + return exportType; + } + + public void setExportType(String exportType) { + this.exportType = exportType; + } + + public List<SelectItem> getModeExportDirkList() { + return modeExportDirkList; + } + + public String getModeExportDirk() { + return modeExportDirk; + } + + public void setModeExportDirk(String modeExportDirk) { + this.modeExportDirk = modeExportDirk; + } + + public String getExportDirkUrl() { + return exportDirkUrl; + } + + public void setExportDirkUrl(String exportDirkUrl) { + this.exportDirkUrl = exportDirkUrl; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/search/beans/AdvancedSearchBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,392 @@ +package de.mpiwg.itgroup.ismi.search.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.log4j.Logger; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.search.utils.ResultEntry; +import org.mpi.openmind.search.utils.SAttribute; +import org.mpi.openmind.search.utils.SAttributeMultipleName; +import org.mpi.openmind.search.utils.SAttributeMultipleValue; +import org.mpi.openmind.search.utils.SAttributeUniqueName; +import org.mpi.openmind.search.utils.SEntity; +import org.mpi.openmind.search.utils.SRelation; +import org.mpi.openmind.search.utils.SRelationMultipleName; +import org.mpi.openmind.search.utils.SRelationUniqueName; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; +import de.mpiwg.itgroup.ismi.entry.beans.SessionBean; +import de.mpiwg.itgroup.ismi.util.guiComponents.Calendar; + +public class AdvancedSearchBean extends AbstractISMIBean implements Serializable{ + + private static Logger logger = Logger.getLogger(AdvancedSearchBean.class); + + private static final long serialVersionUID = 1L; + + private String currentTemplate; + private static List<SelectItem> templateList; + + private transient Witness4TitleQuery witness4TitleQuery; + //private SampleSearch06 sample06; + private SampleSearch07 sample07; + private Titles4PersonQuery titles4PersonQuery; + private CodexOwnershipQuery codexOwnershipQuery; + + static{ + templateList = new ArrayList<SelectItem>(); + //templateList.add(new SelectItem("sample01")); + templateList.add(new SelectItem("witness4Title", "Witnesses for a title")); + //templateList.add(new SelectItem("sample03")); + //templateList.add(new SelectItem("sample04")); + //templateList.add(new SelectItem("sample05")); + templateList.add(new SelectItem("titles4Person", "Titles for a person")); + templateList.add(new SelectItem("codexOwnership", "Codex ownership")); + //templateList.add(new SelectItem("sample07")); + //templateList.add(new SelectItem("sample08")); + //templateList.add(new SelectItem("sample09")); + } + + public AdvancedSearchBean(){ + //logger.info("AdvancedSearchBean"); + this.reset(); + } + + public void reset(){ + //logger.info("AdvancedSearchBean.reset()"); + this.witness4TitleQuery = new Witness4TitleQuery(getAppBean()); + this.titles4PersonQuery = new Titles4PersonQuery(getAppBean()); + this.sample07 = new SampleSearch07(getAppBean()); + this.codexOwnershipQuery = new CodexOwnershipQuery(getAppBean()); + currentTemplate = "witness4Title"; + } + + public void listenerChange(ValueChangeEvent event){ + /* + logger.info(event.getOldValue()); + logger.info(event.getNewValue()); + */ + } + + public String actionSearch(){ + this.search(); + return null; + } + + public SampleSearch07 getSample07() { + return sample07; + } + + public CodexOwnershipQuery getCodexOwnershipQuery() { + return codexOwnershipQuery; + } + + public Witness4TitleQuery getWitness4TitleQuery() { + return witness4TitleQuery; + } + + public void search(){ + long start = System.currentTimeMillis(); + + List<ResultEntry> rs = sample06(); + + //printRs(rs); + + long end = System.currentTimeMillis(); + logger.info("execution time [ms] = " + (end - start)); + logger.info("Search resultSet size= " + rs.size()); + } + + + private List<ResultEntry> test01(){ + List<SEntity> entFilters = new ArrayList<SEntity>(); + List<SRelation> relFilters = new ArrayList<SRelation>(); + + SEntity e1 = new SEntity(0, "PERSON"); + e1.addAtt(new SAttributeUniqueName("name_translit", "abu")); + entFilters.add(e1); + + SEntity e2 = new SEntity(1, "ROLE"); + e2.addAtt(new SAttributeUniqueName("name", "Author")); + entFilters.add(e2); + + SEntity e3 = new SEntity(2, "PLACE"); + e3.addAtt(new SAttributeUniqueName("name", "Spain")); + entFilters.add(e3); + + SEntity e4 = new SEntity(3, "ALIAS"); + e4.addAtt(new SAttributeUniqueName("alias", "Samuel")); + entFilters.add(e4); + + SRelationUniqueName has_role = new SRelationUniqueName(e1.getIndex(), e2.getIndex(), "has_role"); + SRelationUniqueName was_born_in = new SRelationUniqueName(e1.getIndex(), e3.getIndex(), "was_born_in"); + SRelationUniqueName is_prime_alias_name_of = new SRelationUniqueName(e4.getIndex(), e1.getIndex(), "is_prime_alias_name_of"); + relFilters.add(has_role); + relFilters.add(was_born_in); + relFilters.add(is_prime_alias_name_of); + + return getAppBean().getSS().search(entFilters, relFilters); + + } + + private List<ResultEntry> test02(){ + List<SEntity> entFilters = new ArrayList<SEntity>(); + List<SRelation> relFilters = new ArrayList<SRelation>(); + + SEntity e2 = new SEntity(1, "ALIAS"); + e2.addAtt(new SAttributeUniqueName("alias", "abu")); + entFilters.add(e2); + + SEntity e1 = new SEntity(0, "TEXT"); + e1.addAtt(new SAttributeUniqueName("full_title_translit", "abu")); + entFilters.add(e1); + + + SRelationMultipleName hasAlias = new SRelationMultipleName(e2.getIndex(), e1.getIndex(), + "is_prime_alias_title_of", + "is_alias_title_of", + "is_alias_incipit_of", + "is_alias_explicit_of"); + relFilters.add(hasAlias); + + return getAppBean().getSS().search(entFilters, relFilters); + } + + private List<ResultEntry> sample01(){ + + List<SEntity> entFilters = new ArrayList<SEntity>(); + List<SRelation> relFilters = new ArrayList<SRelation>(); + + SEntity role = new SEntity(0, "ROLE"); + role.addAtt(new SAttributeUniqueName("name", "Author")); + entFilters.add(role); + + //alias, "is_prime_alias_name_of", "PERSON" + //alias, "is_alias_name_of", "PERSON" + SEntity person = new SEntity(1, "PERSON"); + person.addAtt(new SAttributeMultipleName("a", "name_translit", "name")); + entFilters.add(person); + + /* + SEntity alias = new SEntity(1, "ALIAS"); + alias.addAtt(new SAttributeUniqueName("alias", "abu")); + entFilters.add(alias); + */ + + SEntity title = new SEntity(2, "TEXT"); + //title.addAtt(new SAttributeMultipleName("abu", "full_title_translit", "full_title")); + entFilters.add(title); + + + SRelationUniqueName has_role = new SRelationUniqueName(person, role, "has_role"); + SRelationUniqueName was_created_by = new SRelationUniqueName(title, person, "was_created_by"); + relFilters.add(was_created_by); + relFilters.add(has_role); + + List<ResultEntry> rs = getAppBean().getSS().search(entFilters, relFilters); + + return rs; + } + + /** + * 5) List of all people who had other “roles” associated with a title (e.g. copyists , owners, patrons, teachers, students, etc.) + * @return + */ + private List<ResultEntry> sample05(){ + + List<SEntity> entFilters = new ArrayList<SEntity>(); + List<SRelation> relFilters = new ArrayList<SRelation>(); + + SEntity role = new SEntity(0, "ROLE"); + role.addAtt(new SAttributeMultipleValue("name", "Annotator", "Copyist", "Corrector", "Dedicatee", "Illuminator", "Illustrator", "Owner", "Patron", "inspector")); + entFilters.add(role); + + //alias, "is_prime_alias_name_of", "PERSON" + //alias, "is_alias_name_of", "PERSON" + SEntity person = new SEntity(1, "PERSON"); + person.addAtt(new SAttributeMultipleName("a", "name_translit", "name")); + entFilters.add(person); + + /* + SEntity alias = new SEntity(1, "ALIAS"); + alias.addAtt(new SAttributeUniqueName("alias", "abu")); + entFilters.add(alias); + */ + + SEntity title = new SEntity(2, "TEXT"); + //title.addAtt(new SAttributeMultipleName("abu", "full_title_translit", "full_title")); + entFilters.add(title); + + + SRelationUniqueName has_role = new SRelationUniqueName(person, role, "has_role"); + SRelationMultipleName title_to_person = new SRelationMultipleName(title, person, "had_patron", "was_dedicated_to", "was_created_by"); + relFilters.add(title_to_person); + relFilters.add(has_role); + + List<ResultEntry> rs = getAppBean().getSS().search(entFilters, relFilters); + + return rs; + } + + /** + * 6) Bring up people associated with a particular title (not just one huge list of people, but be able to distinguish author, student, teacher) + * @return + */ + private List<ResultEntry> sample06(){ + + List<SEntity> entFilters = new ArrayList<SEntity>(); + List<SRelation> relFilters = new ArrayList<SRelation>(); + + //The user can select between: + //"Author", "Annotator", "Copyist", "Corrector", "Dedicatee", "Illuminator", "Illustrator", "Owner", "Patron", "inspector" + SEntity role = new SEntity(0, "ROLE"); + role.addAtt(new SAttributeUniqueName("name", "Annotator")); + entFilters.add(role); + + //alias, "is_prime_alias_name_of", "PERSON" + //alias, "is_alias_name_of", "PERSON" + SEntity person = new SEntity(1, "PERSON"); + person.addAtt(new SAttributeMultipleName("a", "name_translit", "name")); + entFilters.add(person); + + /* + SEntity alias = new SEntity(1, "ALIAS"); + alias.addAtt(new SAttributeUniqueName("alias", "abu")); + entFilters.add(alias); + */ + + SEntity title = new SEntity(2, "TEXT"); + title.addAtt(new SAttributeMultipleName("abu", "full_title_translit", "full_title")); + entFilters.add(title); + + + SRelationUniqueName has_role = new SRelationUniqueName(person, role, "has_role"); + SRelationMultipleName title_to_person = new SRelationMultipleName(title, person, "had_patron", "was_dedicated_to", "was_created_by"); + relFilters.add(title_to_person); + relFilters.add(has_role); + + List<ResultEntry> rs = getAppBean().getSS().search(entFilters, relFilters); + + return rs; + + } + + /** + * 7) Bring up people associated with a particular witness (not just one huge list of people, but be able to distinguish owner, say, from commentator) + * @return + */ + private List<ResultEntry> sample07(){ + + List<SEntity> entFilters = new ArrayList<SEntity>(); + List<SRelation> relFilters = new ArrayList<SRelation>(); + + //The user can select between: + //"Author", "Annotator", "Copyist", "Corrector", "Dedicatee", "Illuminator", "Illustrator", "Owner", "Patron", "inspector" + SEntity role = new SEntity(0, "ROLE"); + role.addAtt(new SAttributeUniqueName("name", "Owner")); + entFilters.add(role); + + //alias, "is_prime_alias_name_of", "PERSON" + //alias, "is_alias_name_of", "PERSON" + SEntity person = new SEntity(1, "PERSON"); + person.addAtt(new SAttributeMultipleName("a", "name_translit", "name")); + entFilters.add(person); + + /* + SEntity alias = new SEntity(1, "ALIAS"); + alias.addAtt(new SAttributeUniqueName("alias", "abu")); + entFilters.add(alias); + */ + + SEntity witness = new SEntity(2, "WITNESS"); + //witness.addAtt(new SAttributeMultipleName("abu", "full_title_translit", "full_title")); + entFilters.add(witness); + + + SRelationUniqueName has_role = new SRelationUniqueName(person, role, "has_role"); + SRelationMultipleName witness_to_person = new SRelationMultipleName(witness, person, "had_patron", "was_copied_by", "was_created_by", "was_studied_by"); + relFilters.add(witness_to_person); + relFilters.add(has_role); + + List<ResultEntry> rs = getAppBean().getSS().search(entFilters, relFilters); + + return rs; + + } + + /** + * 9) Bring up all owners of a particular codex + * @return + */ + private List<ResultEntry> sample08(){ + + List<SEntity> entFilters = new ArrayList<SEntity>(); + List<SRelation> relFilters = new ArrayList<SRelation>(); + + //The user can select between: + //"Author", "Annotator", "Copyist", "Corrector", "Dedicatee", "Illuminator", "Illustrator", "Owner", "Patron", "inspector" + SEntity role = new SEntity(0, "ROLE"); + role.addAtt(new SAttributeUniqueName("name", "Owner")); + entFilters.add(role); + + //alias, "is_prime_alias_name_of", "PERSON" + //alias, "is_alias_name_of", "PERSON" + SEntity person = new SEntity(1, "PERSON"); + person.addAtt(new SAttributeMultipleName("a", "name_translit", "name")); + entFilters.add(person); + + /* + SEntity alias = new SEntity(1, "ALIAS"); + alias.addAtt(new SAttributeUniqueName("alias", "abu")); + entFilters.add(alias); + */ + + SEntity codex = new SEntity(2, "CODEX"); + //witness.addAtt(new SAttributeMultipleName("abu", "full_title_translit", "full_title")); + entFilters.add(codex); + + SRelationUniqueName has_role = new SRelationUniqueName(person, role, "has_role"); + SRelationUniqueName was_owned_by = new SRelationUniqueName(codex, person, "was_owned_by"); + relFilters.add(was_owned_by); + relFilters.add(has_role); + + List<ResultEntry> rs = getAppBean().getSS().search(entFilters, relFilters); + + return rs; + + } + + /* + private void printRs(List<ResultEntry> rs){ + logger.info("--------------"); + for(ResultEntry entry : rs){ + for(Entry<Integer, Long> ent : entry.getEntMap().entrySet()){ + logger.info(ent.getKey() + ") " + getWrapper().getEntityById(ent.getValue()).toSmallString()); + } + } + logger.info("--------------"); + }*/ + + public String getCurrentTemplate() { + return currentTemplate; + } + + public void setCurrentTemplate(String currentTemplate) { + this.currentTemplate = currentTemplate; + } + + public List<SelectItem> getTemplateList() { + return templateList; + } + + public Titles4PersonQuery getTitles4PersonQuery() { + return titles4PersonQuery; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/search/beans/CodexOwnershipQuery.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,219 @@ +package de.mpiwg.itgroup.ismi.search.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Relation; +import org.mpi.openmind.search.utils.ResultEntry; +import org.mpi.openmind.search.utils.SAttributeMultipleName; +import org.mpi.openmind.search.utils.SEntity; +import org.mpi.openmind.search.utils.SRelation; + +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; + +public class CodexOwnershipQuery extends AbstractQuery{ + + private static final long serialVersionUID = 5481872257359678512L; + + private String personName; + private String codexShelfMark; + + public CodexOwnershipQuery(ApplicationBean appBean){ + super(appBean); + this.exportUrlRoot = ApplicationBean.urlISMIExportServiceAuthors; + } + + @Override + public void reset(){ + super.reset(); + this.rs = null; + this.personName = null; + this.codexShelfMark = null; + } + + @Override + protected void search() throws Exception{ + + List<Relation> wasOwnerByList = appBean.getWrapper().getRelation("owned_by", "CODEX", "PERSON"); + List<Long> personCandidates = null; + List<Long> codexCadidates = null; + + if(StringUtils.isNotEmpty(personName)){ + personCandidates = getPersonCadidates(personName); + } + if(StringUtils.isNotEmpty(codexShelfMark)){ + codexCadidates = getCodexCadidates(codexShelfMark); + } + + rs = this.loadResultSet(wasOwnerByList, personCandidates, codexCadidates); + + /* + * TODO there is report for it??? + List<Long> idLongList = new ArrayList<Long>(); + for(Object e : rs){ + Titles4PersonEntry entry = (Titles4PersonEntry)e; + if(!idLongList.contains(entry.getPersonId())) + idLongList.add(entry.getPersonId()); + } + this.idList = ApplicationBean.generateIdList(idLongList); + + this.exportDirkUrl = ApplicationBean.generateExportURL(exportUrlRoot, idList, "xml"); + */ + } + + private List<CodexOwnershipEntry> loadResultSet(List<Relation> wasOwnerByList, + List<Long> personCandidates, + List<Long> codexCadidates){ + + List<CodexOwnershipEntry> list = new ArrayList<CodexOwnershipQuery.CodexOwnershipEntry>(); + + if(!wasOwnerByList.isEmpty()){ + for(Relation rel : wasOwnerByList){ + if((codexCadidates == null || codexCadidates.contains(rel.getSourceId())) && + (personCandidates == null ||personCandidates.contains(rel.getTargetId()))){ + list.add(new CodexOwnershipEntry( + appBean.getWrapper().getEntityById(rel.getSourceId()), appBean.getWrapper().getEntityById(rel.getTargetId()), + appBean.getWrapper())); + } + } + } + + return list; + } + + + public String getPersonName() { + return personName; + } + + public void setPersonName(String personName) { + this.personName = personName; + } + + public String getCodexShelfMark() { + return codexShelfMark; + } + + public void setCodexShelfMark(String codexShelfMark) { + this.codexShelfMark = codexShelfMark; + } + + private List<Long> getPersonCadidates(String personName){ + List<SEntity> entFilters = new ArrayList<SEntity>(); + + //TODO + //alias, "is_prime_alias_name_of", "PERSON" + //alias, "is_alias_name_of", "PERSON" + SEntity person = new SEntity(0, "PERSON"); + if(StringUtils.isNotEmpty(personName)){ + person.addAtt(new SAttributeMultipleName(personName, "name_translit", "name")); + } + entFilters.add(person); + + List<Long> idList = new ArrayList<Long>(); + for(ResultEntry entry : this.appBean.getSS().search(entFilters, new ArrayList<SRelation>())){ + idList.add(entry.getEntMap().get(0)); + } + return idList; + } + + private List<Long> getCodexCadidates(String shelfMark){ + + List<SEntity> entFilters = new ArrayList<SEntity>(); + + SEntity codex = new SEntity(0, "CODEX"); + if(StringUtils.isNotEmpty(shelfMark)){ + codex.addAtt(new SAttributeMultipleName(shelfMark, "identifier")); + } + entFilters.add(codex); + + List<Long> idList = new ArrayList<Long>(); + for(ResultEntry entry : this.appBean.getSS().search(entFilters, new ArrayList<SRelation>())){ + idList.add(entry.getEntMap().get(0)); + } + return idList; + } + + public class CodexOwnershipEntry implements Serializable{ + + private static final long serialVersionUID = -6118835259154299870L; + + private Long personId; + private String personOv; + private Long codexId; + private String codexOv; + private String shelfMark; + private String collection; + + public CodexOwnershipEntry(Entity codex, Entity person, WrapperService ws){ + this.personId = person.getId(); + this.personOv = person.getOwnValue(); + this.codexId = codex.getId(); + this.codexOv = codex.getOwnValue(); + //this.shelfMark = (codex.getAttributeByName("identifier") != null) ? codex.getAttributeByName("identifier").getOwnValue() : null; + try{ + String[] array = this.codexOv.split("_"); + if(array.length > 0){ + this.collection = array[0]; + this.shelfMark = array[1]; + } + }catch (Exception e) { + e.printStackTrace(); + } + } + + public Long getPersonId() { + return personId; + } + + public void setPersonId(Long personId) { + this.personId = personId; + } + + public String getPersonOv() { + return personOv; + } + + public void setPersonOv(String personOv) { + this.personOv = personOv; + } + + public Long getCodexId() { + return codexId; + } + + public void setCodexId(Long codexId) { + this.codexId = codexId; + } + + public String getCodexOv() { + return codexOv; + } + + public void setCodexOv(String codexOv) { + this.codexOv = codexOv; + } + + public String getShelfMark() { + return shelfMark; + } + + public void setShelfMark(String shelfMark) { + this.shelfMark = shelfMark; + } + + public String getCollection() { + return collection; + } + + public void setCollection(String collection) { + this.collection = collection; + } + } + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/search/beans/DisplayAuthorBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,168 @@ +package de.mpiwg.itgroup.ismi.search.beans; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.log4j.Logger; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.auxObjects.SelectItem0; +import de.mpiwg.itgroup.ismi.entry.utils.PrivacityUtils; +import de.mpiwg.itgroup.ismi.utils.templates.AuthorTemplate; + +public class DisplayAuthorBean extends DisplayBean { + + /** + * + */ + private static final long serialVersionUID = -5003760977919749691L; + + private static Logger logger = Logger.getLogger(DisplayAuthorBean.class); + + private AuthorTemplate author; + private Long selectedAuthorId; + + public void showAuthor(Long authorId) { + this.resetDisplay(); + + this.selectedAuthorId = authorId; + Entity entAuthor = getWrapper().getEntityById(authorId); + this.author = new AuthorTemplate(entAuthor, getWrapper()); + + //getting titles + this.titleItems = new ArrayList<SelectItem0>(); + int count = 0; + for(Entity title : getWrapper().getSourcesForTargetRelation(entAuthor.getId(), "was_created_by", TEXT, -1)){ + this.titleItems.add(new SelectItem0(title.getId(), title.getOwnValue() + " [" + title.getId() + "]")); + if(count == 0){ + this.showTitle(title.getId()); + } + count++; + } + + if(this.titleItems.size() > 0){ + this.selectedTitleId = (Long)this.titleItems.get(0).getValue(); + this.listenerShowTitle0(null); + } + } + + @Override + protected void resetDisplay(){ + super.resetDisplay(); + this.titleItems = new ArrayList<SelectItem0>(); + } + + + /* + public void listenerShowTitle(ValueChangeEvent event) { + if (event != null && event.getNewValue() != null) { + this.redirect(null, "?personId=" + selectedAuthorId + "&textId=" + (Long)event.getNewValue() + "#titles"); + } + }*/ + + public void listenerShowTitle0(ActionEvent event){ + SelectItem0 item = (SelectItem0)getRequestBean("titleItem"); + if(item != null){ + this.redirect(null, "?personId=" + selectedAuthorId + "&textId=" + item.getValue() + "#titles"); + } + } + + public String actionTest(){ + System.out.println("actionTest"); + return null; + } + + /* + @Override + public void listenerShowWitness(ValueChangeEvent event) { + if (event != null && event.getNewValue() != null) { + this.redirect(null, "?personId=" + selectedAuthorId + "&textId=" + selectedTitleId + "&witnessId=" + (Long)event.getNewValue() + "#witnesses"); + } + }*/ + + @Override + public void listenerShowWitness0(ActionEvent event){ + SelectItem0 item = (SelectItem0)getRequestBean("witnessItem"); + if (item != null) { + this.redirect(null, "?personId=" + selectedAuthorId + "&textId=" + selectedTitleId + "&witnessId=" + item.getValue() + "#witnesses"); + } + } + + public String actionEditAuthor(){ + if(this.selectedAuthorId != null){ + getSessionBean().editEntity(getWrapper().getEntityById(selectedAuthorId)); + return "entry_edit_entity"; + } + return ""; + } + + //Privacity author + public void changePrivacity4Person(ActionEvent event){ + try { + if(this.selectedAuthorId != null){ + List<Entity> saveList = PrivacityUtils.changePrivacity4Person(getWrapper().getEntityById(selectedAuthorId), null, getWrapper()); + getWrapper().saveEntityListAsNodeWithoutContent(saveList, getUserName()); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + printInternalError(e); + } + } + + //Privacity witness + private void changeAllTitles(boolean privacity) throws Exception{ + List<Entity> saveList = new ArrayList<Entity>(); + for(SelectItem item : titleItems){ + Long id = (Long)item.getValue(); + Entity title = getWrapper().getEntityById(id); + saveList.addAll(PrivacityUtils.changePrivacity4Title(title, privacity, getWrapper())); + } + getWrapper().saveEntityListAsNodeWithoutContent(saveList, getUserName()); + this.showTitle(selectedTitleId); + } + + public void listenerMakeAllTitlesPublic(ActionEvent event){ + try { + logger.debug("listenerMakeAllTitlesPublic"); + this.changeAllTitles(true); + } catch (Exception e) { + logger.error(e.getMessage(), e); + printInternalError(e); + } + } + + public void listenerMakeAllTitlesPrivate(ActionEvent event){ + try { + logger.debug("listenerMakeAllTitlesPrivate"); + this.changeAllTitles(false); + } catch (Exception e) { + logger.error(e.getMessage(), e); + printInternalError(e); + } + + } + + //getters and setters + + public int getTitleItemsSize(){ + if(titleItems != null) + return titleItems.size(); + return 0; + } + + public Long getSelectedAuthorId() { + return selectedAuthorId; + } + + public AuthorTemplate getAuthor() { + return author; + } + + public List<SelectItem0> getTitleItems() { + return titleItems; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/search/beans/DisplayBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,236 @@ +package de.mpiwg.itgroup.ismi.search.beans; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpiwg.itgroup.escidoc.ESciDocHandler; +import org.mpiwg.itgroup.escidoc.bo.Publication; + +import de.mpiwg.itgroup.ismi.auxObjects.SelectItem0; +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; +import de.mpiwg.itgroup.ismi.entry.utils.PrivacityUtils; +import de.mpiwg.itgroup.ismi.util.guiComponents.HtmlOption; +import de.mpiwg.itgroup.ismi.utils.templates.TitleTemplate; +import de.mpiwg.itgroup.ismi.utils.templates.WitnessTemplate; + +public class DisplayBean extends AbstractISMIBean { + + /** + * + */ + private static final long serialVersionUID = 1296816397468908012L; + + private static Logger logger = Logger.getLogger(DisplayBean.class); + + protected TitleTemplate title; + protected WitnessTemplate witness; + + //Witness elements + protected List<SelectItem0> witnessItems = new ArrayList<SelectItem0>(); + protected Long selectedWitnessId; + + //Title elements + protected Long selectedTitleId; + protected List<SelectItem0> titleItems = new ArrayList<SelectItem0>(); + + protected void resetDisplay(){ + this.witness = null; + this.selectedWitnessId = null; + this.title = null; + this.selectedTitleId = null; + this.witnessItems = new ArrayList<SelectItem0>(); + } + + public void showTitle(Long textId){ + this.selectedTitleId = textId; + + this.witness = null; + this.witnessItems = new ArrayList<SelectItem0>(); + this.selectedWitnessId = null; + + long start = System.currentTimeMillis(); + + Entity entTitle = getWrapper().getEntityById(this.selectedTitleId); + + if(this.selectedTitleId != null){ + + this.titleItems = SelectItem0.valueChange(titleItems, textId); + this.title = new TitleTemplate(entTitle, getWrapper(), false); + + //****** getting witnesses ********************** + long startWitness = System.currentTimeMillis(); + List<Entity> list = getWrapper().getSourcesForTargetRelation(selectedTitleId, is_exemplar_of, WITNESS, -1); + for(Entity src : list){ + SelectItem0 item = new SelectItem0(src.getId(), src.getOwnValue() + " [" + src.getId() + "]", true); + this.witnessItems.add(item); + } + + if(list.size() > 0){ + this.showWitness(list.get(0).getId()); + } + + long diff = System.currentTimeMillis() - startWitness; + if(diff > 1000){ + logger.info("Time - listenerShowTitle().getSourcesForTargetRelation(title, 'X', WITNESS, -1) = " + diff + " [ms], Text id= " + this.selectedTitleId); + + } + //************************************************ + } + long diff = System.currentTimeMillis() - start; + + if(diff > 1000){ + logger.info("Time - listenerShowTitle() " + diff + " [ms], Text id= " + this.selectedTitleId); + } + } + + + public void listenerShowWitness0(ActionEvent event){ + SelectItem0 item = (SelectItem0)getRequestBean("witnessItem"); + if (item != null) { + this.redirect(null, "?textId=" + selectedTitleId + "&witnessId=" + item.getValue() + "#witnesses"); + } + } + + + public void showWitness(Long selectedWitnessId) { + + this.selectedWitnessId = selectedWitnessId; + + if (this.selectedWitnessId != null) { + this.witnessItems = SelectItem0.valueChange(witnessItems, selectedWitnessId); + Entity entWitness = getWrapper().getEntityById(selectedWitnessId); + + if (entWitness != null) { + this.witness = new WitnessTemplate(entWitness, getWrapper(), true); + } + } + } + + /** + * This method is called from the result of the simple search. It will set the title(text) into the currentText to be edited. + * @return + */ + public String actionEditTitle() { + if(this.selectedTitleId != null){ + getSessionBean().editEntity(getWrapper().getEntityById(selectedTitleId)); + return "entry_edit_entity"; + } + return ""; + } + + /** + * This method is called from the result of the simple search. It will set + * the witness into the currentWitness to be edited. + * + * @return + */ + public String actionEditWitness() { + if (this.selectedWitnessId != null) { + getSessionBean().editEntity(getWrapper().getEntityById(selectedWitnessId)); + return "entry_edit_entity"; + } + return ""; + } + + //Privacity titles + public void changePrivacity4Title(ActionEvent event){ + try { + if(selectedTitleId != null){ + List<Entity> saveList = PrivacityUtils.changePrivacity4Title(getWrapper().getEntityById(selectedTitleId), null, getWrapper()); + getWrapper().saveEntityListAsNodeWithoutContent(saveList, getUserName()); + this.showTitle(selectedTitleId); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + printInternalError(e); + } + } + + //Privacity witnesses + public void changePrivacity4Witness(ActionEvent event){ + try { + if(selectedWitnessId != null){ + List<Entity> saveList = PrivacityUtils.changePrivacity4Witness(getWrapper().getEntityById(selectedWitnessId), null, getWrapper()); + getWrapper().saveEntityListAsNodeWithoutContent(saveList, getUserName()); + this.showWitness(selectedWitnessId); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + printInternalError(e); + } + + } + + private void changeAllWitnesses(boolean privacity) throws Exception{ + List<Entity> saveList = new ArrayList<Entity>(); + for(SelectItem item : witnessItems){ + Long id = (Long)item.getValue(); + Entity witness = getWrapper().getEntityById(id); + saveList.addAll(PrivacityUtils.changePrivacity4Witness(witness, privacity, getWrapper())); + } + getWrapper().saveEntityListAsNodeWithoutContent(saveList, getUserName()); + this.showWitness(selectedWitnessId); + } + + public void listenerMakeAllWitnessesPublic(ActionEvent event){ + try { + this.changeAllWitnesses(true); + } catch (Exception e) { + logger.error(e.getMessage(), e); + printInternalError(e); + } + } + + public void listenerMakeAllWitnessesPrivate(ActionEvent event){ + try { + this.changeAllWitnesses(false); + } catch (Exception e) { + logger.error(e.getMessage(), e); + printInternalError(e); + } + + } + + public int getWitnessItemsSize() { + if(witnessItems != null) + return witnessItems.size(); + return 0; + } + + public TitleTemplate getTitle() { + return title; + } + + public WitnessTemplate getWitness() { + return witness; + } + + public List<SelectItem0> getWitnessItems() { + return witnessItems; + } + + public Long getSelectedWitnessId() { + return selectedWitnessId; + } + + public Long getSelectedTitleId() { + return selectedTitleId; + } + + public void setSelectedWitnessId(Long selectedWitnessId) { + this.selectedWitnessId = selectedWitnessId; + } + + public void setSelectedTitleId(Long selectedTitleId) { + this.selectedTitleId = selectedTitleId; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/search/beans/DisplayTitleBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,12 @@ +package de.mpiwg.itgroup.ismi.search.beans; + + +public class DisplayTitleBean extends DisplayBean { + + /** + * + */ + private static final long serialVersionUID = -1585311468487920580L; + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/search/beans/SampleSearch06.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,364 @@ +package de.mpiwg.itgroup.ismi.search.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.utils.NormalizerUtils; +import org.mpi.openmind.repository.utils.TransliterationUtil; +import org.mpi.openmind.search.utils.ResultEntry; +import org.mpi.openmind.search.utils.SAttributeMultipleName; +import org.mpi.openmind.search.utils.SAttributeUniqueName; +import org.mpi.openmind.search.utils.SEntity; +import org.mpi.openmind.search.utils.SRelLongKey; +import org.mpi.openmind.search.utils.SRelation; +import org.mpi.openmind.search.utils.SRelationMultipleName; +import org.mpi.openmind.search.utils.SRelationUniqueName; + +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; + +/** + * 7) Bring up people associated with a particular witness + * (not just one huge list of people, but be able to distinguish owner, say, from commentator) + * @author jurzua + * + */ +public class SampleSearch06 extends AbstractQuery implements Serializable{ + + private static final long serialVersionUID = 3749889381908517654L; + private String personName; + private String roleName = "Author"; + private static List<SelectItem> roleList; + + + //"Author", "Annotator", "Copyist", "Corrector", "Dedicatee", "Illuminator", "Illustrator", "Owner", "Patron", "inspector" + static{ + roleList = new ArrayList<SelectItem>(); + roleList.add(new SelectItem("Author")); + roleList.add(new SelectItem("Annotator")); + roleList.add(new SelectItem("Copyist")); + roleList.add(new SelectItem("Corrector")); + roleList.add(new SelectItem("Dedicatee")); + roleList.add(new SelectItem("Illuminator")); + roleList.add(new SelectItem("Illustrator")); + roleList.add(new SelectItem("Owner")); + roleList.add(new SelectItem("Patron")); + roleList.add(new SelectItem("Inspector")); + } + + + public SampleSearch06(ApplicationBean appBean){ + super(appBean); + this.exportUrlRoot = ApplicationBean.urlISMIExportServiceAuthors; + } + + @Override + public void reset(){ + super.reset(); + this.personName = null; + this.roleName = "Author"; + this.rs = null; + this.personTitleKeyList = null; + } + + @Override + protected void search(){ + + List<ResultEntry> rs0 = this.execute01(personName, roleName); + List<ResultEntry> rs1 = null; + if(StringUtils.isNotEmpty(personName)){ + rs1 = this.execute02(personName, roleName); + } + rs = loadResultSet(rs0, rs1); + + List<Long> idLongList = new ArrayList<Long>(); + for(Object e : rs){ + ResultEntry06 entry = (ResultEntry06)e; + if(!idLongList.contains(entry.getPersonId())) + idLongList.add(entry.getPersonId()); + } + this.idList = ApplicationBean.generateIdList(idLongList); + + this.exportDirkUrl = ApplicationBean.generateExportURL(exportUrlRoot, idList, "xml"); + } + + private List<ResultEntry06> loadResultSet(List<ResultEntry> rs0, List<ResultEntry> rs1){ + List<ResultEntry06> currentRs = new ArrayList<SampleSearch06.ResultEntry06>(); + personTitleKeyList = new ArrayList<SRelLongKey>(); + + for(ResultEntry re : rs0){ + + Entity person = getOm().getEntityById(re.getEntMap().get(1)); + Entity title = getOm().getEntityById(re.getEntMap().get(2)); + + String alias = null; + String alias2Person = null; + String role = this.roleName; + String title2Person = re.getRel(2, 1); + List<Entity> subjectList = getOm().getTargetsForSourceRelation(title.getId(), "has_subject", "SUBJECT", 1); + String subject = (subjectList.size() == 0) ? null : subjectList.get(0).getOwnValue(); + + currentRs.add(new ResultEntry06(person, title, alias, alias2Person, role, title2Person, subject)); + putPersonTitleKey(person.getId(), title.getId()); + } + if(rs1 != null){ + for(ResultEntry re : rs1){ + Entity person = getOm().getEntityById(re.getEntMap().get(1)); + Entity title = getOm().getEntityById(re.getEntMap().get(3)); + if(!containsPersonTitleKey(person.getId(), title.getId())){ + + String alias = getOm().getEntityById(re.getEntMap().get(2)).getOwnValue(); + String alias2Person = re.getRel(2, 1); + String role = this.roleName; + String title2Person = re.getRel(3, 1); + List<Entity> subjectList = getOm().getTargetsForSourceRelation(title.getId(), "has_subject", "SUBJECT", 1); + String subject = (subjectList.size() == 0) ? null : subjectList.get(0).getOwnValue(); + + currentRs.add(new ResultEntry06(person, title, alias, alias2Person, role, title2Person, subject)); + putPersonTitleKey(person.getId(), title.getId()); + } + } + } + + Collections.sort(currentRs); + + return currentRs; + } + + private List<SRelLongKey> personTitleKeyList; + private boolean containsPersonTitleKey(Long personId, Long titleId){ + return personTitleKeyList.contains(new SRelLongKey(personId, titleId)); + } + private void putPersonTitleKey(Long personId, Long titleId){ + personTitleKeyList.add(new SRelLongKey(personId, titleId)); + } + + + + private List<ResultEntry> execute01(String personName, String roleName){ + + List<SEntity> entFilters = new ArrayList<SEntity>(); + List<SRelation> relFilters = new ArrayList<SRelation>(); + + //The user can select between: + //"Author", "Annotator", "Copyist", "Corrector", "Dedicatee", "Illuminator", "Illustrator", "Owner", "Patron", "inspector" + SEntity role = new SEntity(0, "ROLE"); + role.addAtt(new SAttributeUniqueName("name", roleName)); + entFilters.add(role); + + //alias, "is_prime_alias_name_of", "PERSON" + //alias, "is_alias_name_of", "PERSON" + SEntity person = new SEntity(1, "PERSON"); + if(StringUtils.isNotEmpty(personName)){ + person.addAtt(new SAttributeMultipleName(personName, "name_translit", "name")); + } + entFilters.add(person); + + SEntity text = new SEntity(2, "TEXT"); + entFilters.add(text); + + + SRelationUniqueName has_role = new SRelationUniqueName(person, role, "has_role"); + SRelationMultipleName text_to_person = new SRelationMultipleName(text, person, "was_created_by", "had_patron", "was_dedicated_to"); + relFilters.add(text_to_person); + relFilters.add(has_role); + + return this.appBean.getSS().search(entFilters, relFilters); + } + + private List<ResultEntry> execute02(String personName, String roleName){ + + List<SEntity> entFilters = new ArrayList<SEntity>(); + List<SRelation> relFilters = new ArrayList<SRelation>(); + + //The user can select between: + //"Author", "Annotator", "Copyist", "Corrector", "Dedicatee", "Illuminator", "Illustrator", "Owner", "Patron", "inspector" + SEntity role = new SEntity(0, "ROLE"); + role.addAtt(new SAttributeUniqueName("name", roleName)); + entFilters.add(role); + + //alias, "is_prime_alias_name_of", "PERSON" + //alias, "is_alias_name_of", "PERSON" + SEntity person = new SEntity(1, "PERSON"); + entFilters.add(person); + + SEntity alias = new SEntity(2, "ALIAS"); + alias.addAtt(new SAttributeUniqueName("alias", personName)); + entFilters.add(alias); + + SEntity text = new SEntity(3, "TEXT"); + entFilters.add(text); + + + SRelationMultipleName is_alias = new SRelationMultipleName(alias, person, "is_alias_name_of", "is_prime_alias_name_of"); + SRelationUniqueName has_role = new SRelationUniqueName(person, role, "has_role"); + SRelationMultipleName text_to_person = new SRelationMultipleName(text, person, "was_created_by", "had_patron", "was_dedicated_to"); + relFilters.add(text_to_person); + relFilters.add(has_role); + relFilters.add(is_alias); + + return this.appBean.getSS().search(entFilters, relFilters); + } + + + public String getPersonName() { + return personName; + } + + public void setPersonName(String personName) { + this.personName = personName; + } + + public String getRoleName() { + return roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + public List<SelectItem> getRoleList() { + return roleList; + } + + public class ResultEntry06 implements Comparable<ResultEntry06>, Serializable{ + private static final long serialVersionUID = 3814421582310240565L; + + private Long personId; + private String personOv; + private String personNOv; + private String alias; + private String alias2Person; + private Long titleId; + private String titleOv; + private String titleNOv; + private String role; + private String title2Person; + private String subject; + + public ResultEntry06( + Entity person, + Entity title, + String alias, + String alias2Person, + String role, + String title2Person, + String subject + ){ + + set(person, title); + this.alias = alias; + this.alias2Person = alias2Person; + this.role = role; + this.title2Person = title2Person; + this.subject = subject; + } + + private void set(Entity person, Entity title){ + this.personId = person.getId(); + this.personOv = person.getOwnValue(); + this.personNOv = person.getNormalizedOwnValue(); + + this.titleId = title.getId(); + this.titleOv = title.getOwnValue(); + this.titleNOv = title.getNormalizedOwnValue(); + } + + public Long getPersonId() { + return personId; + } + + public String getPersonOv() { + return personOv; + } + + public String getPersonNOv() { + return personNOv; + } + + public String getAlias() { + return alias; + } + + public String getAlias2Person() { + return alias2Person; + } + + public Long getTitleId() { + return titleId; + } + + public String getTitleOv() { + return titleOv; + } + + public String getTitleNOv() { + return titleNOv; + } + + public String getRole() { + return role; + } + + public String getTitle2Person() { + return title2Person; + } + + public String getSubject() { + return subject; + } + + @Override + public int compareTo(ResultEntry06 o) { + if(!this.personId.equals(o.personId)){ + + int comparisonPerson = NormalizerUtils.normalizedToCompare(personNOv).compareTo( + NormalizerUtils.normalizedToCompare(o.personNOv)); + if(comparisonPerson != 0){ + return comparisonPerson; + }else{ + if(StringUtils.isNotEmpty(role) && StringUtils.isNotEmpty(o.role)){ + int comparisonRole = this.role.compareTo(o.role); + if(comparisonRole != 0){ + return comparisonRole; + } + }else{ + if(StringUtils.isNotEmpty(role)){ + return -1; + }else if(StringUtils.isNotEmpty(o.role)){ + return 1; + } + } + } + }else{ + if(!this.titleId.equals(o.titleId)){ + //comparing subject + if(StringUtils.isNotEmpty(subject) && StringUtils.isNotEmpty(o.subject)){ + int comparisonSubject = this.subject.compareTo(o.subject); + if(comparisonSubject != 0){ + return comparisonSubject; + } + }else{ + if(StringUtils.isNotEmpty(subject)){ + return -1; + }else if(StringUtils.isNotEmpty(o.subject)){ + return 1; + } + } + //comparing title + int comparisonTitle = NormalizerUtils.normalizedToCompare(titleNOv).compareTo( + NormalizerUtils.normalizedToCompare(o.titleNOv)); + return comparisonTitle; + } + } + return 0; + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/search/beans/SampleSearch07.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,224 @@ +package de.mpiwg.itgroup.ismi.search.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.faces.event.ActionEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.search.utils.ResultEntry; +import org.mpi.openmind.search.utils.SAttributeMultipleName; +import org.mpi.openmind.search.utils.SAttributeUniqueName; +import org.mpi.openmind.search.utils.SEntity; +import org.mpi.openmind.search.utils.SRelation; +import org.mpi.openmind.search.utils.SRelationMultipleName; +import org.mpi.openmind.search.utils.SRelationUniqueName; + +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; + +/** + * 7) Bring up people associated with a particular witness + * (not just one huge list of people, but be able to distinguish owner, say, from commentator) + * @author jurzua + * + */ +public class SampleSearch07 extends AbstractQuery implements Serializable{ + private static final long serialVersionUID = 55883896148547918L; + + private String personName; + private String roleName = "Author"; + private static List<SelectItem> roleList; + private List<ResultEntry07> rs; + + //"Author", "Annotator", "Copyist", "Corrector", "Dedicatee", "Illuminator", "Illustrator", "Owner", "Patron", "inspector" + static{ + roleList = new ArrayList<SelectItem>(); + roleList.add(new SelectItem("Author")); + roleList.add(new SelectItem("Annotator")); + roleList.add(new SelectItem("Copyist")); + roleList.add(new SelectItem("Corrector")); + roleList.add(new SelectItem("Dedicatee")); + roleList.add(new SelectItem("Illuminator")); + roleList.add(new SelectItem("Illustrator")); + roleList.add(new SelectItem("Owner")); + roleList.add(new SelectItem("Patron")); + roleList.add(new SelectItem("Inspector")); + } + + + public SampleSearch07(ApplicationBean appBean){ + super(appBean); + } + + @Override + public void reset(){ + super.reset(); + this.personName = null; + this.roleName = "Author"; + this.rs = null; + } + + @Override + protected void search(){ + List<ResultEntry> rs0 = this.execute(personName, roleName); + //this.printRs(rs, this.appBean.getWrapper()); + + this.rs = new ArrayList<SampleSearch07.ResultEntry07>(); + + int count = 0; + for(ResultEntry re : rs0){ + Entity person = getOm().getEntityById(re.getEntMap().get(1)); + Entity witness = getOm().getEntityById(re.getEntMap().get(2)); + String witness2Person = re.getRel(2, 1); + rs.add(new ResultEntry07( + person.getId(), person.getOwnValue(), + witness.getId(), witness.getOwnValue(), + this.roleName, witness2Person)); + count++; + if(count >= MAX_RS){ + break; + } + } + } + + private List<ResultEntry> execute(String personName, String roleName){ + + List<SEntity> entFilters = new ArrayList<SEntity>(); + List<SRelation> relFilters = new ArrayList<SRelation>(); + + //The user can select between: + //"Author", "Annotator", "Copyist", "Corrector", "Dedicatee", "Illuminator", "Illustrator", "Owner", "Patron", "inspector" + SEntity role = new SEntity(0, "ROLE"); + role.addAtt(new SAttributeUniqueName("name", roleName)); + entFilters.add(role); + + //alias, "is_prime_alias_name_of", "PERSON" + //alias, "is_alias_name_of", "PERSON" + SEntity person = new SEntity(1, "PERSON"); + if(StringUtils.isNotEmpty(personName)){ + person.addAtt(new SAttributeMultipleName(personName, "name_translit", "name")); + } + entFilters.add(person); + + SEntity witness = new SEntity(2, "WITNESS"); + entFilters.add(witness); + + + SRelationUniqueName has_role = new SRelationUniqueName(person, role, "has_role"); + SRelationMultipleName witness_to_person = new SRelationMultipleName(witness, person, "had_patron", "was_copied_by", "was_created_by", "was_studied_by"); + relFilters.add(witness_to_person); + relFilters.add(has_role); + + return this.appBean.getSS().search(entFilters, relFilters); + } + + public String getPersonName() { + return personName; + } + + public void setPersonName(String personName) { + this.personName = personName; + } + + public String getRoleName() { + return roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + public List<SelectItem> getRoleList() { + return roleList; + } + + public List<ResultEntry07> getRs() { + return rs; + } + + @Override + public Integer getRsSize(){ + if(rs != null){ + return rs.size(); + } + return 0; + } + + public class ResultEntry07 implements Serializable{ + private static final long serialVersionUID = -3582904838999322869L; + + private Long personId; + private String personOv; + private Long witnessId; + private String witnessOv; + private String role; + private String witness2Person; + + public ResultEntry07( + Long personId, String personOv, + Long witnessId, String witnessOv, + String role, String witness2Person){ + + this.personId = personId; + this.personOv = personOv; + this.witnessId = witnessId; + this.witnessOv = witnessOv; + this.role = role; + this.witness2Person = witness2Person; + } + + public Long getPersonId() { + return personId; + } + + public void setPersonId(Long personId) { + this.personId = personId; + } + + public String getPersonOv() { + return personOv; + } + + public void setPersonOv(String personOv) { + this.personOv = personOv; + } + + public Long getWitnessId() { + return witnessId; + } + + public void setWitnessId(Long witnessId) { + this.witnessId = witnessId; + } + + public String getWitnessOv() { + return witnessOv; + } + + public void setWitnessOv(String witnessOv) { + this.witnessOv = witnessOv; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public String getWitness2Person() { + return witness2Person; + } + + public void setWitness2Person(String witness2Person) { + this.witness2Person = witness2Person; + } + + + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/search/beans/SearchResultBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,325 @@ +package de.mpiwg.itgroup.ismi.search.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +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.bo.utils.EntitySortByNormalizedOwnValue; +import org.mpi.openmind.repository.services.utils.AttributeFilter; +import org.mpi.openmind.repository.utils.NormalizerUtils; + +import de.mpiwg.itgroup.ismi.auxObjects.ResultSet; +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; + + +public class SearchResultBean extends AbstractISMIBean { + + /** + * + */ + private static final long serialVersionUID = 7072264955252613769L; + public static Long SEC_05 = new Long(5000); + public static Long SEC_10 = new Long(10000); + public static Long SEC_20 = new Long(20000); + public static Long SEC_30 = new Long(30000); + + private List<ResultSet> resultSetList = new ArrayList<ResultSet>(); + + private int maxResult = -1 ; + private int counter = 0; + + public void searchAttributes(String term, String mode){ + long start = System.currentTimeMillis(); + this.resultSetList = new ArrayList<ResultSet>(); + this.counter = 0; + try{ + if (StringUtils.isNotEmpty(term)) { + + boolean includeTitles = (SimpleSearchBean.TITLES.equals(mode) || SimpleSearchBean.AUTHORS_TITLES.equals(mode)) ? true : false; + boolean includeAuthors = (SimpleSearchBean.AUTHORS.equals(mode) || SimpleSearchBean.AUTHORS_TITLES.equals(mode) ? true : false); + + List<AttributeFilter> filters = new ArrayList<AttributeFilter>(); + + AttributeFilter filter1 = new AttributeFilter(); + filter1.setEntObjectClass("PERSON"); + filter1.setName("name"); + //filter1.setNormalize(true); + + AttributeFilter filter2 = new AttributeFilter(); + filter2.setEntObjectClass("TEXT"); + filter2.setName("title"); + //filter2.setNormalize(true); + + AttributeFilter filter3 = new AttributeFilter(); + filter3.setEntObjectClass("PERSON"); + filter3.setName("name_translit"); + + //filter3.setNormalize(true); + + AttributeFilter filter4 = new AttributeFilter(); + filter4.setEntObjectClass("TEXT"); + filter4.setName("title_translit"); + + //filter4.setNormalize(true); + + AttributeFilter filter5 = new AttributeFilter(); + filter5.setEntObjectClass("TEXT"); + filter5.setName("full_title"); + + //filter4.setNormalize(true); + + + AttributeFilter filter6 = new AttributeFilter(); + filter6.setEntObjectClass("TEXT"); + filter6.setName("full_title_translit"); + + + //filers for alias + AttributeFilter filter7 = new AttributeFilter(); + filter7.setEntObjectClass("ALIAS"); + filter7.setName("alias"); + + /* + filter1.setOwnValue(search); + filter2.setOwnValue(search); + filter3.setOwnValue(search); + filter4.setOwnValue(search); + filter5.setOwnValue(search); + filter6.setOwnValue(search); + filter7.setOwnValue(search); + */ + + filters.add(filter1); + filters.add(filter2); + filters.add(filter3); + filters.add(filter4); + filters.add(filter5); + filters.add(filter6); + filters.add(filter7); + + long startQuery = System.currentTimeMillis(); + Map<Attribute, Entity> map; + + if(getCache().isMapDirty()){ + map = getWrapper().searchAttEntityByAttributeFilter(filters, getMaxResult()); + System.out.println(); + System.out.println("###########################################################"); + System.out.println(); + System.out.println("MAP SEARCH SIZEx= " + map.size() + " max result " + getMaxResult()); + /* + for(Attribute a : map.keySet()){ + System.out.println(a); + }*/ + + getCache().setAttResultMap(map); + }else{ + map = getCache().getAttResultMap(); + } + + long endQuery = System.currentTimeMillis(); + String normalizedString = NormalizerUtils.normalize(term); + + System.out.println(""); + System.out.println("***********************"); + System.out.println("Word: " + term); + System.out.println("Normalized: " + normalizedString); + System.out.println("Query Execution= " + (endQuery - startQuery)); + + ResultSet nameResult = new ResultSet("Name"); + ResultSet titleResult = new ResultSet("Title"); + + List<Long> idList = new ArrayList<Long>(); + + int countCached = 0; + int countNoCached = 0; + int noCachedAlias = 0; + int noCachedTextPerson = 0; + int putInCache = 0; + int putInCacheError = 0; + for(Attribute att : map.keySet()){ + + //limiting the execution time. + if((System.currentTimeMillis() - start) > SEC_20 || counter >= 1000) + break; + + //Attribute att = map.get(ent); + Entity ent = map.get(att); + + if(StringUtils.isNotEmpty(att.getNormalizedOwnValue()) && !getCache().ignoreAttribute(att) && att.getNormalizedOwnValue().contains(normalizedString)){ + if(getCache().containsAttribute(att)){ + countCached++; + //if the attributed was saved in the cache + Entity ee = getCache().getEntMap().get(att.getId()); + String description = getCache().getDescriptionMap().get(att.getId() + "-" + ee.getId()); + if(includeAuthors && ee.getObjectClass().equals("PERSON") && !idList.contains(ee.getId())){ + nameResult.setTuple(ee, att); + nameResult.setDescription(ee, description); + //nameResult.setDescription(ee, att.getObjectClass() + "=" + att.getOwnValue()); + counter++; + idList.add(ee.getId()); + }else if(includeTitles && ee.getObjectClass().equals("TEXT") && !idList.contains(ee.getId())){ + titleResult.setTuple(ee, att); + titleResult.setDescription(ee, description); + //titleResult.setDescription(ee, att.getObjectClass() + "=" + att.getOwnValue()); + counter++; + idList.add(ee.getId()); + } + }else{ + + countNoCached++; + if(includeAuthors && !idList.contains(ent.getId()) && att.getName().contains("name") && att.getSourceObjectClass().equals("PERSON")){ + //OC: PERSON + String d = att.getObjectClass() + "=" + att.getOwnValue(); + nameResult.setDescription(ent, d); + nameResult.setTuple(ent, att); + getCache().setTuple(ent, att, d); + counter++; + noCachedTextPerson++; + idList.add(ent.getId()); + }else if(includeTitles && !idList.contains(ent.getId()) && (att.getName().contains("title") || att.getName().contains("full_title"))){ + //OC: TEXT + String d = att.getObjectClass() + "=" + att.getOwnValue(); + titleResult.setDescription(ent, d); + titleResult.setTuple(ent, att); + getCache().setTuple(ent, att, d); + counter++; + noCachedTextPerson++; + idList.add(ent.getId()); + }else if(att.getSourceObjectClass().equals("ALIAS")){ + noCachedAlias++; + //OC: ALIAS + AliasStructure aliasStructure = getAliasStructure(ent, att); + if(aliasStructure.target != null){ + getCache().setTuple(aliasStructure.target, att, aliasStructure.description); + putInCache++; + if(!idList.contains(aliasStructure.target.getId())){ + if(includeAuthors && aliasStructure.target.getObjectClass().equals("PERSON")){ + nameResult.setTuple(aliasStructure.target, att); + nameResult.setDescription(aliasStructure.target, aliasStructure.description); + counter++; + }else if(includeTitles && aliasStructure.target.getObjectClass().equals("TEXT")){ + titleResult.setTuple(aliasStructure.target, att); + titleResult.setDescription(aliasStructure.target, aliasStructure.description); + counter++; + } + idList.add(aliasStructure.target.getId()); + } + }else{ + putInCacheError++; + this.getCache().getIgnoredAttIdList().add(att.getId()); + System.out.println("cacheError++ : " + att); + } + } + + } + } + } + + System.out.println(); + System.out.println("countCached: " + countCached + " - countNoCached: " + countNoCached + " - total: " + (countCached + countNoCached)); + System.out.println("noCachedTextPerson: " + noCachedTextPerson++ + " - noCachedAlias: " + noCachedAlias); + System.out.println("putInCacheError: " + putInCacheError + " - putInCache: " + putInCache); + System.out.println("nameResult: " + nameResult.getResults().size()); + System.out.println("titleResult: " + titleResult.getResults().size()); + + if(nameResult.getResults().size() > 0){ + Collections.sort(nameResult.getResults(), new EntitySortByNormalizedOwnValue()); + this.resultSetList.add(nameResult); + } + if(titleResult.getResults().size() > 0){ + Collections.sort(titleResult.getResults(), new EntitySortByNormalizedOwnValue()); + this.resultSetList.add(titleResult); + } + } + + }catch(Exception e){ + e.printStackTrace(); + } + + long end = System.currentTimeMillis(); + System.out.println("Simple search time execution= " + (end - start)); + } + + /** + * TODO do it more clever! + * rules: + * ----Text + * is_prime_alias_title_of + * is_alias_title_of + * is_alias_incipit_of + * is_alias_explicit_of + * ----Person + * is_prime_alias_name_of + * is_alias_name_of + * @param alias + * @return + */ + private AliasStructure getAliasStructure(Entity alias, Attribute att) throws Exception{ + AliasStructure structure = new AliasStructure(); + structure.aliasAtt = att; + List<Relation> list = null; + list = getWrapper().getSourceRelations(alias, "is_prime_alias_title_of", "TEXT", 1); + if(list.size() > 0) + structure.setRelation(list.get(0)); + list = getWrapper().getSourceRelations(alias, "is_alias_title_of", "TEXT", 1); + if(list.size() > 0) + structure.setRelation(list.get(0)); + list = getWrapper().getSourceRelations(alias, "is_alias_incipit_of", "TEXT", 1); + if(list.size() > 0) + structure.setRelation(list.get(0)); + list = getWrapper().getSourceRelations(alias, "is_alias_explicit_of", "TEXT", 1); + if(list.size() > 0) + structure.setRelation(list.get(0)); + list = getWrapper().getSourceRelations(alias, "is_prime_alias_name_of", "PERSON", 1); + if(list.size() > 0) + structure.setRelation(list.get(0)); + list = getWrapper().getSourceRelations(alias, "is_alias_name_of", "PERSON", 1); + if(list.size() > 0) + structure.setRelation(list.get(0)); + return structure; + } + + public List<ResultSet> getResultSetList() { + return resultSetList; + } + + public void setResultSetList(List<ResultSet> resultSetList) { + this.resultSetList = resultSetList; + } + public int getMaxResult() { + return maxResult; + } + + public void setMaxResult(int maxResult) { + this.maxResult = maxResult; + } + public int getCounter() { + return counter; + } + + public void setCounter(int counter) { + this.counter = counter; + } + private class AliasStructure implements Serializable{ + private static final long serialVersionUID = -833933447985472058L; + + public Entity target = null; + public Entity alias = null; + public Relation rel = null; + public String description = ""; + public Attribute aliasAtt = null; + + public void setRelation(Relation rel){ + this.rel = rel; + this.target = rel.getTarget(); + this.alias = rel.getSource(); + this.description = rel.getOwnValue() + " <- ALIAS [alias=" + aliasAtt.getOwnValue() + "]"; + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/search/beans/SimpleSearchBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,365 @@ +package de.mpiwg.itgroup.ismi.search.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +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.bo.utils.EntitySortByNormalizedOwnValue; +import org.mpi.openmind.repository.services.utils.AttributeFilter; + +import de.mpiwg.itgroup.ismi.auxObjects.ResultSet; +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; +import de.mpiwg.itgroup.ismi.entry.beans.SessionBean; + +public class SimpleSearchBean extends AbstractISMIBean implements Serializable{ + + private static final long serialVersionUID = -1363042229412197533L; + + private static Logger logger = Logger.getLogger(SimpleSearchBean.class); + + public static String NO_ROLE_PERSON = "Person without role"; + + private String inputMethod = "latin"; + private String searchTerm; + + public static List<SelectItem> modeList = new ArrayList<SelectItem>(); + public static String AUTHORS_TITLES = "People and Titles"; + public static String TITLES = "Titles"; + public static String AUTHORS = "People"; + + public static List<AttributeFilter> filters = new ArrayList<AttributeFilter>(); + public static List<AttributeFilter> titlesFilters = new ArrayList<AttributeFilter>(); + public static List<AttributeFilter> authorsFilters = new ArrayList<AttributeFilter>(); + private static AttributeFilter filter1 = new AttributeFilter(); + private static AttributeFilter filter2 = new AttributeFilter(); + private static AttributeFilter filter3 = new AttributeFilter(); + private static AttributeFilter filter4 = new AttributeFilter(); + private static AttributeFilter filter5 = new AttributeFilter(); + private static AttributeFilter filter6 = new AttributeFilter(); + private static AttributeFilter filter7 = new AttributeFilter(); + + private Map<String, ResultSet> resultMap; + private List<String> resultSetNames; + + public String selectedMode; + + static{ + modeList.add(new SelectItem(AUTHORS)); + modeList.add(new SelectItem(TITLES)); + modeList.add(new SelectItem(AUTHORS_TITLES)); + } + + public SimpleSearchBean() { + this.selectedMode = modeList.get(0).getValue().toString(); + } + + + public void listenerSearch(ActionEvent event){ + try { + this.simpleSearchAction(); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + + } + + public void listenerModeValueChange(ValueChangeEvent event){ + this.selectedMode = (String)event.getNewValue(); + } + + public void setInputMethod(String inputMethod) { + this.inputMethod = inputMethod; + } + public String getInputMethod() { + return inputMethod; + } + public void setSearchTerm(String searchTerm) { + this.searchTerm = searchTerm; + } + public String getSearchTerm() { + return searchTerm; + } + + public void simpleSearchAction() throws Exception{ + search0(getSearchTerm(), getSelectedMode()); + } + + public List<SelectItem> getModeList() { + return modeList; + } + + public String getSelectedMode() { + return selectedMode; + } + public void setSelectedMode(String selectedMode) { + this.selectedMode = selectedMode; + } + + //###################################################### + //###################################################### + //###################################################### + + public static Long SEC_05 = new Long(5000); + public static Long SEC_10 = new Long(10000); + public static Long SEC_20 = new Long(20000); + public static Long SEC_30 = new Long(30000); + + private int maxResult = -1 ; + private int counter = 0; + + public void search0(String term, String mode) throws Exception{ + + if (StringUtils.isNotEmpty(term)) { + StringBuilder sb = new StringBuilder(); + long start = System.currentTimeMillis(); + this.resultMap = new HashMap<String, ResultSet>(); + List<Long> usedIdList = new ArrayList<Long>(); + this.counter = 0; + + boolean includeTitles = (SimpleSearchBean.TITLES.equals(mode) || SimpleSearchBean.AUTHORS_TITLES.equals(mode)) ? true : false; + boolean includeAuthors = (SimpleSearchBean.AUTHORS.equals(mode) || SimpleSearchBean.AUTHORS_TITLES.equals(mode) ? true : false); + + Map<Entity, Attribute> map = new HashMap<Entity, Attribute>(); + if(includeAuthors && includeTitles){ + map = getWrapper().searchEntityByAttributeFilter0(term, filters, -1); + }else if(includeAuthors){ + map = getWrapper().searchEntityByAttributeFilter0(term, authorsFilters, -1); + }else if(includeTitles){ + map = getWrapper().searchEntityByAttributeFilter0(term, titlesFilters, -1); + } + //System.out.println("getWrapper().searchEntityByAttributeFilter0= " + (System.currentTimeMillis() - start)); + sb.append("\n\n***********************\n"); + sb.append("getWrapper().searchEntityByAttributeFilter0= " + (System.currentTimeMillis() - start) + "\n"); + + for(Entity ent : map.keySet()){ + if(counter == 1000 || (System.currentTimeMillis() - start) > SEC_20){ + break; + } + Attribute att = map.get(ent); + if(ent.getObjectClass().equals(ALIAS)){ + AliasStructure aliasStructure = getAliasStructure(ent, att); + if(aliasStructure.target != null && !usedIdList.contains(aliasStructure.target.getId())){ + usedIdList.add(aliasStructure.target.getId()); + if(includeAuthors && aliasStructure.target.getObjectClass().equals(PERSON)){ + this.insertPerson(aliasStructure.target, att, aliasStructure.description); + }else if(includeTitles && aliasStructure.target.getObjectClass().equals(TEXT)){ + this.insertTitle(aliasStructure.target, att, aliasStructure.description); + } + } + }else if(!usedIdList.contains(ent.getId())){ + usedIdList.add(ent.getId()); + String d = att.getObjectClass() + "=" + att.getOwnValue(); + if(ent.getObjectClass().equals(PERSON)){ + this.insertPerson(ent, att, d); + }else if(ent.getObjectClass().equals(TEXT)){ + this.insertTitle(ent, att, d); + } + } + } + + for(String key : resultMap.keySet()){ + ResultSet rs = resultMap.get(key); + //System.out.println(key + "= " + rs.getResults().size()); + Collections.sort(rs.getResults(), new EntitySortByNormalizedOwnValue()); + } + + this.resultSetNames = new ArrayList<String>(getResultMap().keySet()); + Collections.sort(this.resultSetNames); + + + long end = System.currentTimeMillis(); + sb.append("Word: " + term + "\n"); + sb.append("includeTitles: " + includeTitles + "\n"); + sb.append("includeAuthors: " + includeAuthors + "\n"); + sb.append("Simple search time execution= " + (end - start) + "\n"); + sb.append("***********************\n"); + sb.append("\n"); + logger.info(sb.toString()); + + } + } + + private void insertTitle(Entity ent, Attribute att, String description){ + if(resultMap.get("Title") == null){ + resultMap.put("Title", new ResultSet("Title")); + } + resultMap.get("Title").setTuple(ent, att); + resultMap.get("Title").setDescription(ent, description); + counter++; + } + + private void insertPerson(Entity ent, Attribute att, String description){ + List<String> roleNameList = getCache().getRoleList(ent.getId()); + for(String roleName : getCache().getRoleList(ent.getId())){ + if(resultMap.get(roleName) == null){ + resultMap.put(roleName, new ResultSet(roleName)); + } + resultMap.get(roleName).setTuple(ent, att); + resultMap.get(roleName).setDescription(ent, description); + } + if(roleNameList.isEmpty()){ + if(resultMap.get(NO_ROLE_PERSON) == null){ + resultMap.put(NO_ROLE_PERSON, new ResultSet(NO_ROLE_PERSON)); + } + resultMap.get(NO_ROLE_PERSON).setTuple(ent, att); + resultMap.get(NO_ROLE_PERSON).setDescription(ent, description); + } + counter++; + } + + public List<String> getResultSetNames(){ + return this.resultSetNames; + } + + /** + * TODO do it more clever! + * rules: + * ----Text + * is_prime_alias_title_of + * is_alias_title_of + * is_alias_incipit_of + * is_alias_explicit_of + * ----Person + * is_prime_alias_name_of + * is_alias_name_of + * @param alias + * @return + */ + private AliasStructure getAliasStructure(Entity alias, Attribute att) throws Exception{ + AliasStructure structure = new AliasStructure(); + structure.aliasAtt = att; + List<Relation> list = null; + list = getWrapper().getSourceRelations(alias, "is_prime_alias_title_of", "TEXT", 1); + if(list.size() > 0) + structure.setRelation(list.get(0)); + list = getWrapper().getSourceRelations(alias, "is_alias_title_of", "TEXT", 1); + if(list.size() > 0) + structure.setRelation(list.get(0)); + list = getWrapper().getSourceRelations(alias, "is_alias_incipit_of", "TEXT", 1); + if(list.size() > 0) + structure.setRelation(list.get(0)); + list = getWrapper().getSourceRelations(alias, "is_alias_explicit_of", "TEXT", 1); + if(list.size() > 0) + structure.setRelation(list.get(0)); + list = getWrapper().getSourceRelations(alias, "is_prime_alias_name_of", "PERSON", 1); + if(list.size() > 0) + structure.setRelation(list.get(0)); + list = getWrapper().getSourceRelations(alias, "is_alias_name_of", "PERSON", 1); + if(list.size() > 0) + structure.setRelation(list.get(0)); + return structure; + } + + public int getMaxResult() { + return maxResult; + } + + public void setMaxResult(int maxResult) { + this.maxResult = maxResult; + } + public int getCounter() { + return counter; + } + + public void setCounter(int counter) { + this.counter = counter; + } + + + public Map<String, ResultSet> getResultMap() { + return resultMap; + } + + + public void setResultMap(Map<String, ResultSet> resultMap) { + this.resultMap = resultMap; + } + + private class AliasStructure{ + public Entity target = null; + public Entity alias = null; + public Relation rel = null; + public String description = ""; + public Attribute aliasAtt = null; + + public void setRelation(Relation rel){ + this.rel = rel; + this.target = rel.getTarget(); + this.alias = rel.getSource(); + this.description = rel.getOwnValue() + " <- ALIAS [alias=" + aliasAtt.getOwnValue() + "]"; + } + } + + static{ + filter1.setEntObjectClass("PERSON"); + filter1.setName("name"); + //filter1.setNormalize(true); + + filter2.setEntObjectClass("TEXT"); + filter2.setName("title"); + //filter2.setNormalize(true); + + filter3.setEntObjectClass("PERSON"); + filter3.setName("name_translit"); + + //filter3.setNormalize(true); + + filter4.setEntObjectClass("TEXT"); + filter4.setName("title_translit"); + + //filter4.setNormalize(true); + + filter5.setEntObjectClass("TEXT"); + filter5.setName("full_title"); + + //filter4.setNormalize(true); + + filter6.setEntObjectClass("TEXT"); + filter6.setName("full_title_translit"); + + + //filers for alias + filter7.setEntObjectClass("ALIAS"); + filter7.setName("alias"); + + authorsFilters.add(filter1); + authorsFilters.add(filter3); + authorsFilters.add(filter7); + + titlesFilters.add(filter2); + titlesFilters.add(filter4); + titlesFilters.add(filter5); + titlesFilters.add(filter6); + titlesFilters.add(filter7); + + /* + filter1.setOwnValue(search); + filter2.setOwnValue(search); + filter3.setOwnValue(search); + filter4.setOwnValue(search); + filter5.setOwnValue(search); + filter6.setOwnValue(search); + filter7.setOwnValue(search); + */ + + filters.add(filter1); + filters.add(filter2); + filters.add(filter3); + filters.add(filter4); + filters.add(filter5); + filters.add(filter6); + filters.add(filter7); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/search/beans/Titles4PersonQuery.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,473 @@ +package de.mpiwg.itgroup.ismi.search.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Relation; +import org.mpi.openmind.repository.utils.NormalizerUtils; +import org.mpi.openmind.search.utils.ResultEntry; +import org.mpi.openmind.search.utils.SAttributeMultipleName; +import org.mpi.openmind.search.utils.SAttributeUniqueName; +import org.mpi.openmind.search.utils.SEntity; +import org.mpi.openmind.search.utils.SRelLongKey; +import org.mpi.openmind.search.utils.SRelation; +import org.mpi.openmind.search.utils.SRelationMultipleName; +import org.mpi.openmind.search.utils.SRelationUniqueName; + +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; + +public class Titles4PersonQuery extends AbstractQuery implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = -5342126098161866749L; + private String personName; + private String roleName = "Author"; + private static List<SelectItem> roleList; + private List<SRelLongKey> personTitleKeyList; + + private boolean displayCodex = false; + private boolean displayAlias = false; + + public Titles4PersonQuery(ApplicationBean appBean){ + super(appBean); + this.exportUrlRoot = ApplicationBean.urlISMIExportServiceAuthors; + } + + //"Author", "Annotator", "Copyist", "Corrector", "Dedicatee", "Illuminator", "Illustrator", "Owner", "Patron", "inspector" + static{ + roleList = new ArrayList<SelectItem>(); + roleList.add(new SelectItem("Author")); + roleList.add(new SelectItem("Annotator")); + roleList.add(new SelectItem("Copyist")); + roleList.add(new SelectItem("Corrector")); + roleList.add(new SelectItem("Dedicatee")); + roleList.add(new SelectItem("Illuminator")); + roleList.add(new SelectItem("Illustrator")); + roleList.add(new SelectItem("Owner")); + roleList.add(new SelectItem("Patron")); + roleList.add(new SelectItem("Inspector")); + } + + @Override + public void reset(){ + super.reset(); + this.personName = null; + this.roleName = "Author"; + this.rs = null; + this.personTitleKeyList = null; + this.displayAlias = false; + this.displayCodex = false; + } + + @Override + protected void search(){ + + this.displayAlias = false; + this.displayCodex = false; + + List<ResultEntry> rs0 = this.execute01(personName, roleName); + List<ResultEntry> rs1 = null; + if(StringUtils.isNotEmpty(personName)){ + rs1 = this.execute02(personName, roleName); + } + rs = loadResultSet(rs0, rs1); + + List<Long> idLongList = new ArrayList<Long>(); + for(Object e : rs){ + Titles4PersonEntry entry = (Titles4PersonEntry)e; + if(!idLongList.contains(entry.getPersonId())) + idLongList.add(entry.getPersonId()); + } + this.idList = ApplicationBean.generateIdList(idLongList); + + this.exportDirkUrl = ApplicationBean.generateExportURL(exportUrlRoot, idList, "xml"); + } + + + + private List<Titles4PersonEntry> loadResultSet(List<ResultEntry> rs0, List<ResultEntry> rs1){ + List<Titles4PersonEntry> currentRS = new ArrayList<Titles4PersonEntry>(); + + List<Long> personIdList = new ArrayList<Long>(); + + + for(ResultEntry re : rs0){ + Entity person = getOm().getEntityById(re.getEntMap().get(1)); + personIdList.add(person.getId()); + currentRS.addAll(getEntryFromPerson(person, null, null, this.roleName)); + } + + if(rs1 != null){ + for(ResultEntry re : rs1){ + Entity person = getOm().getEntityById(re.getEntMap().get(1)); + if(!personIdList.contains(person.getId())){ + String alias = getOm().getEntityById(re.getEntMap().get(2)).getOwnValue(); + String alias2Person = re.getRel(2, 1); + currentRS.addAll(getEntryFromPerson(person, alias, alias2Person, this.roleName)); + this.displayAlias = true; + } + } + } + + return currentRS; + } + + + /** + * Possible ways to find a title from a given person + * 1- TEXT is_exemplar_of WITNESS is_part_of CODEX owned_by PERSON + * 2- + * TEXT was_created_by PERSON + * TEXT had_patron PERSON + * TEXT was_dedicated_to PERSON + */ + private List<Titles4PersonEntry> getEntryFromPerson(Entity person, String alias, String alias2Person, String role){ + //rs.add(new Titles4PersonEntry(person, title, title2Person, codex, codex2Person, alias, alias2Person, role, subject, )); + List<Titles4PersonEntry> rs = new ArrayList<Titles4PersonQuery.Titles4PersonEntry>(); + + List<Entity> entList = getOm().getSourcesForTargetRelation(person.getId(), "was_created_by", "TEXT", -1); + for(Entity title : entList){ + String subject = getSubject(title); + rs.add(new Titles4PersonEntry(person, title, alias, alias2Person, role, subject, "TEXT was_created_by PERSON")); + } + + entList = getOm().getSourcesForTargetRelation(person.getId(), "had_patron", "TEXT", -1); + for(Entity title : entList){ + String subject = getSubject(title); + rs.add(new Titles4PersonEntry(person, title, alias, alias2Person, role, subject, "TEXT had_patron PERSON")); + } + + + entList = getOm().getSourcesForTargetRelation(person.getId(), "was_dedicated_to", "TEXT", -1); + for(Entity title : entList){ + String subject = getSubject(title); + rs.add(new Titles4PersonEntry(person, title, alias, alias2Person, role, subject, "TEXT was_dedicated_to PERSON")); + } + + entList = getOm().getSourcesForTargetRelation(person.getId(), "owned_by", "CODEX", -1); + for(Entity codex : entList){ + List<Entity> witnessList = getOm().getSourcesForTargetRelation(codex.getId(), "is_part_of", "WITNESS", -1); + for(Entity witness : witnessList){ + List<Entity> textList = getOm().getTargetsForSourceRelation(witness.getId(), "is_exemplar_of", "TEXT", -1); + for(Entity title : textList){ + String subject = getSubject(title); + rs.add(new Titles4PersonEntry(person, title, codex, witness, alias, alias2Person, role, subject, + "TEXT is_exemplar_of WITNESS is_part_of CODEX owned_by PERSON")); + this.displayCodex = true; + System.out.println("this.displayCodex = true;"); + } + } + } + + return rs; + } + + private String getSubject(Entity title){ + List<Entity> subjectList = getOm().getTargetsForSourceRelation(title.getId(), "has_subject", "SUBJECT", 1); + return (subjectList.size() == 0) ? null : subjectList.get(0).getOwnValue(); + } + + private List<ResultEntry> execute01(String personName, String roleName){ + + List<SEntity> entFilters = new ArrayList<SEntity>(); + List<SRelation> relFilters = new ArrayList<SRelation>(); + + //The user can select between: + //"Author", "Annotator", "Copyist", "Corrector", "Dedicatee", "Illuminator", "Illustrator", "Owner", "Patron", "inspector" + SEntity role = new SEntity(0, "ROLE"); + role.addAtt(new SAttributeUniqueName("name", roleName)); + entFilters.add(role); + + //alias, "is_prime_alias_name_of", "PERSON" + //alias, "is_alias_name_of", "PERSON" + SEntity person = new SEntity(1, "PERSON"); + if(StringUtils.isNotEmpty(personName)){ + person.addAtt(new SAttributeMultipleName(personName, "name_translit", "name")); + } + entFilters.add(person); + + SRelationUniqueName has_role = new SRelationUniqueName(person, role, "has_role"); + relFilters.add(has_role); + + return this.appBean.getSS().search(entFilters, relFilters); + } + + private List<ResultEntry> execute02(String personName, String roleName){ + + List<SEntity> entFilters = new ArrayList<SEntity>(); + List<SRelation> relFilters = new ArrayList<SRelation>(); + + //The user can select between: + //"Author", "Annotator", "Copyist", "Corrector", "Dedicatee", "Illuminator", "Illustrator", "Owner", "Patron", "inspector" + SEntity role = new SEntity(0, "ROLE"); + role.addAtt(new SAttributeUniqueName("name", roleName)); + entFilters.add(role); + + //alias, "is_prime_alias_name_of", "PERSON" + //alias, "is_alias_name_of", "PERSON" + SEntity person = new SEntity(1, "PERSON"); + entFilters.add(person); + + SEntity alias = new SEntity(2, "ALIAS"); + alias.addAtt(new SAttributeUniqueName("alias", personName)); + entFilters.add(alias); + + SRelationMultipleName is_alias = new SRelationMultipleName(alias, person, "is_alias_name_of", "is_prime_alias_name_of"); + SRelationUniqueName has_role = new SRelationUniqueName(person, role, "has_role"); + relFilters.add(has_role); + relFilters.add(is_alias); + + return this.appBean.getSS().search(entFilters, relFilters); + } + + public String getPersonName() { + return personName; + } + + public void setPersonName(String personName) { + this.personName = personName; + } + + public String getRoleName() { + return roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + public List<SRelLongKey> getPersonTitleKeyList() { + return personTitleKeyList; + } + + public void setPersonTitleKeyList(List<SRelLongKey> personTitleKeyList) { + this.personTitleKeyList = personTitleKeyList; + } + + public List<SelectItem> getRoleList() { + return roleList; + } + + public boolean isDisplayCodex() { + return displayCodex; + } + + public boolean isDisplayAlias() { + return displayAlias; + } + + + + public class Titles4PersonEntry implements Comparable<Titles4PersonEntry>, Serializable{ + private static final long serialVersionUID = 7798695003500406910L; + + private Long personId; + private String personOv; + private String personNOv; + + private Long titleId; + private String titleOv; + private String titleNOv; + + private Long codexId; + private String codexOv; + private String codex2Person; + + private Long witnessId; + private String witnessOv; + private String witnessNOv; + + private String alias; + private String alias2Person; + + private String role; + //private String title2Person; + private String subject; + + + + private String query; + + public Titles4PersonEntry( + Entity person, + Entity title, + Entity codex, + Entity witness, + String alias, + String alias2Person, + String role, + String subject, + String query + ){ + + set(person, title); + this.alias = alias; + this.alias2Person = alias2Person; + this.role = role; + this.subject = subject; + this.query = query; + if(codex != null){ + this.codexId = codex.getId(); + this.codexOv = codex.getOwnValue(); + } + if(witness != null){ + this.witnessId = witness.getId(); + this.witnessOv = witness.getOwnValue(); + this.witnessNOv = witness.getNormalizedOwnValue(); + } + } + + public Titles4PersonEntry( + Entity person, + Entity title, + String alias, + String alias2Person, + String role, + String subject, + String query + ){ + + set(person, title); + this.alias = alias; + this.alias2Person = alias2Person; + this.role = role; + this.subject = subject; + this.query = query; + } + + private void set(Entity person, Entity title){ + this.personId = person.getId(); + this.personOv = person.getOwnValue(); + this.personNOv = person.getNormalizedOwnValue(); + + this.titleId = title.getId(); + this.titleOv = title.getOwnValue(); + this.titleNOv = title.getNormalizedOwnValue(); + } + + public Long getPersonId() { + return personId; + } + + public String getPersonOv() { + return personOv; + } + + public String getPersonNOv() { + return personNOv; + } + + public String getAlias() { + return alias; + } + + public String getAlias2Person() { + return alias2Person; + } + + public Long getTitleId() { + return titleId; + } + + public String getTitleOv() { + return titleOv; + } + + public String getTitleNOv() { + return titleNOv; + } + + public String getRole() { + return role; + } + + public String getSubject() { + return subject; + } + + public Long getCodexId() { + return codexId; + } + + public String getCodexOv() { + return codexOv; + } + + + public String getCodex2Person() { + return codex2Person; + } + + public String getQuery() { + return query; + } + + public Long getWitnessId() { + return witnessId; + } + + public String getWitnessOv() { + return witnessOv; + } + + public String getWitnessNOv() { + return witnessNOv; + } + + @Override + public int compareTo(Titles4PersonEntry o) { + if(!this.personId.equals(o.personId)){ + + int comparisonPerson = NormalizerUtils.normalizedToCompare(personNOv).compareTo( + NormalizerUtils.normalizedToCompare(o.personNOv)); + if(comparisonPerson != 0){ + return comparisonPerson; + }else{ + if(StringUtils.isNotEmpty(role) && StringUtils.isNotEmpty(o.role)){ + int comparisonRole = this.role.compareTo(o.role); + if(comparisonRole != 0){ + return comparisonRole; + } + }else{ + if(StringUtils.isNotEmpty(role)){ + return -1; + }else if(StringUtils.isNotEmpty(o.role)){ + return 1; + } + } + } + }else{ + if(!this.titleId.equals(o.titleId)){ + //comparing subject + if(StringUtils.isNotEmpty(subject) && StringUtils.isNotEmpty(o.subject)){ + int comparisonSubject = this.subject.compareTo(o.subject); + if(comparisonSubject != 0){ + return comparisonSubject; + } + }else{ + if(StringUtils.isNotEmpty(subject)){ + return -1; + }else if(StringUtils.isNotEmpty(o.subject)){ + return 1; + } + } + //comparing title + int comparisonTitle = NormalizerUtils.normalizedToCompare(titleNOv).compareTo( + NormalizerUtils.normalizedToCompare(o.titleNOv)); + return comparisonTitle; + } + } + return 0; + } + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/search/beans/Witness4TitleQuery.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,286 @@ +package de.mpiwg.itgroup.ismi.search.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.utils.NormalizerUtils; +import org.mpi.openmind.search.utils.ResultEntry; +import org.mpi.openmind.search.utils.SAttributeMultipleName; +import org.mpi.openmind.search.utils.SAttributeUniqueName; +import org.mpi.openmind.search.utils.SEntity; +import org.mpi.openmind.search.utils.SRelLongKey; +import org.mpi.openmind.search.utils.SRelation; +import org.mpi.openmind.search.utils.SRelationMultipleName; +import org.mpi.openmind.search.utils.SRelationUniqueName; + +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; + +/** + * 2) List of all witnesses for a title + * (the list should distinguish which witnesses go with a particular title version) + * @author jurzua + * + */ +public class Witness4TitleQuery extends AbstractQuery implements Serializable{ + + private static final long serialVersionUID = -1460003809678104919L; + + private String titleName; + private List<SRelLongKey> titleWitnessKeyList; + + public Witness4TitleQuery(ApplicationBean appBean){ + super(appBean); + this.exportUrlRoot = ApplicationBean.urlISMIExportServiceTitles; + } + + @Override + public void reset(){ + super.reset(); + this.titleName = null; + this.rs = null; + this.titleWitnessKeyList = null; + } + + @Override + protected void search(){ + + List<ResultEntry> rs0 = this.execute01(titleName); + List<ResultEntry> rs1 = null; + if(StringUtils.isNotEmpty(titleName)){ + rs1 = this.execute02(titleName); + } + rs = loadResultSet(rs0, rs1); + + List<Long> idLongList = new ArrayList<Long>(); + for(Object e : rs){ + ResultEntry02 entry = (ResultEntry02)e; + if(!idLongList.contains(entry.titleId)) + idLongList.add(entry.titleId); + } + this.idList = ApplicationBean.generateIdList(idLongList); + + this.exportDirkUrl = ApplicationBean.generateExportURL(exportUrlRoot, idList, "xml"); + } + + private List<ResultEntry02> loadResultSet(List<ResultEntry> rs0, List<ResultEntry> rs1){ + List<ResultEntry02> currentRs = new ArrayList<ResultEntry02>(); + titleWitnessKeyList = new ArrayList<SRelLongKey>(); + + int count = 0; + + for(ResultEntry re : rs0){ + Entity title = getOm().getEntityById(re.getEntMap().get(0)); + Entity witness = getOm().getEntityById(re.getEntMap().get(1)); + + List<Entity> subjectList = getOm().getTargetsForSourceRelation(title.getId(), "has_subject", "SUBJECT", 1); + String subject = (subjectList.size() == 0) ? null : subjectList.get(0).getOwnValue(); + + currentRs.add(new ResultEntry02(title, witness, subject)); + putTitleWitnessKeyList(title.getId(), witness.getId()); + count++; + if(count >= MAX_RS){ + break; + } + } + + if(rs1 != null && count < MAX_RS){ + for(ResultEntry re : rs1){ + Entity title = getOm().getEntityById(re.getEntMap().get(0)); + Entity witness = getOm().getEntityById(re.getEntMap().get(1)); + if(!containsTitleWitnessKeyList(title.getId(), witness.getId())){ + + Entity alias = getOm().getEntityById(re.getEntMap().get(1)); + String alias2Person = re.getRel(1, 0); + List<Entity> subjectList = getOm().getTargetsForSourceRelation(title.getId(), "has_subject", "SUBJECT", 1); + String subject = (subjectList.size() == 0) ? null : subjectList.get(0).getOwnValue(); + + currentRs.add(new ResultEntry02(title, witness, subject, alias.getOwnValue(), alias2Person)); + putTitleWitnessKeyList(title.getId(), witness.getId()); + count++; + if(count >= MAX_RS){ + break; + } + } + } + } + + Collections.sort(currentRs); + + return currentRs; + } + + private void putTitleWitnessKeyList(Long titleId, Long witness){ + titleWitnessKeyList.add(new SRelLongKey(titleId, witness)); + } + + private boolean containsTitleWitnessKeyList(Long titleId, Long witnessId){ + return titleWitnessKeyList.contains(new SRelLongKey(titleId, witnessId)); + } + + private List<ResultEntry> execute01(String titleName){ + + List<SEntity> entFilters = new ArrayList<SEntity>(); + List<SRelation> relFilters = new ArrayList<SRelation>(); + + + SEntity text = new SEntity(0, "TEXT"); + if(StringUtils.isNotEmpty(titleName)){ + text.addAtt(new SAttributeMultipleName(titleName, "full_title_translit", "full_title")); + } + entFilters.add(text); + + SEntity witness = new SEntity(1, "WITNESS"); + entFilters.add(witness); + + SRelationUniqueName is_exemplar_of = new SRelationUniqueName(witness, text, "is_exemplar_of"); + relFilters.add(is_exemplar_of); + + return this.appBean.getSS().search(entFilters, relFilters); + } + + private List<ResultEntry> execute02(String titleName){ + + List<SEntity> entFilters = new ArrayList<SEntity>(); + List<SRelation> relFilters = new ArrayList<SRelation>(); + + + SEntity text = new SEntity(0, "TEXT"); + entFilters.add(text); + + SEntity alias = new SEntity(1, "ALIAS"); + alias.addAtt(new SAttributeUniqueName("alias", titleName)); + entFilters.add(alias); + + SEntity witness = new SEntity(2, "WITNESS"); + entFilters.add(witness); + + SRelationMultipleName is_alias = new SRelationMultipleName(alias, text, + "is_prime_alias_title_of", "is_alias_title_of", + "is_alias_explicit_of", "is_alias_incipit_of"); + SRelationUniqueName is_exemplar_of = new SRelationUniqueName(witness, text, "is_exemplar_of"); + relFilters.add(is_exemplar_of); + relFilters.add(is_alias); + + return this.appBean.getSS().search(entFilters, relFilters); + } + + public class ResultEntry02 implements Comparable<ResultEntry02>, Serializable{ + private static final long serialVersionUID = -2672042198162179468L; + + public Long titleId; + public String titleOv; + public String titleNOv; + public String alias; + public String alias2Title; + public Long witnessId; + public String witnessOv; + public String witnessNOv; + public String subject; + + public ResultEntry02(Entity title, Entity witness, String subject){ + this.set(title, witness, subject); + + } + + public ResultEntry02(Entity title, Entity witness, String subject, String alias, String alias2Title){ + this.set(title, witness, subject); + this.alias = alias; + this.alias2Title = alias2Title; + } + + private void set(Entity title, Entity witness, String subject){ + this.subject = subject; + + this.titleId = title.getId(); + this.titleOv = title.getOwnValue(); + this.titleNOv = title.getNormalizedOwnValue(); + + this.witnessId = witness.getId(); + this.witnessOv = witness.getOwnValue(); + this.witnessNOv = witness.getNormalizedOwnValue(); + } + + @Override + public int compareTo(ResultEntry02 o) { + if(!this.titleId.equals(o.titleId)){ + + //comparing subject + if(StringUtils.isNotEmpty(subject) && StringUtils.isNotEmpty(o.subject)){ + int comparisonSubject = this.subject.compareTo(o.subject); + if(comparisonSubject != 0){ + return comparisonSubject; + } + }else{ + if(StringUtils.isNotEmpty(subject)){ + return -1; + }else if(StringUtils.isNotEmpty(o.subject)){ + return 1; + } + } + + //comparing title + int comparisonTitle = NormalizerUtils.normalizedToCompare(titleNOv).compareTo( + NormalizerUtils.normalizedToCompare(o.titleNOv)); + if(comparisonTitle != 0){ + return comparisonTitle; + } + }else{ + if(!this.witnessId.equals(o.witnessId)){ + //comparing witness + int comparisonWitness = NormalizerUtils.normalizedToCompare(titleNOv).compareTo( + NormalizerUtils.normalizedToCompare(o.titleNOv)); + return comparisonWitness; + } + } + return 0; + } + + public Long getTitleId() { + return titleId; + } + + public String getTitleOv() { + return titleOv; + } + + public String getTitleNOv() { + return titleNOv; + } + + public String getAlias() { + return alias; + } + + public String getAlias2Title() { + return alias2Title; + } + + public Long getWitnessId() { + return witnessId; + } + + public String getWitnessOv() { + return witnessOv; + } + + public String getWitnessNOv() { + return witnessNOv; + } + + public String getSubject() { + return subject; + } + } + + public String getTitleName() { + return titleName; + } + + public void setTitleName(String titleName) { + this.titleName = titleName; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/AbstractServlet.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,45 @@ +package de.mpiwg.itgroup.ismi.servlets; + +import javax.faces.FactoryFinder; +import javax.faces.context.FacesContext; +import javax.faces.context.FacesContextFactory; +import javax.faces.lifecycle.Lifecycle; +import javax.faces.lifecycle.LifecycleFactory; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.mpi.openmind.cache.WrapperService; + +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; + + +public class AbstractServlet extends HttpServlet { + private static final long serialVersionUID = 1L; + + public static String APP_BEAN = "ApplicationBean1"; + + public ApplicationBean getAppBean(HttpServletRequest request, HttpServletResponse response) { + ApplicationBean appBean = (ApplicationBean)getApplicationBean(request, response, APP_BEAN); + + if(appBean == null){ + appBean = new ApplicationBean(); + getFacesContext(request, response).getCurrentInstance().getExternalContext().getApplicationMap().put(APP_BEAN, appBean); + } + return appBean; + } + + public Object getApplicationBean(HttpServletRequest request, HttpServletResponse response, String bean) { + return getFacesContext(request, response).getExternalContext().getApplicationMap().get(bean); + } + + + public FacesContext getFacesContext(HttpServletRequest request, HttpServletResponse response) { + ServletContext servletContext = ((HttpServletRequest)request).getSession().getServletContext(); + FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY); + LifecycleFactory lifecycleFactory = (LifecycleFactory)FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY); + Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE); + return contextFactory.getFacesContext(servletContext, request, response, lifecycle); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/AbstractServletMethod.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,61 @@ +package de.mpiwg.itgroup.ismi.servlets; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +public class AbstractServletMethod { + + public static Long getLong(HttpServletRequest request, String name){ + Long value = null; + try{ + String s = request.getParameter(name); + value = new Long(s); + }catch (Exception e) { + } + return value; + } + + public static String getString(HttpServletRequest request, String name){ + String value = null; + try{ + value = request.getParameter(name); + }catch (Exception e) { + } + return value; + } + + public static Boolean getBoolean(HttpServletRequest request, String name){ + Boolean value = false; + try{ + String s = request.getParameter(name); + value = new Boolean(s); + }catch (Exception e) { + } + return value; + } + + public static Integer getInteger(HttpServletRequest request, String name){ + Integer value = null; + try{ + String s = request.getParameter(name); + value = new Integer(s); + }catch (Exception e) { + } + return value; + } + + public static List<Long> getLongList(HttpServletRequest request, String name){ + List<Long> list = new ArrayList<Long>(); + String s = request.getParameter(name); + String[] array = s.split("[|]"); + for(String sID : array){ + try{ + Long id = new Long(sID); + list.add(id); + }catch (Exception e) {} + } + return list; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/JSONInterface.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,159 @@ +package de.mpiwg.itgroup.ismi.servlets; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.util.Map; +import java.util.Map.Entry; + +import javax.servlet.Servlet; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.mpi.openmind.cache.WrapperService; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONDataProxy; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONExistRel; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetAtts; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetDef; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetDefs; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetEnt; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetEnts; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetEntsSize; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetPublicCodices; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetTitleDetails; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetWitnessDetails; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetWitnesses4Codex; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONSearch; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetRels; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetSrcRels; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetSrcs4TarRel; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetTarRels; +import de.mpiwg.itgroup.ismi.servlets.jsonmethods.JSONGetTars4SrcRel; + +public class JSONInterface extends AbstractServlet implements Servlet{ + private static final long serialVersionUID = 1L; + + private static Logger logger = Logger.getLogger(JSONInterface.class); + + private HttpServletRequest request; + private HttpServletResponse response; + + private WrapperService wrapper; + + private void initialize(HttpServletRequest request, HttpServletResponse response){ + + this.request = request; + this.response = response; + this.response.setContentType("application/json; charset=UTF-8"); + //this.response.setContentType("text/html; charset=UTF-8"); + try { + request.setCharacterEncoding("UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + this.doIt(request, response); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + this.doIt(request, response); + } + + public void doIt(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + long start = System.currentTimeMillis(); + this.initialize(request, response); + + String method = request.getParameter(JSONUtils.METHOD); + + logger.debug("Starting " + paramsToString(request.getParameterMap())); + + if(StringUtils.isNotEmpty(method)){ + try{ + if(method.equals(JSONUtils.M_GET_ENT)){ + JSONGetEnt.execute(getWrapper(), request, response); + }else if(method.equals("data_proxy")){ + JSONDataProxy.execute(request, response); + }else if(method.equals(JSONUtils.M_GET_ENTS)){ + JSONGetEnts.execute(getWrapper(), request, response); + }else if(method.equals(JSONUtils.M_GET_ENTS_SIZE)){ + JSONGetEntsSize.execute(getWrapper(), request, response); + }else if(method.equals(JSONUtils.M_GET_DEF)){ + JSONGetDef.execute(getWrapper(), request, response); + }else if(method.equals(JSONUtils.M_GET_DEFS)){ + JSONGetDefs.execute(getWrapper(), request, response); + }else if(method.equals(JSONUtils.M_GET_SRC_RELS)){ + JSONGetSrcRels.execute(getWrapper(), request, response); + }else if(method.equals(JSONUtils.M_GET_TAR_RELS)){ + JSONGetTarRels.execute(getWrapper(), request, response); + }else if(method.equals(JSONUtils.M_GET_ATTS)){ + JSONGetAtts.execute(getWrapper(), request, response); + }else if(method.equals(JSONUtils.M_GET_TARS_4_SRC_REL)){ + JSONGetTars4SrcRel.execute(getWrapper(), request, response); + }else if(method.equals(JSONUtils.M_GET_SRCS_4_TAR_REL)){ + JSONGetSrcs4TarRel.execute(getWrapper(), request, response); + }else if(method.equals(JSONUtils.M_EXIST_RELATION)){ + JSONExistRel.execute(getWrapper(), request, response); + }else if(method.equals(JSONUtils.M_GET_RELS)){ + JSONGetRels.execute(getWrapper(), request, response); + }else if(method.equals(JSONUtils.M_SEARCH)){ + JSONSearch.execute(getWrapper(), request, response); + }else if(method.equals(JSONUtils.M_GET_PUBLIC_CODICES)){ + JSONGetPublicCodices.execute(getWrapper(), request, response); + }else if(method.equals(JSONUtils.M_WITNESSES_4_CODEX)){ + JSONGetWitnesses4Codex.execute(getWrapper(), request, response); + }else if(method.equals("get_title_details")){ + JSONGetTitleDetails.execute(getWrapper(), request, response); + }else if(method.equals("get_witness_details")){ + JSONGetWitnessDetails.execute(getWrapper(), request, response); + }else{ + PrintWriter out = response.getWriter(); + out.print("{\"responseInfo\": \"Method no valid "+ method +".\"}"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Method no valid "+ method +"."); + } + }catch (Exception e) { + logger.error(e.getMessage(), e); + PrintWriter out = response.getWriter(); + out.print(e.getMessage()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + } + }else{ + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter method not found!."); + } + long end = System.currentTimeMillis(); + logger.debug("Finish [time=" + (end-start) + "] " + paramsToString(request.getParameterMap())); + } + + private String paramsToString(Map<String, String[]> paramMap){ + StringBuilder sb = new StringBuilder(); + + for(Entry<String, String[]> entry : paramMap.entrySet()){ + sb.append(entry.getKey() + "=["); + int count = 0; + for(String value : entry.getValue()){ + if(count > 0){ + sb.append(", "); + } + sb.append(value); + count++; + } + sb.append("] "); + } + + return sb.toString(); + } + + + public WrapperService getWrapper(){ + if(this.wrapper == null){ + this.wrapper = getAppBean(request, response).getWrapper(); + } + return this.wrapper; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/AbstractServletJSONMethod.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,60 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.util.Map; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import de.mpiwg.itgroup.ismi.servlets.AbstractServletMethod; + +public class AbstractServletJSONMethod extends AbstractServletMethod{ + + protected static String RESPONSE = "response"; + protected static String RESPONSE_INFO = "response_info"; + protected static String OK = "ok"; + protected static String EXCEPTION = "exception"; + protected static String METHOD = "method"; + protected static String RUNTIME = "runtime"; + protected static String PARAMETERS = "parameters"; + + protected static JSONObject finallyExecution(JSONObject json, JSONObject parameters, long startExecution){ + if(json == null){ + json = new JSONObject(); + } + + if(!json.has(RESPONSE)){ + try { + json.put(RESPONSE, OK); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + try { + json.put(PARAMETERS, parameters); + json.put(RUNTIME, (System.currentTimeMillis() - startExecution)); + } catch (JSONException e) { + e.printStackTrace(); + } + return json; + } + + public static JSONObject parametersToString(Map<String, ?> map){ + JSONObject json = new JSONObject(); + try { + for(String key : map.keySet()){ + String[] values = (String[])map.get(key); + JSONArray array = new JSONArray(); + for(int i=0; i<values.length; i++){ + array.put(values[i]); + } + json.put(key, array); + } + } catch (JSONException e) { + e.printStackTrace(); + } + + return json; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONDataProxy.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,33 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import de.mpiwg.itgroup.ismi.utils.HTTPUtils; +import de.mpiwg.itgroup.ismi.utils.HTTPUtils.HttpStringResponse; + +public class JSONDataProxy { + + + //http://images.rasi.mcgill.ca/data/Majlis_shura_21.json + + public static void execute(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + String file = request.getParameter("file"); + + HttpStringResponse resp = HTTPUtils.getHttpSSLStringResponse("https://images.rasi.mcgill.ca/data/" + file + ".json"); + + if(resp.code == 200){ + + PrintWriter out = response.getWriter(); + out.print(resp.content); + }else{ + response.sendError(resp.code, "Problems loading http://images.rasi.mcgill.ca/data/" + file + ".json"); + } + + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONExistRel.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,53 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONExistRel extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + + Long srcId = getLong(request, JSONUtils.P_SRC_ID); + Long tarId = getLong(request, JSONUtils.P_TAR_ID); + String relName = getString(request, JSONUtils.P_REL_NAME); + + if(srcId == null || tarId == null || StringUtils.isEmpty(relName)){ + json.put(RESPONSE, EXCEPTION); + json.put(RESPONSE_INFO, "The parameters 'src_id', 'tar_id', and 'rel_name' are mandatory."); + + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "The parameters 'src_id', 'tar_id', and 'rel_name' are mandatory."); + + }else{ + + Boolean existRel = ws.existRelation(srcId, tarId, relName); + json.put(JSONUtils.R_EXIST_REL, existRel); + } + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetAtts.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,56 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Attribute; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONGetAtts extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + Long entId = getLong(request, JSONUtils.P_ID); + Boolean includeRomanization = getBoolean(request, JSONUtils.P_INCL_ROMANIZATION); + + if(entId == null){ + json.put(RESPONSE, EXCEPTION); + json.put(RESPONSE_INFO, "Parameter 'id' is mandatory and should be a number."); + + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter 'id' is mandatory and should be a number."); + + }else{ + List<Attribute> attList = ws.getAttributeByEntId(entId); + JSONArray array = new JSONArray(); + for(Attribute att : attList){ + array.put(JSONUtils.attributeToJSON(att, includeRomanization)); + } + json.put(JSONUtils.R_ATTS, array); + } + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetDef.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,58 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONGetDef extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + String oc = request.getParameter(JSONUtils.P_OC); + Boolean includeRomanization = getBoolean(request, JSONUtils.P_INCL_ROMANIZATION); + + if(StringUtils.isEmpty(oc)){ + json.put(RESPONSE, EXCEPTION); + json.put(RESPONSE_INFO, "Object class parameter not valid."); + + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, + "Object class parameter not valid."); + + }else{ + Entity def = ws.getDefinition(oc); + List<Attribute> attList = ws.getAttributeByEntId(def.getId()); + List<Relation> srcList = ws.getDefSourceRelations(def.getOwnValue()); + List<Relation> tarList = ws.getDefTargetRelations(def.getOwnValue()); + json.put(JSONUtils.R_DEF, JSONUtils.entityToJSON(def, attList, srcList, tarList, includeRomanization)); + } + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetDefs.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,49 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONGetDefs extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + JSONArray defArray = new JSONArray(); + List<Entity> list = ws.getLWDefinitions(); + for(Entity def : list){ + List<Attribute> attList = ws.getAttributeByEntId(def.getId()); + List<Relation> srcList = ws.getDefSourceRelations(def.getOwnValue()); + List<Relation> tarList = ws.getDefTargetRelations(def.getOwnValue()); + defArray.put(JSONUtils.entityToJSON(def, attList, srcList, tarList, false)); + } + json.put(JSONUtils.R_DEFS, defArray); + //TODO sort!!! + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetEnt.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,90 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONGetEnt extends AbstractServletJSONMethod{ + + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + Long entId = getLong(request, JSONUtils.P_ID); + String mpiwgId = getString(request, JSONUtils.P_MPIWGID); + Boolean includeContent = getBoolean(request, JSONUtils.P_INCLUDE); + Boolean includeRomanization = getBoolean(request, JSONUtils.P_INCL_ROMANIZATION); + + Integer depth = getInteger(request, JSONUtils.P_DEPTH); + depth = (depth == null) ? 0 : depth; + depth = (depth > 2) ? 2 : depth; + + if(entId == null && StringUtils.isEmpty(mpiwgId)){ + json.put(RESPONSE, EXCEPTION); + json.put(RESPONSE_INFO, "Neither parameter 'id' nor 'mpiwg_id' have been found in the parameter list."); + + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter 'id' is mandatory and should be a number."); + + }else if(StringUtils.isNotEmpty(mpiwgId)){ + + List<Attribute> attList = ws.getAttributesByExactValue("mpiwg_id", mpiwgId); + if(!attList.isEmpty()){ + entId = attList.get(0).getSourceId(); + } + } + + if(entId != null){ + loadEntity(ws, json, entId, depth, includeContent, includeRomanization); + }else{ + json.put(RESPONSE_INFO, "Entity no found."); + } + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + e.printStackTrace(); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + } + + private static void loadEntity(WrapperService ws, JSONObject json, Long entId, Integer depth, Boolean includeContent, Boolean includeRomanization) throws JSONException{ + Entity ent = null; + if(depth > 0 || (includeContent != null && includeContent)){ + ent = ws.getEntityByIdWithContent(entId); + }else{ + ent = ws.getLightweightEntityById(entId); + } + if(ent != null){ + JSONObject jsonEntity = null; + if(depth > 0){ + jsonEntity = JSONUtils.entityToJSON(ent, depth, ws, includeRomanization); + }else{ + jsonEntity = JSONUtils.entityToJSON(ent, includeRomanization); + } + json.put(JSONUtils.ENT, jsonEntity); + }else{ + json.put(RESPONSE_INFO, "Entity no found."); + } + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetEnts.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,77 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONGetEnts extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + String oc = request.getParameter(JSONUtils.P_OC); + String ids = request.getParameter(JSONUtils.P_IDS); + Boolean includeRomanization = getBoolean(request, JSONUtils.P_INCL_ROMANIZATION); + + if(StringUtils.isEmpty(oc) && StringUtils.isEmpty(ids)){ + json.put(RESPONSE, EXCEPTION); + json.put(RESPONSE_INFO, "Object class parameter for the entities not valid."); + + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, + "Object class parameter for the entities not valid."); + + }else if(StringUtils.isNotEmpty(oc)){ + List<Entity> list = ws.getEntitiesByDef(oc); + JSONArray array = new JSONArray(); + for(Entity ent : list){ + array.put(JSONUtils.entityToJSON(ent, includeRomanization)); + } + json.put(JSONUtils.R_ENTS, array); + json.put(JSONUtils.R_ENTS_SIZE, list.size()); + }else{ + String[] idArray = ids.split(","); + JSONArray array = new JSONArray(); + for(String sid : idArray){ + try { + Long id = Long.parseLong(sid); + Entity ent = ws.getEntityByIdWithContent(id); + if(ent != null){ + array.put(JSONUtils.entityToJSON(ent, includeRomanization)); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + json.put(JSONUtils.R_ENTS, array); + json.put(JSONUtils.R_ENTS_SIZE, array.length()); + + } + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetEntsSize.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,49 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONGetEntsSize extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + String oc = request.getParameter(JSONUtils.P_OC); + + if(StringUtils.isEmpty(oc)){ + json.put(RESPONSE, EXCEPTION); + json.put(RESPONSE_INFO, "ObjectClass no valid."); + + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Object Class no valid."); + + }else{ + int count = ws.getEntitiesCount(oc); + json.put(JSONUtils.R_ENTS_SIZE, count); + } + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetPublicCodices.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,54 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONGetPublicCodices extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + + Boolean includeRomanization = getBoolean(request, JSONUtils.P_INCL_ROMANIZATION); + + JSONArray array = new JSONArray(); + + List<Attribute> attList = ws.getAttributesByDefByAttName("CODEX", "public", "true", -1); + for(Attribute att : attList){ + Entity ent = ws.getEntityByIdWithContent(att.getSourceId()); + if(ent != null){ + array.put(JSONUtils.entityToJSON(ent, includeRomanization)); + } + } + json.put(JSONUtils.R_ENTS, array); + json.put(JSONUtils.R_ENTS_SIZE, array.length()); + + + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetRels.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,82 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.json.JSONArray; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONGetRels extends AbstractServletJSONMethod{ + + private static Logger logger = Logger.getLogger(JSONGetRels.class); + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + + String name = getString(request, JSONUtils.P_REL_NAME); + String srcOC = getString(request, JSONUtils.P_SRC_OC); + String tarOC = getString(request, JSONUtils.P_TAR_OC); + Boolean inclEnts = getBoolean(request, JSONUtils.P_INCL_ENTS); + Boolean includeRomanization = getBoolean(request, JSONUtils.P_INCL_ROMANIZATION); + + + if(StringUtils.isNotEmpty(name)){ + List<Relation> list = ws.getRelation(name, srcOC, tarOC); + JSONArray array = new JSONArray(); + if(inclEnts != null && inclEnts.equals(true)){ + for(Relation rel : list){ + Entity src = ws.getEntityById(rel.getSourceId()); + Entity tar = ws.getEntityById(rel.getTargetId()); + if(src != null && tar != null){ + List<Attribute> srcAtts = ws.getAttributeByEntId(src.getId()); + List<Attribute> tarAtts = ws.getAttributeByEntId(tar.getId()); + if(srcAtts != null && tarAtts != null){ + array.put(JSONUtils.relationToJSON(rel, src, tar, srcAtts, tarAtts, includeRomanization)); + } + }else{ + System.err.println("Lost src or/and tar fot rhis relation: " + rel.toString()); + } + } + }else{ + for(Relation rel : list){ + array.put(JSONUtils.relationToJSON(rel, includeRomanization)); + } + } + + json.put(JSONUtils.R_RELS, array); + json.put(JSONUtils.R_RELS_SIZE, list.size()); + }else{ + PrintWriter out = response.getWriter(); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "The parameters '" + JSONUtils.P_REL_NAME + "' is mandatory."); + } + }catch (Exception e) { + logger.error(e.getMessage(), e); + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal error, please take a look at log file."); + //e.printStackTrace(); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetSrcRels.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,59 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONGetSrcRels extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + Long entId = getLong(request, JSONUtils.P_ID); + String relName = getString(request, JSONUtils.P_REL_NAME); + String tarOc = getString(request, JSONUtils.P_TAR_OC); + Boolean includeRomanization = getBoolean(request, JSONUtils.P_INCL_ROMANIZATION); + + if(entId == null || StringUtils.isEmpty(relName) || StringUtils.isEmpty(tarOc)){ + json.put(RESPONSE, EXCEPTION); + json.put(RESPONSE_INFO, "The parameters 'id', 'rel_name' and 'tar_oc' are mandatory."); + + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "The parameters 'id', 'rel_name' and 'tar_oc' are mandatory."); + + }else{ + List<Relation> relList = ws.getSourceRelations(ws.getEntityByIdReadOnly(entId), relName, tarOc, -1); + JSONArray array = new JSONArray(); + for(Relation rel : relList){ + array.put(JSONUtils.relationToJSON(rel, includeRomanization)); + } + json.put(JSONUtils.R_SRC_RELS, array); + } + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetSrcs4TarRel.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,60 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONGetSrcs4TarRel extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + Long entId = getLong(request, JSONUtils.P_ID); + String relName = getString(request, JSONUtils.P_REL_NAME); + String srcOc = getString(request, JSONUtils.P_SRC_OC); + Boolean includeRomanization = getBoolean(request, JSONUtils.P_INCL_ROMANIZATION); + + + if(entId == null || StringUtils.isEmpty(relName) || StringUtils.isEmpty(srcOc)){ + json.put(RESPONSE, EXCEPTION); + json.put(RESPONSE_INFO, "The parameters 'id', 'rel_name' and 'src_oc' are mandatory."); + + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "The parameters 'id', 'rel_name' and 'src_oc' are mandatory."); + + }else{ + List<Entity> entList = ws.getSourcesForTargetRelation(ws.getEntityByIdReadOnly(entId), relName, srcOc, -1); + JSONArray array = new JSONArray(); + for(Entity ent : entList){ + array.put(JSONUtils.entityToJSON(ent, includeRomanization)); + } + json.put(JSONUtils.R_ENTS, array); + } + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetTarRels.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,60 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONGetTarRels extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + Long entId = getLong(request, JSONUtils.P_ID); + String relName = getString(request, JSONUtils.P_REL_NAME); + String srcOc = getString(request, JSONUtils.P_SRC_OC); + Boolean includeRomanization = getBoolean(request, JSONUtils.P_INCL_ROMANIZATION); + + + if(entId == null || StringUtils.isEmpty(relName) || StringUtils.isEmpty(srcOc)){ + json.put(RESPONSE, EXCEPTION); + json.put(RESPONSE_INFO, "The parameters 'id', 'rel_name' and 'src_oc' are mandatory."); + + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "The parameters 'id', 'rel_name' and 'src_oc' are mandatory."); + + }else{ + List<Relation> relList = ws.getTargetRelations(ws.getEntityByIdReadOnly(entId), relName, srcOc, -1); + JSONArray array = new JSONArray(); + for(Relation rel : relList){ + array.put(JSONUtils.relationToJSON(rel, includeRomanization)); + } + json.put(JSONUtils.R_TAR_RELS, array); + } + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetTars4SrcRel.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,60 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONGetTars4SrcRel extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + Long entId = getLong(request, JSONUtils.P_ID); + String relName = getString(request, JSONUtils.P_REL_NAME); + String tarOc = getString(request, JSONUtils.P_TAR_OC); + Boolean includeRomanization = getBoolean(request, JSONUtils.P_INCL_ROMANIZATION); + + if(entId == null || StringUtils.isEmpty(relName) || StringUtils.isEmpty(tarOc)){ + json.put(RESPONSE, EXCEPTION); + json.put(RESPONSE_INFO, "The parameters 'id', 'rel_name' and 'tar_oc' are mandatory."); + + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "The parameters 'id', 'rel_name' and 'tar_oc' are mandatory."); + + }else{ + List<Entity> entList = ws.getTargetsForSourceRelation(ws.getEntityByIdReadOnly(entId), relName, tarOc, -1); + JSONArray array = new JSONArray(); + for(Entity ent : entList){ + array.put(JSONUtils.entityToJSON(ent, includeRomanization)); + } + json.put(JSONUtils.R_ENTS, array); + } + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetTitleDetails.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,84 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; +import de.mpiwg.itgroup.ismi.utils.templates.TitleTemplate; + +public class JSONGetTitleDetails extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + + JSONObject titleDetails = new JSONObject(); + + String sid = request.getParameter(JSONUtils.P_ID); + + if(StringUtils.isEmpty(sid)){ + throw new Exception("Parameter id can not be null."); + } + Long titleId = Long.parseLong(sid); + Entity title = ws.getEntityByIdWithContent(titleId); + TitleTemplate template = new TitleTemplate(title, ws, true); + + titleDetails.put("ov", template.ov); + titleDetails.put("author", template.author); + titleDetails.put("category", template.category); + titleDetails.put("createIn", template.createIn); + titleDetails.put("creationDate", template.creationDate); + titleDetails.put("dedication", template.dedication); + titleDetails.put("explicit", template.explicit); + titleDetails.put("fullTitle", template.fullTitle); + titleDetails.put("fullTitleTranslit", template.fullTitleTranslit); + titleDetails.put("incipit", template.incipit); + titleDetails.put("language", template.language); + titleDetails.put("notes", template.notes); + titleDetails.put("tableOfContents", template.tableOfContents); + titleDetails.put("personDedicatedTo", template.personDedicatedTo); + titleDetails.put("commentaryOnText", template.commentaryOnText); + titleDetails.put("translationOfText", template.translationOfText); + titleDetails.put("versionOfText", template.versionOfText); + + //aliases + JSONArray aliases = new JSONArray(); + for(String alias : template.aliasList){ + aliases.put(alias); + } + titleDetails.put("aliases", aliases); + + //authorMissattributions + JSONArray missatts = new JSONArray(); + for(String missatt : template.authorMisattributionList){ + missatts.put(missatt); + } + titleDetails.put("authorMisattribution", missatts); + + json.put("data", titleDetails); + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetWitnessDetails.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,105 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; +import de.mpiwg.itgroup.ismi.utils.templates.TitleTemplate; +import de.mpiwg.itgroup.ismi.utils.templates.WitnessTemplate; + +public class JSONGetWitnessDetails extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + + JSONObject witnessDetails = new JSONObject(); + + String sid = request.getParameter(JSONUtils.P_ID); + Boolean useRomanization = getBoolean(request, JSONUtils.P_INCL_ROMANIZATION); + + + if(StringUtils.isEmpty(sid)){ + throw new Exception("Parameter id can not be null."); + } + Long witnessId = Long.parseLong(sid); + + Entity witness = ws.getEntityByIdWithContent(witnessId); + WitnessTemplate template = new WitnessTemplate(witness, ws, useRomanization); + + + witnessDetails.put("ov", template.ov); + witnessDetails.put("title", template.title); + witnessDetails.put("startPage", template.startPage); + witnessDetails.put("endPage", template.endPage); + witnessDetails.put("status", template.status); + witnessDetails.put("tableOfContents", template.tableOfContents); + witnessDetails.put("notesOnTitleAuthor", template.notesOnTitleAuthor); + witnessDetails.put("notesOnCollationAndCorrections", template.notesOnCollationAndCorrections); + witnessDetails.put("notesOnOwnership", template.notesOnOwnership); + witnessDetails.put("notes", template.notes); + witnessDetails.put("codex", template.codex); + witnessDetails.put("collection", template.collection); + witnessDetails.put("repository", template.repository); + witnessDetails.put("city", template.city); + witnessDetails.put("country", template.country); + witnessDetails.put("folios", template.folios); + witnessDetails.put("incipit", template.incipit); + witnessDetails.put("explicit", template.explicit); + witnessDetails.put("subject", template.subject); + witnessDetails.put("ahlwardtNo", template.ahlwardtNo); + witnessDetails.put("titleAsWrittenInWitness", template.titleAsWrittenInWitness); + witnessDetails.put("authorAsWrittenInWitness", template.authorAsWrittenInWitness); + witnessDetails.put("copyist", template.copyist); + witnessDetails.put("placeOfCopying", template.placeOfCopying); + witnessDetails.put("colophon", template.colophon); + + witnessDetails.put("pageDimensions", template.page_dimensions); + witnessDetails.put("writtenAreaDimensions", template.written_area_dimensions); + witnessDetails.put("linesPerPage", template.lines_per_page); + witnessDetails.put("pageLayout", template.page_layout); + witnessDetails.put("script", template.script); + witnessDetails.put("writingSurface", template.writing_surface); + witnessDetails.put("fullTitle", template.fullTitle); + witnessDetails.put("fullTitleTranslit", template.fullTitleTranslit); + witnessDetails.put("creationDate", template.creationDate); + + witnessDetails.put("authorName", template.authorName); + witnessDetails.put("authorNameTranslit", template.authorNameTranslit); + + + + JSONArray array = new JSONArray(); + for(String reader : template.wasStudiedByList){ + array.put(reader); + } + + witnessDetails.put("readers", array); + + + json.put("data", witnessDetails); + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONGetWitnesses4Codex.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,58 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONGetWitnesses4Codex extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + + String sid = request.getParameter(JSONUtils.P_ID); + Boolean includeRomanization = getBoolean(request, JSONUtils.P_INCL_ROMANIZATION); + + if(StringUtils.isEmpty(sid)){ + throw new Exception("Parameter id can not be null."); + } + Long codexId = Long.parseLong(sid); + + List<Entity> witnessList = ws.getSourcesForTargetRelation(codexId, "is_part_of", "WITNESS", -1); + + JSONArray array = new JSONArray(); + for(Entity ent : witnessList){ + array.put(JSONUtils.entityToJSON(ent, includeRomanization)); + } + json.put(JSONUtils.R_ENTS, array); + json.put(JSONUtils.R_ENTS_SIZE, witnessList.size()); + + + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/jsonmethods/JSONSearch.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,205 @@ +package de.mpiwg.itgroup.ismi.servlets.jsonmethods; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Deque; +import java.util.LinkedList; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class JSONSearch extends AbstractServletJSONMethod{ + + public static void execute(WrapperService ws, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject json = new JSONObject(); + long startExecution = System.currentTimeMillis(); + + try{ + + String query = getString(request, "query"); + Boolean includeRomanization = getBoolean(request, JSONUtils.P_INCL_ROMANIZATION); + + if(StringUtils.isEmpty(query)){ + json.put(RESPONSE, EXCEPTION); + json.put(RESPONSE_INFO, "Parameter 'query' is mandatory and should be a number."); + + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter 'query' is mandatory and should be a number."); + }else{ + if(query.startsWith("/")){ + query = query.replaceFirst("/", ""); + } + String[] queryArray = query.split("/"); + + + boolean idAtBeginning = true; + List<Long> idList = getIdListFromString(queryArray[0]); + if(idList.isEmpty()){ + idList = getIdListFromString(queryArray[queryArray.length-1]); + idAtBeginning = false; + } + + + Deque<String> pathQueue; + if(idAtBeginning){ + pathQueue = getPathExcludingBeginning(queryArray); + searchFromLeft(json, idList, pathQueue, false, ws, includeRomanization); + }else{ + pathQueue = getPathExcludingEnd(queryArray); + searchFromLeft(json, idList, pathQueue, true, ws, includeRomanization); + } + } + + }catch (Exception e) { + PrintWriter out = response.getWriter(); + out.print(json.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + e.printStackTrace(); + }finally{ + json = finallyExecution(json, parametersToString(request.getParameterMap()), startExecution); + } + PrintWriter out = response.getWriter(); + out.print(json.toString()); + + } + + + public static void searchFromLeft(JSONObject jsonResult, List<Long> idList, Deque<String> pathQueue, boolean fromRight, + WrapperService ws, + boolean includeRomanization) throws Exception{ + + JSONArray rsArray = new JSONArray(); + JSONArray idNoFoundArray = new JSONArray(); + int count = 0; + for(Long rootId : idList){ + Entity root = ws.getLightweightEntityById(rootId); + if(root != null){ + + List<Deque<Entity>> rs = null; + if(fromRight){ + rs = searchFromRight(new LinkedList<String>(pathQueue), root, ws); + }else{ + rs = searchFromLeft(new LinkedList<String>(pathQueue), root, ws); + } + + for(Deque<Entity> entry : rs){ + JSONArray entryArray = new JSONArray(); + while(!entry.isEmpty()){ + Entity ent = (fromRight) ? entry.removeFirst() : entry.removeLast(); + entryArray.put(JSONUtils.entityToJSON(ent, includeRomanization)); + } + rsArray.put(entryArray); + count++; + } + }else{ + System.err.println("JSONGetPath - Entity no found - ID=" + rootId); + idNoFoundArray.put(rootId); + } + } + jsonResult.put("rs", rsArray); + jsonResult.put("ids_no_found", idNoFoundArray); + jsonResult.put("rs_size", count); + } + + public static List<Deque<Entity>> searchFromRight(Deque<String> PathQueue, Entity tar, WrapperService ws){ + List<Deque<Entity>> rs = new ArrayList<Deque<Entity>>(); + + if(!PathQueue.isEmpty()){ + String relName = PathQueue.pollLast(); + String srcOC = PathQueue.pollLast(); + + List<Entity> srcs = ws.getSourcesForTargetRelation(tar, relName, srcOC, -1); + + if(!srcs.isEmpty()){ + for(Entity src : srcs){ + List<Deque<Entity>> rs0 = searchFromRight(new LinkedList<String>(PathQueue), src, ws); + for(Deque<Entity> deque : rs0){ + deque.add(tar); + rs.add(deque); + } + } + } + + }else{ + Deque<Entity> resultEntry = new LinkedList<Entity>(); + resultEntry.add(tar); + rs.add(resultEntry); + } + + return rs; + } + + public static List<Deque<Entity>> searchFromLeft(Deque<String> pathQueue, Entity src, WrapperService ws){ + + List<Deque<Entity>> rs = new ArrayList<Deque<Entity>>(); + + if(!pathQueue.isEmpty()){ + String relName = pathQueue.pollFirst(); + String tarOC = pathQueue.pollFirst(); + + List<Entity> tars = ws.getTargetsForSourceRelation(src, relName, tarOC, -1); + + if(!tars.isEmpty()){ + for(Entity tar : tars){ + List<Deque<Entity>> rs0 = searchFromLeft(new LinkedList<String>(pathQueue), tar, ws); + for(Deque<Entity> deque : rs0){ + deque.add(src); + rs.add(deque); + } + } + }else{ + Deque<Entity> resultEntry = new LinkedList<Entity>(); + resultEntry.add(src); + rs.add(resultEntry); + } + }else{ + Deque<Entity> resultEntry = new LinkedList<Entity>(); + resultEntry.add(src); + rs.add(resultEntry); + } + + return rs; + } + + private static List<Long> getIdListFromString(String values){ + List<Long> list = new ArrayList<Long>(); + String[] idArray = values.split(","); + try{ + for(int i=0; i<idArray.length; i++){ + list.add(new Long(idArray[i])); + } + }catch (Exception e) {} + + return list; + } + + private static Deque<String> getPathExcludingBeginning(String[] query){ + Deque<String> pathQueue = new LinkedList<String>(); + for(int i=1; i<query.length; i++){ + System.out.print(query[i] + "\t"); + pathQueue.add(query[i]); + } + return pathQueue; + } + + private static Deque<String> getPathExcludingEnd(String[] query){ + Deque<String> pathQueue = new LinkedList<String>(); + for(int i=0; i<query.length-1; i++){ + System.out.print(query[i] + "\t"); + pathQueue.add(query[i]); + } + return pathQueue; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/servlets/testing/Performance.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,177 @@ +package de.mpiwg.itgroup.ismi.servlets.testing; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URL; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + + +public class Performance { + + private static final int BUFFER_SIZE = 1024; + + public static void executeWitnessTest(Long id){ + + try { + getText(id); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static void getText(Long textId) throws Exception { + + //System.out.println(json.getString("ent")); + + Entity text = getEnt(textId); + + System.out.println(text.toString()); + + getWitness(text.getId()); + } + + private static void getWitness(Long textId) throws Exception { + + List<Entity> witnessList = getSrcs4TarRel(textId, "is_exemplar_of", "WITNESS"); + for(Entity w : witnessList){ + //System.out.println(w.toString()); + getCodex(w.getId()); + } + } + + private static void getCodex(Long witnessId) throws Exception { + //get_tars_4_src_rel&id=witnessId&rel_name=is_part_of&tar_oc=CODEX + + List<Entity> codexList = getTars4SrcRel(witnessId, "is_part_of", "CODEX"); + for(Entity codex : codexList){ + //System.out.println(codex.toString()); + getCollection(codex.getId()); + } + } + + private static void getCollection(Long codexId) throws Exception { + //get_tars_4_src_rel&id=codexId&rel_name=is_part_of&tar_oc=COLLECTION + + List<Entity> collList = getTars4SrcRel(codexId, "is_part_of", "COLLECTION"); + for(Entity coll : collList){ + //System.out.println(coll.toString()); + getRepository(coll.getId()); + } + + } + + private static void getRepository(Long collectionId) throws Exception { + //get_tars_4_src_rel&id=collectionId&rel_name=is_part_of&tar_oc=REPOSITORY + + List<Entity> repList = getTars4SrcRel(collectionId, "is_part_of", "REPOSITORY"); + for(Entity rep : repList){ + System.out.println(rep.toString()); + } + } + + private static void getPlace(Long repositoryId) throws Exception { + //get_tars_4_src_rel&id=repositoryId&rel_name=is_in&tar_oc=PLACE + } + + private static Entity getEnt(Long id) throws Exception{ + JSONObject json = jsonFromURL("get_ent&id=" + id + "&include_content=true"); + return JSONUtils.jsonToEntity(json.getJSONObject("ent")); + } + + private static List<Entity> getTars4SrcRel(Long id, String relName, String tarOC) throws Exception{ + List<Entity> rs = new ArrayList<Entity>(); + JSONObject json = jsonFromURL("get_tars_4_src_rel&id=" + id + "&rel_name=" + relName + "&tar_oc=" + tarOC); + + JSONArray jsonArray = json.getJSONArray("ents"); + for(int i =0; i<jsonArray.length(); i++){ + rs.add(JSONUtils.jsonToEntity(jsonArray.getJSONObject(i))); + } + return rs; + } + + private static List<Entity> getSrcs4TarRel(Long id, String relName, String srcOC) throws Exception{ + List<Entity> rs = new ArrayList<Entity>(); + JSONObject json = jsonFromURL("get_srcs_4_tar_rel&id=" + id + "&rel_name=" + relName + "&src_oc=" + srcOC); + + JSONArray jsonArray = json.getJSONArray("ents"); + for(int i =0; i<jsonArray.length(); i++){ + rs.add(JSONUtils.jsonToEntity(jsonArray.getJSONObject(i))); + } + return rs; + } + + + //get a BufferedReader for a webpage from its URL + public static BufferedReader read(URL url) throws Exception { + return new BufferedReader(new InputStreamReader(url.openStream(),"utf-8")); + } + + public static JSONObject jsonFromURL(String s) throws Exception { + String url = "https://openmind-ismi-dev.mpiwg-berlin.mpg.de/om4-ismi/jsonInterface?method=" + s; + + System.out.println(url); + trustAll(); + URL realURL = new URL(url); + BufferedReader reader = read(realURL); + int charsRead; + char[] copyBuffer = new char[BUFFER_SIZE]; + StringBuffer sb = new StringBuffer(); + while ((charsRead = reader.read(copyBuffer, 0, BUFFER_SIZE)) != -1) + sb.append(copyBuffer, 0, charsRead); + + return new JSONObject(sb.toString()); + } + //allows us to access https connections without verifying the certificate + public static void trustAll() throws Exception { + // Create a trust manager that does not validate certificate chains + TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + public void checkClientTrusted(X509Certificate[] certs, String authType) { + } + public void checkServerTrusted(X509Certificate[] certs, String authType) { + } + } + }; + + // Install the all-trusting trust manager + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + + // Create all-trusting host name verifier + HostnameVerifier allHostsValid = new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + + // Install the all-trusting host verifier + HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); + } + + /** + * @param args + */ + public static void main(String[] args) { + Performance.executeWitnessTest(new Long(444596)); + + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/tool/beans/SelectInputDateBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,152 @@ +/* MPL License text (see http://www.mozilla.org/MPL/) */ + + +package de.mpiwg.itgroup.ismi.tool.beans; + + + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; +import java.util.GregorianCalendar; + +//rich import com.icesoft.faces.context.effects.Effect; +//rich import com.icesoft.faces.context.effects.Highlight; + +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +/** + * <p>The SelectInputDateBean Class is used to store the selected dates from the + * selectinputdate components.</p> + * + * @since 0.3 + */ +public class SelectInputDateBean { + /** + * Variables to store the selected dates. + */ + private Date date1=new Date(); + private Date date2=new Date(); + private Date date3=new Date(); + private Date date4=new Date(); + private String pattern ="date"; + private List patterns = new ArrayList(); + // effect is fired when dat2 value is changed. + + /* rich + protected Effect valueChangeEffect2; + + public SelectInputDateBean() { + super(); + valueChangeEffect2 = new Highlight("#fda505"); + valueChangeEffect2.setFired(true); + date2 = new GregorianCalendar().getTime(); + patterns.add(new SelectItem("date", "MM/dd/yyyy")); + patterns.add(new SelectItem("dateTime", "MMM/dd/yyyy HH:mm")); + patterns.add(new SelectItem("dateTimeAmPm", "MMM/dd/yyyy hh:mm a")); + }*/ + + /** + * Gets the first selected date. + * + * @return the first selected date + */ + public Date getDate1() { + return date1; + } + + /** + * Sets the first selected date. + * + * @param date the first selected date + */ + public void setDate1(Date date) { + date1 = date; + } + + /** + * Gets the 2nd selected date. + * + * @return the 2nd selected date + */ + public Date getDate2() { + return date2; + } + + /** + * Sets the 2nd selected date. + * + * @param date the 2nd selected date + */ + public void setDate2(Date date) { + date2 = date; + } + + /** + * Gets the default timezone of the host server. The timezone is needed + * by the convertDateTime for formatting the time dat values. + * + * @return timezone for the current JVM + */ + public TimeZone getTimeZone() { + return java.util.TimeZone.getDefault(); + } + + /* rich + public Effect getValueChangeEffect2() { + return valueChangeEffect2; + } + + public void setValueChangeEffect2(Effect valueChangeEffect2) { + this.valueChangeEffect2 = valueChangeEffect2; + } + */ + + /** + * When values change event occures on date2 then we reset the effect + * so the user can see the changed value more easily. + * + * @param event JSF value change event. + */ + /* rich + public void effect2ChangeListener(ValueChangeEvent event){ + valueChangeEffect2.setFired(false); + } + */ + + public String getPattern() { + return pattern; + } + + public void setPattern(String pattern) { + this.pattern = pattern; + } + + public List getPatterns() { + return patterns; + } + + public void setPatterns(List patterns) { + this.patterns = patterns; + } + + public Date getDate3() { + return date3; + } + + public void setDate3(Date date3) { + this.date3 = date3; + } + + public Date getDate4() { + return date4; + } + + public void setDate4(Date date4) { + this.date4 = date4; + } + + +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/AbstractCalendar.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,205 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.model.SelectItem; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; + +public abstract class AbstractCalendar extends AbstractISMIBean{ + + private static final long serialVersionUID = -6494784177169138202L; + + public static String FROM = "from"; + public static String UNTIL = "until"; + public static String YEAR = "year"; + public static String ADD_INF = "additional_info"; + public static String CALENDAR_TYPE = "calendar_type"; + public static String INPUT_FORM = "input_form"; + public static String STATE = "state"; + public static String DATE = "date"; + public static String DATE_IN_TEXT = "date_in_text"; + + public static String INPUT_FORM_YEAR = "Year"; + public static String INPUT_FORM_DATE = "Date"; + public static String INPUT_FORM_FULL_DATE = "Full date"; + public static String INPUT_FORM_RANGE = "Range"; + public static String INPUT_FORM_FULL_RANGE = "Full range"; + + public static String TYPE_GREGORIAN = "Gregorian"; + public static String TYPE_ISLAMIC = "Islamic"; + public static String TYPE_JULIAN = "Julian"; + + public static String STATE_UNKNOWN = "unknown"; + public static String STATE_KNOWN = "known"; + public static String STATE_NOT_CHECKED = "not checked"; + + public static String FLOUIT = "flouit"; + public static String DISPLAY_FLOUIT = "display_flouit"; + + + + public String getSTATE_UNKNOWN(){ + return STATE_UNKNOWN; + } + + public String getSTATE_KNOWN(){ + return STATE_KNOWN; + } + + public String getSTATE_NOT_CHECKED(){ + return STATE_NOT_CHECKED; + } + + public List<SelectItem> getStateList(){ + return stateList; + } + + public static List<SelectItem> inputFormList = new ArrayList<SelectItem>(); + public static List<SelectItem> calendarTypeList = new ArrayList<SelectItem>(); + private static List<SelectItem> stateList = new ArrayList<SelectItem>(); + private static List<SelectItem> gregorianMonths = new ArrayList<SelectItem>(); + private static List<SelectItem> islamicMonths = new ArrayList<SelectItem>(); + private static List<SelectItem> julianMonths = new ArrayList<SelectItem>(); + private static List<SelectItem> suggestedDaysOfMonth = new ArrayList<SelectItem>(); + + protected static List<SelectItem> suggestedDaysOfWeek = new ArrayList<SelectItem>(8); + + + static{ + + suggestedDaysOfWeek.add(new SelectItem(0, "unknown")); + suggestedDaysOfWeek.add(new SelectItem(1, "Monday")); + suggestedDaysOfWeek.add(new SelectItem(2, "Tuesday")); + suggestedDaysOfWeek.add(new SelectItem(3, "Wednesday")); + suggestedDaysOfWeek.add(new SelectItem(4, "Thursday")); + suggestedDaysOfWeek.add(new SelectItem(5, "Friday")); + suggestedDaysOfWeek.add(new SelectItem(6, "Saturday")); + suggestedDaysOfWeek.add(new SelectItem(7, "Sunday")); + + stateList.add(new SelectItem(STATE_NOT_CHECKED)); + stateList.add(new SelectItem(STATE_KNOWN)); + stateList.add(new SelectItem(STATE_UNKNOWN)); + + inputFormList.add(new SelectItem(INPUT_FORM_YEAR)); + inputFormList.add(new SelectItem(INPUT_FORM_DATE)); + inputFormList.add(new SelectItem(INPUT_FORM_RANGE)); + + calendarTypeList.add(new SelectItem(TYPE_GREGORIAN)); + calendarTypeList.add(new SelectItem(TYPE_ISLAMIC)); + calendarTypeList.add(new SelectItem(TYPE_JULIAN)); + + //gregorianMonths.add(new SelectItem(new Integer(0), "-- choose --")); + gregorianMonths.add(new SelectItem(new Integer(1), "1 - January")); + gregorianMonths.add(new SelectItem(new Integer(2), "2 - February")); + gregorianMonths.add(new SelectItem(new Integer(3), "3 - March")); + gregorianMonths.add(new SelectItem(new Integer(4), "4 - April")); + gregorianMonths.add(new SelectItem(new Integer(5), "5 - May")); + gregorianMonths.add(new SelectItem(new Integer(6), "6 - June")); + gregorianMonths.add(new SelectItem(new Integer(7), "7 - July")); + gregorianMonths.add(new SelectItem(new Integer(8), "8 - August")); + gregorianMonths.add(new SelectItem(new Integer(9), "9 - September")); + gregorianMonths.add(new SelectItem(new Integer(10), "10 - October")); + gregorianMonths.add(new SelectItem(new Integer(11), "11 - November")); + gregorianMonths.add(new SelectItem(new Integer(12), "12 - December")); + + //islamicMonths.add(new SelectItem(new Integer(0), "-- choose --")); + + islamicMonths.add(new SelectItem(new Integer(1), "1 - " + hex("Muḥarram"))); + islamicMonths.add(new SelectItem(new Integer(2), "2 - " + hex("Ṣafar"))); + islamicMonths.add(new SelectItem(new Integer(3), "3 - " + hex("Rabīʿ I"))); + islamicMonths.add(new SelectItem(new Integer(4), "4 - " + hex("Rabīʿ II"))); + islamicMonths.add(new SelectItem(new Integer(5), "5 - " + hex("Jumādỳ I"))); + islamicMonths.add(new SelectItem(new Integer(6), "6 - " + hex("Jumādỳ II"))); + islamicMonths.add(new SelectItem(new Integer(7), "7 - Rajab")); + islamicMonths.add(new SelectItem(new Integer(8), "8 - " + hex("Šaʿbān"))); + islamicMonths.add(new SelectItem(new Integer(9), "9 - " + hex("Ramaḍān"))); + islamicMonths.add(new SelectItem(new Integer(10), "10 - " + hex("Šawwāl"))); + islamicMonths.add(new SelectItem(new Integer(11), "11 - " + hex("Ḏu al-Qaʿdaẗ"))); + islamicMonths.add(new SelectItem(new Integer(12), "12 - " + hex("Ḏu al-Ḥijjaẗ"))); + + //julianMonths.add(new SelectItem(new Integer(0), "-- choose --")); + julianMonths.add(new SelectItem(new Integer(1), "1 - Ianuarius")); + julianMonths.add(new SelectItem(new Integer(2), "2 - Februarius")); + julianMonths.add(new SelectItem(new Integer(3), "3 - Martius")); + julianMonths.add(new SelectItem(new Integer(4), "4 - Aprilis")); + julianMonths.add(new SelectItem(new Integer(5), "5 - Maius")); + julianMonths.add(new SelectItem(new Integer(6), "6 - Iunius")); + julianMonths.add(new SelectItem(new Integer(7), "7 - Quintilis (Iulius)")); + julianMonths.add(new SelectItem(new Integer(8), "8 - Sextilis (Augustus)")); + julianMonths.add(new SelectItem(new Integer(9), "9 - September")); + julianMonths.add(new SelectItem(new Integer(10), "10 - October")); + julianMonths.add(new SelectItem(new Integer(11), "11 - November")); + julianMonths.add(new SelectItem(new Integer(12), "12 - December")); + + //suggestedDaysOfMonth.add(new SelectItem(new Integer(0), "-- choose --")); + for(int i=1; i<= 31; i++){ + suggestedDaysOfMonth.add(new SelectItem(new Integer(i), "" + i)); + } + } + + public static String hex(String s){ + + Character c = 0x1e25; + s = s.replace("ḥ", c + ""); + c = 0x1e62; + s = s.replace("Ṣ", c + ""); + c = 0x12b; + s = s.replace("ī", c + ""); + c = 0x2bf; + s = s.replace("ʿ", c + ""); + c = 0x101; + s = s.replace("ā", c + ""); + c = 0x1ef3; + s = s.replace("ỳ", c + ""); + c = 0x160; + s = s.replace("Š", c + ""); + c = 0x1e0d; + s = s.replace("ḍ", c + ""); + c = 0x1e0e; + s = s.replace("Ḏ", c + ""); + c = 0x1e24; + s = s.replace("Ḥ", c + ""); + c = 0x1e97; + s = s.replace("ẗ", c + ""); + + return s; + } + + public List<SelectItem> getSuggestedDaysOfMonth(){ + return suggestedDaysOfMonth; + } + + public List<SelectItem> getInputFormList(){ + return inputFormList; + } + + public List<SelectItem> getCalendarTypeList(){ + return calendarTypeList; + } + + public List<SelectItem> getGregorianMonths(){ + return gregorianMonths; + } + + public List<SelectItem> getIslamicMonths(){ + return islamicMonths; + } + + public List<SelectItem> getJulianMonths(){ + return julianMonths; + } + + public List<SelectItem> getSuggestedDaysOfWeek(){ + return suggestedDaysOfWeek; + } + + public String getINPUT_FORM_YEAR(){ return INPUT_FORM_YEAR;} + public String getINPUT_FORM_DATE(){ return INPUT_FORM_DATE;} + public String getINPUT_FORM_RANGE(){ return INPUT_FORM_RANGE;} + public String getINPUT_FORM_FULL_RANGE(){ return INPUT_FORM_FULL_RANGE;} + public String getTYPE_GREGORIAN(){ return TYPE_GREGORIAN;} + public String getTYPE_ISLAMIC(){ return TYPE_ISLAMIC;} + public String getTYPE_JULIAN(){ return TYPE_JULIAN;} +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/AbstractDate.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,94 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import javax.faces.model.SelectItem; + +public class AbstractDate { + + protected static Map<Integer, String> gregorianMonths = new HashMap<Integer, String>(12); + protected static Map<Integer, String> islamicMonths = new HashMap<Integer, String>(12); + protected static Map<Integer, String> julianMonths = new HashMap<Integer, String>(12); + + static{ + + gregorianMonths.put(1, "January (1)"); + gregorianMonths.put(2, "February (2)"); + gregorianMonths.put(3, "March (3)"); + gregorianMonths.put(4, "April (4)"); + gregorianMonths.put(5, "May (5)"); + gregorianMonths.put(6, "June (6)"); + gregorianMonths.put(7, "July (7)"); + gregorianMonths.put(8, "August (8)"); + gregorianMonths.put(9, "September (9)"); + gregorianMonths.put(10, "October (10)"); + gregorianMonths.put(11, "November (11)"); + gregorianMonths.put(12, "December (12)"); + + islamicMonths.put(1, hex("Muḥarram") + " (1)"); + islamicMonths.put(2, hex("Ṣafar") + " (2)"); + islamicMonths.put(3, hex("Rabīʿ I") + " (3)"); + islamicMonths.put(4, hex("Rabīʿ II") + " (4)"); + islamicMonths.put(5, hex("Jumādỳ I") + " (5)"); + islamicMonths.put(6, hex("Jumādỳ II") + " (6)"); + islamicMonths.put(7, "Rajab (7)"); + islamicMonths.put(8, hex("Šaʿbān") + " (8)"); + islamicMonths.put(9, hex("Ramaḍān") + " (9)"); + islamicMonths.put(10, hex("Šawwāl") + " (10)"); + islamicMonths.put(11, hex("Ḏu al-Qaʿdaẗ") + " (11)"); + islamicMonths.put(12, hex("Ḏu al-Ḥijjaẗ") + " (12)"); + + julianMonths.put(1, "Ianuarius (1)"); + julianMonths.put(2, "Februarius (2)"); + julianMonths.put(3, "Martius (3)"); + julianMonths.put(4, "Aprilis (4)"); + julianMonths.put(5, "Maius (5)"); + julianMonths.put(6, "Iunius (6)"); + julianMonths.put(7, "Quintilis (Iulius) (7)"); + julianMonths.put(8, "Sextilis (Augustus) (8)"); + julianMonths.put(9, "September (9)"); + julianMonths.put(10, "October (10)"); + julianMonths.put(11, "November (11)"); + julianMonths.put(12, "December (12)"); + } + + public static String hex(String s){ + + Character c = 0x1e25; + s = s.replace("ḥ", c + ""); + c = 0x1e62; + s = s.replace("Ṣ", c + ""); + c = 0x12b; + s = s.replace("ī", c + ""); + c = 0x2bf; + s = s.replace("ʿ", c + ""); + c = 0x101; + s = s.replace("ā", c + ""); + c = 0x1ef3; + s = s.replace("ỳ", c + ""); + c = 0x160; + s = s.replace("Š", c + ""); + c = 0x1e0d; + s = s.replace("ḍ", c + ""); + c = 0x1e0e; + s = s.replace("Ḏ", c + ""); + c = 0x1e24; + s = s.replace("Ḥ", c + ""); + c = 0x1e97; + s = s.replace("ẗ", c + ""); + + return s; + } + + protected boolean isDayInWeek(Integer day){ + if(day == null) + return false; + if(day >= 1 && day <= 7){ + return true; + } + return false; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/Calendar.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,543 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +import java.io.Serializable; + +import javax.faces.event.ActionEvent; + +import org.apache.commons.lang.StringUtils; +import org.joda.time.DateTime; +import org.joda.time.chrono.GregorianChronology; +import org.joda.time.chrono.IslamicChronology; +import org.joda.time.chrono.JulianChronology; +import org.json.JSONException; +import org.json.JSONObject; + +import de.mpiwg.itgroup.ismi.json.utils.JSONUtils; + +public class Calendar extends AbstractCalendar implements Serializable { + private static final long serialVersionUID = 1L; + + private String inputForm; + private String calendarType; + + private Date fromGregorian = new Date(); + private Date untilGregorian = new Date(); + private String additionalInfo; + + private Integer currentYear; + private Date currentFrom = new Date(); + private Date currentUntil = new Date(); + + private String dateInText; + private String state; + + public Calendar(){ + this.calendarType = TYPE_GREGORIAN; + this.inputForm = INPUT_FORM_YEAR; + this.state = STATE_NOT_CHECKED; + } + + public Calendar(String jsonString){ + if(StringUtils.isNotEmpty(jsonString)){ + try { + JSONObject json = new JSONObject(jsonString); + this.state = json.getString(STATE); + + if(StringUtils.isNotEmpty(state)){ + if(state.equals(STATE_KNOWN)){ + + this.additionalInfo = json.getString(ADD_INF); + this.calendarType = json.getString(CALENDAR_TYPE); + this.inputForm = json.getString(INPUT_FORM); + + if(inputForm.equals(INPUT_FORM_YEAR)){ + this.fromGregorian = new Date(json.getJSONObject(FROM)); + this.untilGregorian = new Date(json.getJSONObject(UNTIL)); + this.currentYear = json.getInt(YEAR); + }else if(inputForm.equals(INPUT_FORM_RANGE)){ + this.fromGregorian = new Date(json.getJSONObject(FROM)); + this.untilGregorian = new Date(json.getJSONObject(UNTIL)); + if(calendarType.equals(TYPE_GREGORIAN)){ + this.currentFrom = new Date(json.getJSONObject(FROM)); + this.currentUntil = new Date(json.getJSONObject(UNTIL)); + }else if(calendarType.equals(TYPE_ISLAMIC)){ + this.currentFrom = new Date(this.fromGregorian.getIslamicDateTime()); + this.currentUntil = new Date(this.untilGregorian.getIslamicDateTime()); + }else if(calendarType.equals(TYPE_JULIAN)){ + this.currentFrom = new Date(this.fromGregorian.getJulianDateTime()); + this.currentUntil = new Date(this.untilGregorian.getJulianDateTime()); + } + }else if(inputForm.equals(INPUT_FORM_DATE)){ + this.fromGregorian = new Date(json.getJSONObject(DATE)); + if(calendarType.equals(TYPE_GREGORIAN)){ + this.currentFrom = new Date(json.getJSONObject(DATE)); + }else if(calendarType.equals(TYPE_ISLAMIC)){ + this.currentFrom = new Date(this.fromGregorian.getIslamicDateTime()); + }else if(calendarType.equals(TYPE_JULIAN)){ + this.currentFrom = new Date(this.fromGregorian.getJulianDateTime()); + } + } + + if(json.has("dayOfWeekFrom")){ + this.currentFrom.setDayOfWeek(json.getInt("dayOfWeekFrom")); + } + if(json.has("dayOfWeekUntil")){ + this.currentUntil.setDayOfWeek(json.getInt("dayOfWeekUntil")); + } + if(json.has("dayOfWeek")){ + this.currentFrom.setDayOfWeek(json.getInt("dayOfWeek")); + } + + }else if(state.equals(STATE_NOT_CHECKED) || state.equals(STATE_UNKNOWN)){ + if(json.has(DATE_IN_TEXT)){ + this.dateInText = json.getString(DATE_IN_TEXT); + } + this.calendarType = TYPE_GREGORIAN; + this.inputForm = INPUT_FORM_YEAR; + } + } + + } catch (Exception e) { + e.printStackTrace(); + this.state = STATE_NOT_CHECKED; + this.calendarType = TYPE_GREGORIAN; + this.inputForm = INPUT_FORM_YEAR; + } + }else{ + this.calendarType = TYPE_GREGORIAN; + this.inputForm = INPUT_FORM_YEAR; + this.state = STATE_NOT_CHECKED; + } + } + + public void update(){ + + if(inputForm.equals(INPUT_FORM_RANGE)){ + if(isUntilOlderThanFrom()){ + if(calendarType.equals(TYPE_GREGORIAN)){ + this.inputGregorianRange(); + }else if(calendarType.equals(TYPE_ISLAMIC)){ + this.inputIslamicRange(); + }else if(calendarType.equals(TYPE_JULIAN)){ + this.inputJulianRange(); + } + }else{ + addGeneralMsg("The until date must be older than the from date."); + } + + }else if(inputForm.equals(INPUT_FORM_YEAR)){ + if(calendarType.equals(TYPE_GREGORIAN)){ + this.inputGregorianYear(); + }else if(calendarType.equals(TYPE_ISLAMIC)){ + this.inputIslamicYear(); + }else if(calendarType.equals(TYPE_JULIAN)){ + this.inputJulianYear(); + } + }else if(inputForm.equals(INPUT_FORM_DATE)){ + if(calendarType.equals(TYPE_GREGORIAN)){ + this.inputGregorianFrom(); + }else if(calendarType.equals(TYPE_ISLAMIC)){ + this.inputIslamicFrom(); + }else if(calendarType.equals(TYPE_JULIAN)){ + this.inputJulianFrom(); + } + } + } + + public boolean isDeployable(){ + return (!this.state.equals(STATE_NOT_CHECKED) && !this.state.equals(STATE_UNKNOWN)); + } + + public String getFormattedRange(){ + if(inputForm != null){ + String from = this.fromGregorian.toString(); + if(this.inputForm.equals(INPUT_FORM_DATE)){ + return "[" + from + "]"; + }else{ + + String until = this.untilGregorian.toString(); + if(StringUtils.isNotEmpty(from) && StringUtils.isNotEmpty(until)){ + return "[FROM: " + from + " TO: " + until + "]"; + } + } + } + return null; + } + + public String getFormattedIslamicRange(){ + if(inputForm != null){ + String from = this.fromGregorian.toIslamicString(); + if(this.inputForm.equals(INPUT_FORM_DATE)){ + return "[" + from + "]"; + }else{ + String until = this.untilGregorian.toIslamicString(); + if(StringUtils.isNotEmpty(from) && StringUtils.isNotEmpty(until)){ + return "[FROM: " + from + " TO: " + until + "]"; + } + } + } + return null; + } + + public String getFormattedJulianRange(){ + if(inputForm != null){ + String from = this.fromGregorian.toJulianString(); + if(this.inputForm.equals(INPUT_FORM_DATE)){ + return "[" + from + "]"; + }else{ + String until = this.untilGregorian.toJulianString(); + if(StringUtils.isNotEmpty(from) && StringUtils.isNotEmpty(until)){ + return "[FROM: " + from + " TO: " + until + "]"; + } + } + } + return null; + } + + public void listenerUpdate(ActionEvent e){ + this.update(); + } + + + public String getCalendarAsHtml(){ + StringBuilder sb = new StringBuilder(); + + if(isDeployable()){ + sb.append("<table align=\"left\">"); + + sb.append("<tr>"); + sb.append("<th align=\"left\">Gregorian:</th>"); + sb.append("<th align=\"left\">" + this.getFormattedRange() + "</th>"); + sb.append("</tr>"); + + sb.append("<tr>"); + sb.append("<th align=\"left\">Islamic:</th>"); + sb.append("<th align=\"left\">" + this.getFormattedIslamicRange() + "</th>"); + sb.append("</tr>"); + + sb.append("<tr>"); + sb.append("<th align=\"left\">Julian:</th>"); + sb.append("<th align=\"left\">" + this.getFormattedJulianRange() + "</th>"); + sb.append("</tr>"); + + sb.append("</table>"); + }else if(this.state.equals(STATE_UNKNOWN)){ + sb.append("Unkknown"); + }else{ + sb.append("Not checked"); + if(StringUtils.isNotEmpty(this.dateInText)){ + sb.append("=" + this.dateInText); + } + } + + return sb.toString(); + } + + + private void inputGregorianRange(){ + this.inputGregorianFrom(); + try{ + DateTime gregrorian = + new DateTime(currentUntil.getYear(), currentUntil.getMonth(), currentUntil.getDayOfMonth(), 0, 0, 0, 0, GregorianChronology.getInstance()); + this.untilGregorian = new Date(gregrorian.withChronology(GregorianChronology.getInstance())); + if(isDayInWeek(currentUntil.getDayOfWeek())){ + this.untilGregorian.setDayOfWeek(currentUntil.getDayOfWeek()); + } + }catch (Exception e) { + this.addGeneralMsg("In until date - " + e.getMessage()); + } + } + + private void inputGregorianFrom(){ + try{ + DateTime gregorian = + new DateTime(currentFrom.getYear(), currentFrom.getMonth(), currentFrom.getDayOfMonth(), 0, 0, 0, 0, GregorianChronology.getInstance()); + this.fromGregorian = new Date(gregorian); + if(isDayInWeek(currentFrom.getDayOfWeek())){ + this.fromGregorian.setDayOfWeek(currentFrom.getDayOfWeek()); + } + }catch (Exception e) { + this.addGeneralMsg("In from date - " + e.getMessage()); + } + } + + private void inputIslamicRange(){ + this.inputIslamicFrom(); + try{ + DateTime islamic = + new DateTime(currentUntil.getYear(), currentUntil.getMonth(), currentUntil.getDayOfMonth(), 0, 0, 0, 0, IslamicChronology.getInstance()); + DateTime gregorian = islamic.withChronology(GregorianChronology.getInstance()); + this.untilGregorian = new Date(gregorian); + if(isDayInWeek(currentUntil.getDayOfWeek())){ + this.untilGregorian.setDayOfWeek(gregorian.getDayOfWeek()); + }else{ + this.untilGregorian.setAmbiguity(2); + } + }catch (Exception e) { + this.addGeneralMsg("In until date - " + e.getMessage()); + } + } + + private void inputIslamicFrom(){ + try{ + DateTime islamic = + new DateTime(currentFrom.getYear(), currentFrom.getMonth(), currentFrom.getDayOfMonth(), 0, 0, 0, 0, IslamicChronology.getInstance()); + DateTime gregorian = islamic.withChronology(GregorianChronology.getInstance()); + this.fromGregorian = new Date(gregorian); + if(isDayInWeek(currentFrom.getDayOfWeek())){ + this.fromGregorian.setDayOfWeek(gregorian.getDayOfWeek()); + }else{ + this.fromGregorian.setAmbiguity(2); + } + }catch (Exception e) { + this.addGeneralMsg("In from date - " + e.getMessage()); + } + } + + + private void inputJulianRange(){ + this.inputJulianFrom(); + DateTime julian = null; + try{ + julian = + new DateTime(currentUntil.getYear(), currentUntil.getMonth(), currentUntil.getDayOfMonth(), 0, 0, 0, 0, JulianChronology.getInstance()); + DateTime gregorian = julian.withChronology(GregorianChronology.getInstance()); + this.untilGregorian = new Date(gregorian); + if(isDayInWeek(currentUntil.getDayOfWeek())){ + this.untilGregorian.setDayOfWeek(gregorian.getDayOfWeek()); + } + }catch (Exception e) { + this.addGeneralMsg("In until date - " + e.getMessage()); + } + } + + private void inputJulianFrom(){ + DateTime julian = null; + try{ + julian = + new DateTime(currentFrom.getYear(), currentFrom.getMonth(), currentFrom.getDayOfMonth(), 0, 0, 0, 0, JulianChronology.getInstance()); + DateTime gregorian = julian.withChronology(GregorianChronology.getInstance()); + this.fromGregorian = new Date(gregorian); + if(isDayInWeek(currentFrom.getDayOfWeek())){ + this.fromGregorian.setDayOfWeek(gregorian.getDayOfWeek()); + } + }catch (Exception e) { + addGeneralMsg("In from date - " + e.getMessage()); + } + } + + public void inputGregorianYear(){ + if(inputForm.equals(INPUT_FORM_YEAR) && currentYear != null){ + this.fromGregorian = new Date(new DateTime(currentYear, 1, 1, 0, 0, 0, 0, GregorianChronology.getInstance())); + this.untilGregorian = new Date(new DateTime(currentYear, 12, 31, 0, 0, 0, 0, GregorianChronology.getInstance())); + } + } + + public void inputIslamicYear(){ + if(this.currentYear < 1 || this.currentYear > 292271022){ + this.addGeneralMsg("year must be in the range [1,292271022]"); + }else { + DateTime islamic = + new DateTime(currentYear, 1, 1, 0, 0, 0, 0, IslamicChronology.getInstance()); + DateTime gregorian = islamic.withChronology(GregorianChronology.getInstance()); + this.fromGregorian = new Date(gregorian); + this.fromGregorian.setAmbiguity(2); + this.fromGregorian.setDayOfWeek(null); + + islamic = + new DateTime(currentYear, 12, 29, 0, 0, 0, 0, IslamicChronology.getInstance()); + gregorian = islamic.withChronology(GregorianChronology.getInstance()); + this.untilGregorian = new Date(gregorian); + this.untilGregorian.setAmbiguity(2); + this.untilGregorian.setDayOfWeek(null); + } + } + + public void inputJulianYear(){ + if(this.currentYear < 1){ + this.addGeneralMsg("Value 0 for year is not supported"); + }else{ + DateTime julian = + new DateTime(currentYear, 1, 1, 0, 0, 0, 0, JulianChronology.getInstance()); + DateTime gregorian = julian.withChronology(GregorianChronology.getInstance()); + this.fromGregorian = new Date(gregorian); + this.fromGregorian.setDayOfWeek(null); + + julian = + new DateTime(currentYear, 12, 31, 0, 0, 0, 0, JulianChronology.getInstance()); + gregorian = julian.withChronology(GregorianChronology.getInstance()); + this.untilGregorian = new Date(gregorian); + this.untilGregorian.setDayOfWeek(null); + } + } + + + public String toJSONString(){ + this.update(); + JSONObject json = this.toJSON(); + if(json != null){ + return json.toString(); + } + return ""; + } + + public JSONObject toJSON(){ + JSONObject json = new JSONObject(); + if(state.equals(STATE_KNOWN)){ + try { + + if(inputForm.equals(INPUT_FORM_YEAR)){ + json.put(YEAR, this.currentYear); + json.put(FROM, this.fromGregorian.toJSON()); + json.put(UNTIL, this.untilGregorian.toJSON()); + }else if(inputForm.equals(INPUT_FORM_RANGE)){ + json.put(FROM, this.fromGregorian.toJSON()); + json.put(UNTIL, this.untilGregorian.toJSON()); + if(isDayInWeek(currentFrom.getDayOfWeek())){ + json.put("dayOfWeekFrom", currentFrom.getDayOfWeek()); + } + if(isDayInWeek(currentUntil.getDayOfWeek())){ + json.put("dayOfWeekUntil", currentUntil.getDayOfWeek()); + } + }else if(inputForm.equals(INPUT_FORM_DATE)){ + json.put(DATE, this.fromGregorian.toJSON()); + if(isDayInWeek(currentFrom.getDayOfWeek())){ + json.put("dayOfWeek", currentFrom.getDayOfWeek()); + } + } + + json.put(STATE, this.state); + json.put(ADD_INF, additionalInfo); + json.put(CALENDAR_TYPE, this.calendarType); + json.put(INPUT_FORM, this.inputForm); + + } catch (JSONException e) { + e.printStackTrace(); + } + return json; + }else if(state.equals(STATE_UNKNOWN)){ + try { + json.put(STATE, this.state); + } catch (JSONException e) { + e.printStackTrace(); + } + return json; + }else if(state.equals(STATE_NOT_CHECKED) && StringUtils.isNotEmpty(dateInText)){ + try { + json.put(STATE, this.state); + json.put(DATE_IN_TEXT, this.dateInText); + } catch (JSONException e) { + e.printStackTrace(); + } + return json; + } + return null; + } + + public boolean isUntilOlderThanFrom(){ + if(this.currentFrom.getYear() != null && this.currentUntil.getYear() != null){ + if(this.currentFrom.getYear() < this.currentUntil.getYear()){ + return true; + }else if(this.currentFrom.getYear().equals(this.currentUntil.getYear())){ + if(this.currentFrom.getMonth() != null && this.currentUntil.getMonth() != null){ + if(this.currentFrom.getMonth() < this.currentUntil.getMonth()){ + return true; + }else if(this.currentFrom.getMonth().equals(this.currentUntil.getMonth())){ + if(this.currentFrom.getDayOfMonth() != null && this.currentUntil.getDayOfMonth() != null){ + if(this.currentFrom.getDayOfMonth() < this.currentUntil.getDayOfMonth()){ + return true; + } + } + } + } + } + } + return false; + } + + private boolean isDayInWeek(Integer day){ + if(day == null) + return false; + if(day >= 1 && day <= 7){ + return true; + } + return false; + } + + public Date getFromGregorian() { + return fromGregorian; + } + public void setFromGregorian(Date fromGregorian) { + this.fromGregorian = fromGregorian; + } + public Date getUntilGregorian() { + return untilGregorian; + } + public void setUntilGregorian(Date untilGregorian) { + this.untilGregorian = untilGregorian; + } + + public String getInputForm() { + return inputForm; + } + + public void setInputForm(String inputForm) { + this.inputForm = inputForm; + } + + public String getCalendarType() { + return calendarType; + } + + public void setCalendarType(String calendarType) { + this.calendarType = calendarType; + } + + public String getAdditionalInfo() { + return additionalInfo; + } + + public void setAdditionalInfo(String additionalInfo) { + this.additionalInfo = additionalInfo; + } + + public Integer getCurrentYear() { + return currentYear; + } + + public void setCurrentYear(Integer currentYear) { + this.currentYear = currentYear; + } + + public Date getCurrentFrom() { + return currentFrom; + } + + public void setCurrentFrom(Date currentFrom) { + this.currentFrom = currentFrom; + } + + public Date getCurrentUntil() { + return currentUntil; + } + + public void setCurrentUntil(Date currentUntil) { + this.currentUntil = currentUntil; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getDateInText() { + return dateInText; + } + + public void setDateInText(String dateInText) { + this.dateInText = dateInText; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/DataPaginator.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,128 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +import java.text.MessageFormat; + +public class DataPaginator { + /* This should be parameters or properties stored somewhere */ + private int itemsPerPage = 10; + private int rewindFastForwardBy = 10; + + private int currentPage; + private int numberOfPages; + + private String recordStatus; + + public void first(){ + this.currentPage = 0; + } + + public void last(){ + this.currentPage = this.numberOfPages -1; + } + + public void fastRewind () { + this.rewind(this.rewindFastForwardBy); + } + + private void rewind (int aRewindFastForwardBy) { + int newPageNumber = currentPage - aRewindFastForwardBy; + if (newPageNumber < 0) { + currentPage = 0; + } else { + currentPage = newPageNumber; + } + } + + public void goToPage(int newPageNumber){ + if (newPageNumber > this.numberOfPages -1) { + currentPage = this.numberOfPages -1; + } else if(newPageNumber < 0 ){ + currentPage = 0; + }else{ + currentPage = newPageNumber; + } + + } + + private void forward (int aRewindFastForwardBy) { + int newPageNumber = currentPage + aRewindFastForwardBy; + if (newPageNumber > this.numberOfPages - 1) { + currentPage = this.numberOfPages -1; + } else { + currentPage = newPageNumber; + } + } + + public void previous () { + this.rewind(1); + } + + public void next () { + this.forward(1); + } + + public void fastForward () { + this.forward(this.rewindFastForwardBy); + } + + public void initCount() { + if (currentPage > numberOfPages) { + currentPage=numberOfPages; + } + } + + public int getNumberOfPages() { + return numberOfPages; + } + + public void setNumberOfPages(int numberOfPages) { + this.numberOfPages = numberOfPages; + } + + public void resetNumberOfPages(int itemsTotal){ + int numberOfPages = (itemsTotal + % this.getItemsPerPage() == 0) ? + itemsTotal + / this.getItemsPerPage() : + (itemsTotal + / this.getItemsPerPage()) + 1; + this.setNumberOfPages(numberOfPages); + } + + public int getCurrentPage() { + return currentPage; + } + + public void setCurrentPage(int currentPage) { + this.currentPage = currentPage; + } + + public String getRecordStatus () { + this.recordStatus = MessageFormat.format("{0} of {1}", + new Object []{ + Integer.valueOf(currentPage + 1), + Integer.valueOf(numberOfPages) + }); + return recordStatus; + } + + public void setRecordStatus(String recordStatus) { + this.recordStatus = recordStatus; + } + + public int getItemsPerPage() { + return itemsPerPage; + } + + public void setItemsPerPage(int itemsPerPage) { + this.itemsPerPage = itemsPerPage; + } + + public int getRewindFastForwardBy() { + return rewindFastForwardBy; + } + + public void setRewindFastForwardBy(int rewindFastForwardBy) { + this.rewindFastForwardBy = rewindFastForwardBy; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/Date.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,219 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +import java.io.Serializable; + +import org.joda.time.DateTime; +import org.joda.time.chrono.GregorianChronology; +import org.joda.time.chrono.IslamicChronology; +import org.joda.time.chrono.JulianChronology; +import org.json.JSONException; +import org.json.JSONObject; + +public class Date extends AbstractDate implements Serializable{ + private static final long serialVersionUID = -6470414082851873885L; + + public static String AMBIGUITY = "2"; + + private Integer dayOfMonth; + private Integer dayOfWeek; + private Integer dayOfYear; + private Integer month; + private Integer year; + private Integer century; + private Integer ambiguity; + + public Date(){} + + public Date(DateTime dateTime){ + this.setTime(dateTime); + this.ambiguity = 0; + } + + /* + public Date(Integer year, Integer month, Integer dayOfMonth){ + this.year = year; + this.month = month; + this.dayOfMonth = dayOfMonth; + }*/ + + public Date(JSONObject json) { + try{ + dayOfMonth = json.getInt("dayOfMonth"); + month = json.getInt("month"); + year = json.getInt("year"); + //century = json.getInt("century"); + if(json.has("century")){ + century = json.getInt("century"); + } + if(json.has("dayOfWeek")){ + dayOfWeek = json.getInt("dayOfWeek"); + } + if(json.has("dayOfYear")){ + dayOfYear = json.getInt("dayOfYear"); + } + if(json.has("ambiguity")){ + ambiguity = json.getInt("ambiguity"); + } + }catch (Exception e) { + e.printStackTrace(); + } + } + + public void setTime(DateTime dateTime){ + //TODO is gregorian chronology + this.dayOfMonth = dateTime.getDayOfMonth(); + this.dayOfYear = dateTime.getDayOfYear(); + //this.dayOfWeek = dateTime.getDayOfWeek(); + this.month = dateTime.getMonthOfYear(); + this.year = dateTime.getYear(); + this.century = dateTime.getCenturyOfEra(); + } + + public JSONObject toJSON(){ + JSONObject json = new JSONObject(); + try { + json.put("dayOfMonth", dayOfMonth); + json.put("dayOfYear", dayOfYear); + json.put("month", month); + json.put("year", year); + json.put("century", century); + json.put("dayOfWeek", dayOfWeek); + json.put("ambiguity", ambiguity); + } catch (JSONException e) { + e.printStackTrace(); + } + return json; + } + + public String toString(){ + if(year == null || month == null || dayOfMonth == null) + return null; + StringBuilder sb = new StringBuilder(); + sb.append(this.dayOfMonth + "."); + sb.append(Date.gregorianMonths.get(this.month) + "."); + sb.append(this.year); + if(this.ambiguity != null && this.ambiguity > 0){ + sb.append(" [+-" + this.ambiguity + "]"); + } + return sb.toString(); + } + + public String toIslamicString(){ + try{ + if(year == null || month == null || dayOfMonth == null) + return null; + + DateTime gr = + new DateTime(this.year, this.month, this.dayOfMonth, 0, 0, 0, 0, GregorianChronology.getInstance()); + + DateTime islamic = new DateTime(gr.withChronology(IslamicChronology.getInstance())); + + StringBuilder sb = new StringBuilder(); + sb.append(islamic.getDayOfMonth() + "."); + sb.append(Date.islamicMonths.get(islamic.getMonthOfYear()) + "."); + sb.append(islamic.getYear()); + if(!isDayInWeek(this.dayOfWeek) && !hasAmbiguity()){ + sb.append(" [+-" + AMBIGUITY + "]"); + } + return sb.toString(); + }catch (Exception e) {} + return "no valid"; + } + + public boolean hasAmbiguity(){ + if(this.getAmbiguity() == null) + return false; + if(this.getAmbiguity() > 0) + return true; + return false; + } + + public String toJulianString(){ + try{ + if(year == null || month == null || dayOfMonth == null) + return null; + + DateTime gr = + new DateTime(this.year, this.month, this.dayOfMonth, 0, 0, 0, 0, GregorianChronology.getInstance()); + + DateTime julian = new DateTime(gr.withChronology(JulianChronology.getInstance())); + + StringBuilder sb = new StringBuilder(); + sb.append(julian.getDayOfMonth() + "."); + sb.append(Date.julianMonths.get(julian.getMonthOfYear()) + "."); + sb.append(julian.getYear()); + if(this.ambiguity != null && this.ambiguity > 0){ + sb.append(" [+-" + this.ambiguity + "]"); + } + return sb.toString(); + }catch (Exception e) {} + return "no valid"; + } + + public DateTime getIslamicDateTime(){ + if(year == null || month == null || dayOfMonth == null) + return null; + try{ + DateTime gr = + new DateTime(this.year, this.month, this.dayOfMonth, 0, 0, 0, 0, GregorianChronology.getInstance()); + + return new DateTime(gr.withChronology(IslamicChronology.getInstance())); + }catch (Exception e) {} + return null; + } + + public DateTime getJulianDateTime(){ + if(year == null || month == null || dayOfMonth == null) + return null; + try{ + DateTime gr = + new DateTime(this.year, this.month, this.dayOfMonth, 0, 0, 0, 0, GregorianChronology.getInstance()); + + return new DateTime(gr.withChronology(JulianChronology.getInstance())); + }catch (Exception e) {} + return null; + } + + public Integer getDayOfMonth() { + return dayOfMonth; + } + public void setDayOfMonth(Integer dayOfMonth) { + this.dayOfMonth = dayOfMonth; + } + public Integer getDayOfWeek() { + return dayOfWeek; + } + public void setDayOfWeek(Integer dayOfWeek) { + this.dayOfWeek = dayOfWeek; + } + public Integer getDayOfYear() { + return dayOfYear; + } + public void setDayOfYear(Integer dayOfYear) { + this.dayOfYear = dayOfYear; + } + public Integer getMonth() { + return month; + } + public void setMonth(Integer month) { + this.month = month; + } + public Integer getYear() { + return year; + } + public void setYear(Integer year) { + this.year = year; + } + public Integer getCentury() { + return century; + } + public void setCentury(Integer century) { + this.century = century; + } + public Integer getAmbiguity() { + return ambiguity; + } + public void setAmbiguity(Integer ambiguity) { + this.ambiguity = ambiguity; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/EndNoteMisattribution.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,111 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +import java.io.Serializable; +import java.util.List; + +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Node; +import org.mpi.openmind.repository.bo.Relation; + +public class EndNoteMisattribution implements Serializable { + private static final long serialVersionUID = -1840193000833171154L; + + public static String MISATT = "MISATTRIBUTION"; + public static String MISATTRIBUTED_TO = "misattributed_to"; + public static String IS_REFERENCE_OF = "is_reference_of"; + public static String HAS_AUTHOR_MISATT = "has_author_misattribution"; + + private Entity misatt; + private Entity person; + private Reference ref; + private WrapperService ot; + private String userName; + + public EndNoteMisattribution(WrapperService ot, String userName){ + this.ot = ot; + this.userName = userName; + } + + public Entity saveAndGetMisattribution(Entity text) throws Exception{ + + if(misatt == null){ + misatt = new Entity(Node.TYPE_ABOX, MISATT, false); + } + + Entity entityRef = this.ref.getEnt(); + ot.saveAssertion(entityRef, userName); + + this.misatt.removeAllSourceRelations(MISATTRIBUTED_TO, "PERSON"); + Relation rel0 = new Relation(misatt, person, MISATTRIBUTED_TO); + + this.misatt.removeAllTargetRelations(IS_REFERENCE_OF, "REFERENCE"); + Relation rel1 = new Relation(entityRef, misatt, IS_REFERENCE_OF); + + this.misatt.removeAllTargetRelations(HAS_AUTHOR_MISATT, "TEXT"); + Relation rel2 = new Relation(text, misatt, HAS_AUTHOR_MISATT); + + + ot.saveAssertion(misatt, userName); + + return text; + } + + public static EndNoteMisattribution create(Entity person, WrapperService ot, String userName) { + EndNoteMisattribution obj = new EndNoteMisattribution(ot, userName); + + obj.setPerson(person); + obj.setRef(new Reference(null)); + + return obj; + } + + public static EndNoteMisattribution load(Entity misatt, WrapperService ot, String userName) throws Exception{ + + EndNoteMisattribution obj = new EndNoteMisattribution(ot, userName); + + if(misatt.isLightweight()){ + obj.setMisatt(ot.getEntityByIdWithContent(misatt.getId())); + } + //loading person. Person can be Light Weight + List<Entity> tmpList = ot.getTargetsForSourceRelation(misatt, MISATTRIBUTED_TO, "PERSON", -1); + if(tmpList.size() > 1){ + throw new Exception("Misattribution (entity) can not has more than one person associated. " + misatt.toString()); + }else if(tmpList.size() > 0){ + obj.setPerson(tmpList.get(0)); + } + + tmpList = ot.getSourcesForTargetRelation(misatt, IS_REFERENCE_OF, "REFERENCE", -1); + if(tmpList.size() > 0){ + Entity ref = tmpList.get(0); + if(ref.isLightweight()){ + ref = ot.getEntityByIdWithContent(ref.getId()); + } + obj.setRef(new Reference(ref)); + } + + //this.person = person; + //this.ref = new Reference(ref); + return obj; + } + + public Entity getPerson() { + return person; + } + public void setPerson(Entity person) { + this.person = person; + } + public Reference getRef() { + return ref; + } + public void setRef(Reference ref) { + this.ref = ref; + } + public Entity getMisatt() { + return misatt; + } + public void setMisatt(Entity misatt) { + this.misatt = misatt; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/EndNoteMisattributionTable.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,153 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; + +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Relation; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; +import de.mpiwg.itgroup.ismi.utils.SelectableObject; + +public class EndNoteMisattributionTable extends AbstractISMIBean{ + private static final long serialVersionUID = -2756216426560705499L; + + private List<SelectableObject<EndNoteMisattribution>> list = new ArrayList<SelectableObject<EndNoteMisattribution>>(); + + private EndNoteMisattribution misatt; + + private ListenerObject lo = new ListenerObject(PERSON, "name_translit"); + //private String attName; + //private String oc; + + public EndNoteMisattributionTable(){ + /* + this.attName = attName; + this.oc = oc; + */ + } + + public void listenerRemove(ActionEvent event){ + List<SelectableObject<EndNoteMisattribution>> toDelete = new ArrayList<SelectableObject<EndNoteMisattribution>>(); + + for(SelectableObject<EndNoteMisattribution> so : this.list){ + if(so.isSelected()){ + toDelete.add(so); + } + } + for(SelectableObject<EndNoteMisattribution> so : toDelete){ + this.list.remove(so); + } + } + + public void listenerEditRef(ActionEvent event){ + SelectableObject<EndNoteMisattribution> so = + (SelectableObject<EndNoteMisattribution>)getRequestBean("item"); + if(so != null){ + this.misatt = so.getObj(); + } + } + + public void listenerSaveRef(ActionEvent event){ + this.misatt = null; + } + + public void listenerCancel(ActionEvent event){ + //@TODO + } + + public void listenerCreate(ActionEvent event){ + if(this.lo.entity != null & this.lo.entity.isPersistent()){ + this.create(this.lo.entity); + } + } + + public void load(Entity misattEntity){ + if(!containsEntity(misattEntity)){ + //TODO sort + //Collections.sort(this.misattList); + try { + this.list.add(new SelectableObject<EndNoteMisattribution>(EndNoteMisattribution.load(misattEntity, getWrapper(), getUserName()))); + } catch (Exception e) { + addErrorMsg(e.getMessage()); + e.printStackTrace(); + } + }else{ + addGeneralMsg("This entity has been already inserted!"); + } + } + + public void create(Entity person){ + try { + this.list.add(new SelectableObject<EndNoteMisattribution>(EndNoteMisattribution.create(person, getWrapper(), getUserName()))); + } catch (Exception e) { + addErrorMsg(e.getMessage()); + e.printStackTrace(); + } + } + + private boolean containsEntity(Entity ent){ + for(SelectableObject<EndNoteMisattribution> so : this.list){ + if(so.getObj().getPerson() != null && so.getObj().getPerson().getId().equals(ent.getId())){ + return true; + } + } + return false; + } + + /* + public void listenerChanged(ValueChangeEvent event) { + this.lo = changeListener(event, lo, this.oc, this.attName); + if(lo.entity != null && lo.entity.isPersistent()){ + lo.statusImage.setStatus(StatusImage.STATUS_OK); + }else{ + lo.statusImage.setStatus(StatusImage.STATUS_UNSET); + } + } + */ + + + public Entity saveMisattributions(Entity text) throws Exception{ + for(EndNoteMisattribution misatt : this.getMisattList()){ + text = misatt.saveAndGetMisattribution(text); + } + return text; + } + + + private List<EndNoteMisattribution> getMisattList(){ + List<EndNoteMisattribution> list = new ArrayList<EndNoteMisattribution>(); + for(SelectableObject<EndNoteMisattribution> so : this.list){ + list.add(so.getObj()); + } + return list; + } + + public List<SelectableObject<EndNoteMisattribution>> getList() { + return list; + } + + public void setList(List<SelectableObject<EndNoteMisattribution>> list) { + this.list = list; + } + + public EndNoteMisattribution getMisatt() { + return misatt; + } + + public void setMisatt(EndNoteMisattribution misatt) { + this.misatt = misatt; + } + + public ListenerObject getLo() { + return lo; + } + + public void setLo(ListenerObject lo) { + this.lo = lo; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/EntityList.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,271 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; + +import org.apache.log4j.Logger; +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Node; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; + +public class EntityList extends AbstractISMIBean{ + + private static final long serialVersionUID = -3339006604248018647L; + + private static Logger logger = Logger.getLogger(EntityList.class); + + private List<Entity> entities = new ArrayList<Entity>(); + private Map<Long, Boolean> selections = new HashMap<Long, Boolean>(); + private String title; + + //some relations have an attribute date + private boolean useCalendar; + private Map<Long, Calendar> calendarMap; + + private ListenerObject lo; + + private String input; + private Long id; + + private WrapperService otg; + private String user; + + public EntityList(String oc, String attName, String title){ + this.lo = new ListenerObject(oc, attName); + this.title = title; + } + + public EntityList(String oc, String attName, boolean useCalendar){ + this.lo = new ListenerObject(oc, attName); + this.useCalendar = useCalendar; + this.calendarMap = new HashMap<Long, Calendar>(); + } + + public EntityList(String oc, String attName, WrapperService otg, String user){ + this.lo = new ListenerObject(oc, attName); + this.otg = otg; + this.user = user; + } + + public EntityList(String oc, String attName, WrapperService otg, String user, boolean useCalendar){ + this.lo = new ListenerObject(oc, attName); + this.otg = otg; + this.user = user; + this.useCalendar = useCalendar; + this.calendarMap = new HashMap<Long, Calendar>(); + } + + + public void listenerAddRole(ActionEvent event){ + if(otg != null && isUnique(id)){ + Entity role = otg.getEntityById(id); + if(role != null){ + this.add(role); + } + } + } + + public void listenerCreate(ActionEvent event){ + try { + if(otg != null && isUnique(input)){ + Entity e = new Entity(Node.TYPE_ABOX, lo.getClassObj(), false); + e.setOwnValue(input); + e.addAttribute(new Attribute(this.lo.getAttName(), "text", input)); + otg.saveEntity(e, this.user); + this.add(e); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + e.printStackTrace(); + this.printInternalError(e); + } + } + + public void listenerCreateNoUnique(ActionEvent event){ + try { + if(otg != null ){ + Entity e = new Entity(Node.TYPE_ABOX, lo.getClassObj(), false); + e.setOwnValue(input); + e.addAttribute(new Attribute(this.lo.getAttName(), "text", input)); + otg.saveEntity(e, this.user); + this.add(e); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + e.printStackTrace(); + this.printInternalError(e); + } + } + + private boolean isUnique(Long id){ + for(Entity e : entities){ + if(e.getId().compareTo(id) == 0){ + addErrorMsg("This entity was already selected."); + return false; + } + } + return true; + } + + private boolean isUnique(String input){ + for(Entity e : entities){ + if(e.getOwnValue().equals(input)){ + addErrorMsg("An entity " + lo.getClassObj() + " with name " + input + " exists already."); + return false; + } + } + return true; + } + + public void listenerChanged(ValueChangeEvent event) { + this.lo = changeListener(event, lo, this.lo.getClassObj(), this.lo.getAttName()); + if(lo.entity != null && lo.entity.isPersistent()){ + lo.statusImage.setStatus(StatusImage.STATUS_OK); + }else{ + lo.statusImage.setStatus(StatusImage.STATUS_UNSET); + } + } + + public void listenerAdd(ActionEvent event){ + this.add(this.lo.entity); + } + + public void listenerRemoveSelection(ActionEvent event){ + for(Entity remove : getSelectedEntities()){ + this.remove(remove.getId()); + } + } + + public void add(Entity e){ + if(e != null && e.isPersistent()){ + if(!selections.containsKey(e.getId())){ + this.entities.add(e); + this.selections.put(e.getId(), false); + Collections.sort(this.entities); + if(useCalendar){ + Calendar cal = new Calendar(); + this.calendarMap.put(e.getId(), cal); + } + } + } + } + + public void add(Entity e, Attribute calendarAtt){ + if(e != null && e.isPersistent()){ + if(!selections.containsKey(e.getId())){ + this.entities.add(e); + this.selections.put(e.getId(), false); + Collections.sort(this.entities); + if(useCalendar){ + if(calendarAtt == null){ + this.calendarMap.put(e.getId(), new Calendar()); + }else{ + this.calendarMap.put(e.getId(), AbstractISMIBean.updateCalendar(calendarAtt)); + } + } + } + } + } + + public Calendar getCalendar(Long entId){ + if(calendarMap != null){ + return calendarMap.get(entId); + } + return null; + } + + public void addList(List<Entity> list){ + for(Entity e : list){ + this.add(e); + } + } + + public void remove(Long id){ + this.selections.remove(id); + Entity e = null; + for(Entity ent : entities){ + if(ent.getId().intValue() == id){ + e = ent; + break; + } + } + this.entities.remove(e); + } + + + + private List<Entity> getSelectedEntities(){ + List<Entity> list = new ArrayList<Entity>(); + for(Entity e : entities){ + if(selections.get(e.getId())){ + list.add(e); + } + } + return list; + } + + + public List<Entity> getEntities() { + return entities; + } + public void setEntities(List<Entity> entities) { + this.entities = entities; + } + public Map<Long, Boolean> getSelections() { + return selections; + } + + public void setSelections(Map<Long, Boolean> selections) { + this.selections = selections; + } + + public ListenerObject getLo() { + return lo; + } + + public void setLo(ListenerObject lo) { + this.lo = lo; + } + + public String getInput() { + return input; + } + + public void setInput(String input) { + this.input = input; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Map<Long, Calendar> getCalendarMap() { + return calendarMap; + } + + public void setCalendarMap(Map<Long, Calendar> calendarMap) { + this.calendarMap = calendarMap; + } + + public boolean isUseCalendar() { + return useCalendar; + } + + public String getTitle() { + return title; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/FacesUtils.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,134 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; +import javax.faces.FactoryFinder; +import javax.faces.application.Application; +import javax.faces.application.ApplicationFactory; +import javax.faces.application.FacesMessage; +import javax.faces.context.ExternalContext; +import javax.faces.context.FacesContext; +import javax.faces.el.ValueBinding; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +/** + * JSF utilities. + */ +public class FacesUtils { + /** + * Get servlet context. + * + * @return the servlet context + */ + public static ServletContext getServletContext() { + return (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); + } + + public static ExternalContext getExternalContext() { + FacesContext fc = FacesContext.getCurrentInstance(); + return fc.getExternalContext(); + } + + public static HttpSession getHttpSession(boolean create) { + return (HttpSession) FacesContext.getCurrentInstance(). + getExternalContext().getSession(create); + } + + /** + * Get managed bean based on the bean name. + * + * @param beanName the bean name + * @return the managed bean associated with the bean name + */ + public static Object getManagedBean(String beanName) { + + return getValueBinding(getJsfEl(beanName)).getValue(FacesContext.getCurrentInstance()); + } + + /** + * Remove the managed bean based on the bean name. + * + * @param beanName the bean name of the managed bean to be removed + */ + public static void resetManagedBean(String beanName) { + getValueBinding(getJsfEl(beanName)).setValue(FacesContext.getCurrentInstance(), null); + } + + /** + * Store the managed bean inside the session scope. + * + * @param beanName the name of the managed bean to be stored + * @param managedBean the managed bean to be stored + */ + public static void setManagedBeanInSession(String beanName, Object managedBean) { + FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(beanName, managedBean); + } + + /** + * Get parameter value from request scope. + * + * @param name the name of the parameter + * @return the parameter value + */ + public static String getRequestParameter(String name) { + return (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(name); + } + + /** + * Add information message. + * + * @param msg the information message + */ + public static void addInfoMessage(String msg) { + addInfoMessage(null, msg); + } + + /** + * Add information message to a specific client. + * + * @param clientId the client id + * @param msg the information message + */ + public static void addInfoMessage(String clientId, String msg) { + FacesContext.getCurrentInstance().addMessage(clientId, new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg)); + } + + /** + * Add error message. + * + * @param msg the error message + */ + public static void addErrorMessage(String msg) { + addErrorMessage(null, msg); + } + + /** + * Add error message to a specific client. + * + * @param clientId the client id + * @param msg the error message + */ + public static void addErrorMessage(String clientId, String msg) { + FacesContext.getCurrentInstance().addMessage(clientId, new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg)); + } + + private static Application getApplication() { + ApplicationFactory appFactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); + return appFactory.getApplication(); + } + + private static ValueBinding getValueBinding(String el) { + return getApplication().createValueBinding(el); + } + + private static HttpServletRequest getServletRequest() { + return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); + } + + private static Object getElValue(String el) { + return getValueBinding(el).getValue(FacesContext.getCurrentInstance()); + } + + private static String getJsfEl(String value) { + return "#{" + value + "}"; + } + } \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/HtmlOption.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,59 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +import org.apache.commons.lang.StringUtils; + +public class HtmlOption { + + private String value; + private String label; + private String style; + + public HtmlOption(String value, String label){ + this.value = value; + this.label = label; + } + + public HtmlOption(String value, String label, String style){ + this.value = value; + this.label = label; + this.style = style; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getStyle() { + return style; + } + + public void setStyle(String style) { + this.style = style; + } + + + public String getHtml(){ + StringBuilder sb = new StringBuilder(); + + sb.append("<option value=\""+ value +"\" "); + if(StringUtils.isNotEmpty(style)){ + sb.append("style=\"" + style + "\""); + } + sb.append(">"); + sb.append("</option>"); + + return sb.toString(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/IslamicCalendar.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,315 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +import org.joda.time.DateTime; +import org.joda.time.chrono.GregorianChronology; +import org.joda.time.chrono.IslamicChronology; +import org.joda.time.chrono.JulianChronology; +//rich import com.icesoft.faces.context.effects.Effect; +//rich import com.icesoft.faces.context.effects.Highlight; +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; + +public class IslamicCalendar extends AbstractISMIBean{ + + private static List<SelectItem> suggestedDaysOfMonth = new ArrayList<SelectItem>(); + private static List<SelectItem> suggestedDaysOfWeek = new ArrayList<SelectItem>(); + private static List<SelectItem> suggestedMonths = new ArrayList<SelectItem>(); + + private Integer islamicDayOfMonth; + private Integer islamicDayOfWeek; + private Integer islamicMonthOfYear; + private Integer islamicYear; + + private String islamicStringDate; + private String internalIslamicStringDate; + + private String dateType; + public String internalDateType; + + public boolean islamicDateMalFormed; + + static{ + + suggestedDaysOfWeek = new ArrayList<SelectItem>(); + suggestedDaysOfWeek.add(new SelectItem(new Integer(0), "-- choose --")); + suggestedDaysOfWeek.add(new SelectItem(new Integer(1), "Yawm al-Ithnayn - Monday")); + suggestedDaysOfWeek.add(new SelectItem(new Integer(2), "Yawm ath-Thalaathaa' - Tuesday")); + suggestedDaysOfWeek.add(new SelectItem(new Integer(3), "Yawm al-Arba'aa' - Wednesday")); + suggestedDaysOfWeek.add(new SelectItem(new Integer(4), "Yawm al-Khamis - Thursday")); + suggestedDaysOfWeek.add(new SelectItem(new Integer(5), "Yawm al-Jumu'ah - Friday")); + suggestedDaysOfWeek.add(new SelectItem(new Integer(6), "Yawm as-Sabt - Saturday")); + suggestedDaysOfWeek.add(new SelectItem(new Integer(7), "Yawm al-Ahad - Sunday")); + + + suggestedDaysOfMonth = new ArrayList<SelectItem>(); + suggestedDaysOfMonth.add(new SelectItem(new Integer(0), "-- choose --")); + for(int i=1; i<= 31; i++){ + suggestedDaysOfMonth.add(new SelectItem(new Integer(i), "" + i)); + } + + suggestedMonths = new ArrayList<SelectItem>(); + suggestedMonths.add(new SelectItem(new Integer(0), "-- choose --")); + suggestedMonths.add(new SelectItem(new Integer(1), "1 - Muharram")); + suggestedMonths.add(new SelectItem(new Integer(2), "2 - Safar")); + suggestedMonths.add(new SelectItem(new Integer(3), "3 - Rabi' al-Awwal")); + suggestedMonths.add(new SelectItem(new Integer(4), "4 - Rabi' al-Thani")); + suggestedMonths.add(new SelectItem(new Integer(5), "5 - Jumada al-Ula")); + suggestedMonths.add(new SelectItem(new Integer(6), "6 - Jumada al-Thani")); + suggestedMonths.add(new SelectItem(new Integer(7), "7 - Rajab")); + suggestedMonths.add(new SelectItem(new Integer(8), "8 - Sha'ban")); + suggestedMonths.add(new SelectItem(new Integer(9), "9 - Ramadan")); + suggestedMonths.add(new SelectItem(new Integer(10), "10 - Shawwal")); + suggestedMonths.add(new SelectItem(new Integer(11), "11 - Dhu al-Qa'da")); + suggestedMonths.add(new SelectItem(new Integer(12), "12 - Dhu al-Hijja")); + } + + public IslamicCalendar(){ + this.islamicDayOfWeek = 0; + this.islamicDayOfMonth = 0; + this.islamicMonthOfYear = 0; + this.islamicYear = 1; + } + + public void listenerChangeDateString(ValueChangeEvent event){ + String newValue = (String)event.getNewValue(); + this.internalIslamicStringDate = newValue; + } + + public void listenerChangeDateType(ValueChangeEvent event){ + String newValue = (String)event.getNewValue(); + + if(ApplicationBean.FORMATED_DATE.equals(newValue)){ + if(this.islamicDateMalFormed = this.setIslamicDate(this.islamicStringDate)){ + this.addGeneralMsg("The date in text format can not be converted."); + this.internalDateType = ApplicationBean.PLAIN_DATE; + }else{ + this.internalDateType = ApplicationBean.FORMATED_DATE; + } + }else if(ApplicationBean.PLAIN_DATE.equals(newValue)){ + this.internalDateType = ApplicationBean.PLAIN_DATE; + this.internalIslamicStringDate = getIslamicDateForFormattedWidget(); + } + } + + public void init(String s){ + //this.setIslamicDate(s); + this.internalIslamicStringDate = s; + this.islamicStringDate = s; + this.islamicDateMalFormed = this.setIslamicDate(this.islamicStringDate); + if(this.islamicDateMalFormed){ + this.internalDateType = ApplicationBean.PLAIN_DATE; + }else{ + this.internalDateType = ApplicationBean.FORMATED_DATE; + } + } + + public boolean setIslamicDate(String date){ + try{ + this.islamicStringDate = date; + this.islamicDayOfMonth = 0; + this.islamicMonthOfYear = 0; + this.islamicYear = 1; + this.islamicDayOfWeek = 0; + + if(StringUtils.isNotEmpty(date)){ + String[] list = date.split("\\."); + if(list.length == 1){ + this.islamicYear = new Integer(list[0]); + }else if(list.length == 2){ + this.islamicMonthOfYear = new Integer(list[0]); + this.islamicYear = new Integer(list[1]); + }else if(list.length == 3){ + this.islamicDayOfMonth = new Integer(list[0]); + this.islamicMonthOfYear = new Integer(list[1]); + this.islamicYear = new Integer(list[2]); + }else if(list.length == 4){ + this.islamicDayOfWeek = new Integer(list[0]); + this.islamicDayOfMonth = new Integer(list[1]); + this.islamicMonthOfYear = new Integer(list[2]); + this.islamicYear = new Integer(list[3]); + } + } + }catch(Exception e){ + return true; + } + return false; + } + + public static int getDayOfWeek(String date){ + if(StringUtils.isNotEmpty(date)){ + String[] list = date.split("\\."); + if(list.length == 4){ + return new Integer(list[0]); + } + } + return 0; + } + + public static int getDayOfMonth(String date){ + if(StringUtils.isNotEmpty(date)){ + String[] list = date.split("\\."); + if(list.length == 3){ + return new Integer(list[0]); + } + } + return 0; + } + + public static int getMonthOfYear(String date){ + if(StringUtils.isNotEmpty(date)){ + String[] list = date.split("\\."); + if(list.length == 2){ + return new Integer(list[0]); + }else if(list.length == 3){ + return new Integer(list[1]); + } + } + return 0; + } + + public static int getYear(String date){ + if(StringUtils.isNotEmpty(date)){ + String[] list = date.split("\\."); + if(list.length == 1){ + return new Integer(list[0]); + }else if(list.length == 2){ + return new Integer(list[1]); + }else if(list.length == 3){ + return new Integer(list[2]); + } + } + return 0; + } + + public String getIslamicDate(){ + if(ApplicationBean.PLAIN_DATE.equals(this.getDateType())){ + return getIslamicStringDate(); + } + return getIslamicDateForFormattedWidget(); + } + + public String getIslamicDateForFormattedWidget(){ + return this.islamicDayOfWeek + "." + this.islamicDayOfMonth.toString() + "." + this.islamicMonthOfYear + "." + this.islamicYear; + } + + public String islamic2Gregorian(){ + return islamic2Gregorian(getIslamicYear(), getIslamicMonthOfYear(), getIslamicDayOfMonth(), getIslamicDayOfWeek()); + } + + public String islamic2Julian(){ + return islamic2Julian(getIslamicYear(), getIslamicMonthOfYear(), getIslamicDayOfMonth(), getIslamicDayOfWeek()); + } + + public static String islamic2Gregorian(String date){ + return islamic2Gregorian(getYear(date), getMonthOfYear(date), getDayOfMonth(date), getDayOfWeek(date)); + } + + public static String islamic2Julian(String date){ + return islamic2Julian(getYear(date), getMonthOfYear(date), getDayOfMonth(date), getDayOfWeek(date)); + } + + public static String islamic2Julian(int year, int monthOfYear, int dayOfMonth, int dayOfWeek){ + int validMonthOfYear = (monthOfYear < 1) ? 1 : monthOfYear; + int validDayOfMonth = (dayOfMonth < 1) ? 1 : dayOfMonth; + Integer validDayOfWeek = (dayOfWeek >= 1 && dayOfWeek <= 7) ? dayOfWeek : null; + + DateTime dtIslamic = + new DateTime(year, validMonthOfYear, validDayOfMonth, 0, 0, 0, 0, IslamicChronology.getInstance()); + if(validDayOfWeek != null){ + dtIslamic = dtIslamic.withDayOfWeek(validDayOfWeek); + } + + DateTime dtJulian = dtIslamic.withChronology(JulianChronology.getInstance()); + return dtJulian.getDayOfWeek() + "." + dtJulian.getDayOfMonth() + "." + dtJulian.getMonthOfYear() + "." + dtJulian.getYear(); + } + + public static String islamic2Gregorian(int year, int monthOfYear, int dayOfMonth, int dayOfWeek){ + System.out.println(dayOfWeek + "." + dayOfMonth + "." + monthOfYear + "." + year); + int validMonthOfYear = (monthOfYear < 1) ? 1 : monthOfYear; + int validDayOfMonth = (dayOfMonth < 1) ? 1 : dayOfMonth; + Integer validDayOfWeek = (dayOfWeek >= 1 && dayOfWeek <= 7) ? dayOfWeek : null; + + DateTime dtIslamic = + new DateTime(year, validMonthOfYear, validDayOfMonth, 0, 0, 0, 0, IslamicChronology.getInstance()); + if(validDayOfWeek != null){ + dtIslamic = dtIslamic.withDayOfWeek(validDayOfWeek); + } + + DateTime dtGregorian = dtIslamic.withChronology(GregorianChronology.getInstance()); + + return dtGregorian.getDayOfWeek() + "." + dtGregorian.getDayOfMonth() + "." + dtGregorian.getMonthOfYear() + "." + dtGregorian.getYear(); + } + + public List<SelectItem> getSuggestedDaysOfMonth(){ + return suggestedDaysOfMonth; + } + + public List<SelectItem> getSuggestedMonths(){ + return suggestedMonths; + } + public Integer getIslamicDayOfMonth() { + return islamicDayOfMonth; + } + + public void setIslamicDayOfMonth(Integer islamicDayOfMonth) { + this.islamicDayOfMonth = islamicDayOfMonth; + } + + public Integer getIslamicMonthOfYear() { + return islamicMonthOfYear; + } + + public void setIslamicMonthOfYear(Integer islamicMonthOfYear) { + this.islamicMonthOfYear = islamicMonthOfYear; + } + + public Integer getIslamicYear() { + return islamicYear; + } + + public void setIslamicYear(Integer islamicYear) { + this.islamicYear = islamicYear; + } + + + public List<SelectItem> getSuggestedDaysOfWeek() { + return suggestedDaysOfWeek; + } + + public Integer getIslamicDayOfWeek() { + return islamicDayOfWeek; + } + + public void setIslamicDayOfWeek(Integer islamicDayOfWeek) { + this.islamicDayOfWeek = islamicDayOfWeek; + } + + + public boolean isIslamicDateMalformed() { + return this.islamicDateMalFormed; + } + + public String getIslamicStringDate() { + //return islamicStringDate; + return internalIslamicStringDate; + } + + public void setIslamicStringDate(String islamicStringDate) { + this.islamicStringDate = islamicStringDate; + } + public String getDateType() { + return internalDateType; + //return dateType; + } + + public void setDateType(String dateType) { + this.dateType = dateType; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/MisattributionDataTable.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,164 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; + +import org.mpi.openmind.repository.bo.Entity; +import org.mpiwg.itgroup.escidoc.bo.ESciDocItem; +import org.mpiwg.itgroup.escidoc.utils.ESciDocItemDataTable; + +import de.mpiwg.itgroup.ismi.auxObjects.ListenerObject; +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; + +/** + * TEXT misattributed_to PERSON + * @author jurzua + * + */ +public class MisattributionDataTable extends AbstractISMIBean{ + + private List<TargetMisattribution> misattList = new ArrayList<TargetMisattribution>(); + private Map<Long, Boolean> selectionList = new HashMap<Long, Boolean>(); + + private ListenerObject lo = new ListenerObject(); + private String attName; + private String objectClass; + + private TargetMisattribution currentMisatt; + private ESciDocItemDataTable refDataTable; + + public MisattributionDataTable(String oc, String attName){ + this.attName = attName; + this.objectClass = oc; + this.refDataTable = new ESciDocItemDataTable(this); + } + + public void setESciDocItem(ESciDocItem item){ + if(this.currentMisatt != null){ + this.currentMisatt.setItem(item); + } + } + + public void listenerCloseRefDialog(ActionEvent event){ + this.currentMisatt = null; + this.refDataTable.listenerClose(event); + } + + public void listenerOpenRefDialog(ActionEvent event){ + this.currentMisatt = (TargetMisattribution)getRequestBean("misatt"); + this.refDataTable.listenerOpen(event); + } + + + public void listenerAdd(ActionEvent event){ + this.add(this.lo.entity); + } + + public void listenerRemoveSelection(ActionEvent event){ + for(Entity remove : getSelectedEntities()){ + this.remove(remove.getId()); + } + } + + public void listenerChanged(ValueChangeEvent event) { + this.lo = changeListener(event, lo, this.objectClass, this.attName); + if(lo.entity != null && lo.entity.isPersistent()){ + lo.statusImage.setStatus(StatusImage.STATUS_OK); + }else{ + lo.statusImage.setStatus(StatusImage.STATUS_UNSET); + } + } + + private List<Entity> getSelectedEntities(){ + List<Entity> list = new ArrayList<Entity>(); + for(TargetMisattribution misatt : this.misattList){ + Entity e = misatt.getPerson(); + if(selectionList.get(e.getId())){ + list.add(e); + } + } + return list; + } + + public void add(Entity e){ + if(e != null && e.isPersistent()){ + if(!selectionList.containsKey(e.getId())){ + this.misattList.add(new TargetMisattribution(e, null, null, getAppBean())); + this.selectionList.put(e.getId(), false); + //TODO sort + //Collections.sort(this.misattList); + } + } + } + + public void add(Entity person, String refId, String notes){ + this.misattList.add(new TargetMisattribution(person, refId, notes, getAppBean())); + this.selectionList.put(person.getId(), false); + } + + public void remove(Long id){ + this.selectionList.remove(id); + TargetMisattribution toDelete = null; + for(TargetMisattribution misatt : this.misattList){ + Entity ent = misatt.getPerson(); + if(ent.getId().intValue() == id){ + toDelete = misatt; + break; + } + } + this.misattList.remove(toDelete); + } + + + public List<TargetMisattribution> getMisattList() { + return misattList; + } + + public void setMisattList(List<TargetMisattribution> misattList) { + this.misattList = misattList; + } + + public Map<Long, Boolean> getSelectionList() { + return selectionList; + } + public void setSelectionList(Map<Long, Boolean> selectionList) { + this.selectionList = selectionList; + } + public ListenerObject getLo() { + return lo; + } + public void setLo(ListenerObject lo) { + this.lo = lo; + } + public String getAttName() { + return attName; + } + public void setAttName(String attName) { + this.attName = attName; + } + public String getObjectClass() { + return objectClass; + } + public void setObjectClass(String objectClass) { + this.objectClass = objectClass; + } + public TargetMisattribution getCurrentMisatt() { + return currentMisatt; + } + public void setCurrentMisatt(TargetMisattribution currentMisatt) { + this.currentMisatt = currentMisatt; + } + + public ESciDocItemDataTable getRefDataTable() { + return refDataTable; + } + + public void setRefDataTable(ESciDocItemDataTable refDataTable) { + this.refDataTable = refDataTable; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/Reference.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,183 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +import java.io.Serializable; + +import org.apache.commons.lang.StringUtils; + +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.bo.Node; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; + +public class Reference implements Cloneable, Serializable{ + + /** + * + */ + private static final long serialVersionUID = 8933033295341938974L; + public static String ADD_INFORMATION = "additional_information"; + public static String ESCIDOC_ID = "id"; + public static String ENDNOTE_ID = "endnote-id"; + public static String ENDNOTE_CONTENT = "endnote-content"; + + //public static int EDITION = 0; + //public static int CREATION = 1; + + private Entity ent; + private String endNoteId; + private String endNoteContent; + private String addInformation; + private String escidocId; + //private int mode = CREATION; + + @Override + protected Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + @Override + public boolean equals(Object o){ + + if(o instanceof Reference){ + Reference other = (Reference)o; + if(StringUtils.equals(endNoteId, other.endNoteId) && + StringUtils.equals(endNoteContent, other.endNoteContent) && + StringUtils.equals(addInformation, other.addInformation) && + StringUtils.equals(escidocId, other.escidocId)){ + //@TODO compare entities + return true; + } + } + + return false; + } + + public Reference(Entity ent){ + this.setEnt(ent); + } + + public void setEnt(Entity ent){ + if(ent != null){ + this.ent = ent; + //this.mode = EDITION; + if(ent.containsAttribute(ADD_INFORMATION)){ + this.addInformation = ent.getAttributeByName(ADD_INFORMATION).getValue(); + } + if(ent.containsAttribute(ESCIDOC_ID)){ + this.escidocId = ent.getAttributeByName(ESCIDOC_ID).getValue(); + } + if(ent.containsAttribute(ENDNOTE_ID)){ + this.endNoteId = ent.getAttributeByName(ENDNOTE_ID).getValue(); + } + if(ent.containsAttribute(ENDNOTE_CONTENT)){ + this.endNoteContent = ent.getAttributeByName(ENDNOTE_CONTENT).getValue(); + } + }else{ + //this.mode = CREATION; + } + } + + public boolean isEmpty(){ + if(ent == null && + StringUtils.isEmpty(endNoteId) && + StringUtils.isEmpty(endNoteContent) && + StringUtils.isEmpty(addInformation) && + StringUtils.isEmpty(escidocId)){ + return true; + } + return false; + } + + public Entity getEnt(){ + //xxxx + if(this.ent == null){ + this.ent = new Entity(Node.TYPE_ABOX, AbstractISMIBean.REFERENCE, false); + } + if(!ent.containsAttribute(ADD_INFORMATION)){ + ent.addAttribute(new Attribute(ADD_INFORMATION, "text", this.addInformation)); + } + if(!ent.containsAttribute(ESCIDOC_ID)){ + ent.addAttribute(new Attribute(ESCIDOC_ID, "text", this.escidocId)); + } + if(!ent.containsAttribute(ENDNOTE_ID)){ + ent.addAttribute(new Attribute(ENDNOTE_ID, "text", this.endNoteId)); + } + if(!ent.containsAttribute(ENDNOTE_CONTENT)){ + ent.addAttribute(new Attribute(ENDNOTE_CONTENT, "text", this.endNoteContent)); + } + + //xxxx + if(StringUtils.isNotEmpty(addInformation)){ + ent.getAttributeByName(ADD_INFORMATION).setValue(addInformation); + } + if(StringUtils.isNotEmpty(escidocId)){ + ent.getAttributeByName(ESCIDOC_ID).setValue(escidocId); + } + if(StringUtils.isNotEmpty(endNoteId)){ + ent.getAttributeByName(ENDNOTE_ID).setValue(endNoteId); + } + if(StringUtils.isNotEmpty(endNoteContent)){ + ent.getAttributeByName(ENDNOTE_CONTENT).setValue(endNoteContent); + } + + return ent; + } + + public String getEndNoteId() { + return endNoteId; + } + + public void setEndNoteId(String endNoteId) { + this.endNoteId = endNoteId; + } + + public String getEndNoteContent() { + return endNoteContent; + } + + public void setEndNoteContent(String endNoteContent) { + this.endNoteContent = endNoteContent; + } + + public String getAddInformation() { + return addInformation; + } + + public void setAddInformation(String addInformation) { + this.addInformation = addInformation; + } + + public String getEscidocId() { + return escidocId; + } + + public void setEscidocId(String escidocId) { + this.escidocId = escidocId; + } + + @Override + public String toString(){ + StringBuilder sb = new StringBuilder(); + + sb.append("Reference="); + if(ent != null){ + sb.append(ent.toString() + "\n"); + } + if(StringUtils.isNotEmpty(endNoteId)){ + sb.append(endNoteId + "\n"); + } + if(StringUtils.isNotEmpty(endNoteContent)){ + sb.append(endNoteContent + "\n"); + } + if(StringUtils.isNotEmpty(escidocId)){ + sb.append(escidocId); + } + return sb.toString(); + } + + /* + public int getMode(){ + return mode; + }*/ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/ReferenceTable.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,172 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ActionEvent; + +import org.mpi.openmind.repository.bo.Entity; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractBean; +import de.mpiwg.itgroup.ismi.utils.ISMIUtils; +import de.mpiwg.itgroup.ismi.utils.SelectableObject; + + +public class ReferenceTable extends AbstractBean{ + + private Reference ref; + private Reference originalRef; + + + public List<SelectableObject<Reference>> list = new ArrayList<SelectableObject<Reference>>(); + + public ReferenceTable(){} + + public void loadRefs(List<Entity> refs){ + for(Entity ent : refs){ + this.list.add(new SelectableObject<Reference>(new Reference(ent))); + } + } + + public void listenerEditRef(ActionEvent event){ + SelectableObject<Reference> so = (SelectableObject<Reference>)getRequestBean("item"); + if(so != null && so.getObj() != null){ + this.originalRef = (Reference)so.getObj(); + try { + this.ref = (Reference)this.originalRef.clone(); + } catch (Exception e) { + e.printStackTrace(); + } + + }else{ + addErrorMsg("Problems loading references"); + } + } + + public String actionEditRef(){ + SelectableObject<Reference> so = (SelectableObject<Reference>)getRequestBean("item"); + if(so != null && so.getObj() != null){ + this.originalRef = (Reference)so.getObj(); + try { + this.ref = (Reference)this.originalRef.clone(); + } catch (Exception e) { + e.printStackTrace(); + } + + }else{ + addErrorMsg("Problems loading references"); + } + return new String(); + } + + public void actionListenerSave(ActionEvent event){ + this.save(); + } + + private void save(){ + System.out.println("actionRefSave actionRefSave actionRefSave"); + if(!ref.isEmpty()){ + ref.getEnt(); + if(originalRef != null){ + ISMIUtils.replaceRef(list, originalRef, ref); + }else{ + list.add(new SelectableObject<Reference>(ref)); + } + } + this.ref = null; + this.originalRef = null; + } + + public void listenerRefSave(ActionEvent event){ + if(!ref.isEmpty()){ + ref.getEnt(); + if(originalRef != null){ + ISMIUtils.replaceRef(list, originalRef, ref); + }else{ + list.add(new SelectableObject<Reference>(ref)); + } + } + this.ref = null; + this.originalRef = null; + } + + public void listenerCreateRef(ActionEvent event){ + this.ref = new Reference(null); + this.originalRef = null; + } + + public String actionCreateRef(){ + System.out.println("actionCreateRef"); + this.ref = new Reference(null); + this.originalRef = null; + return new String(""); + } + + public String actionCancel(){ + this.ref = null; + this.originalRef = null; + return new String(); + } + + + public void listenerCancel(ActionEvent event){ + this.ref = null; + this.originalRef = null; + } + + public String actionRemoveRef(){ + System.out.println("actionRemoveRef"); + List<SelectableObject<Reference>> toDelete = new ArrayList<SelectableObject<Reference>>(); + for(SelectableObject<Reference> so : this.list){ + if(so.isSelected()){ + toDelete.add(so); + } + } + for(SelectableObject<Reference> so : toDelete){ + this.list.remove(so); + } + return new String(""); + } + + public void listenerRemoveRef(ActionEvent event){ + List<SelectableObject<Reference>> toDelete = new ArrayList<SelectableObject<Reference>>(); + for(SelectableObject<Reference> so : this.list){ + if(so.isSelected()){ + toDelete.add(so); + } + } + for(SelectableObject<Reference> so : toDelete){ + this.list.remove(so); + } + } + + public Reference getRef() { + return ref; + } + + public void setRef(Reference ref) { + this.ref = ref; + } + + public Reference getOriginalRef() { + return originalRef; + } + + public void setOriginalRef(Reference originalRef) { + this.originalRef = originalRef; + } + + public List<SelectableObject<Reference>> getList() { + return list; + } + + public void setList(List<SelectableObject<Reference>> list) { + this.list = list; + } + + public boolean getHasReferences(){ + if(this.list.isEmpty()) + return false; + return true; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/StatusChecker.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,10 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +public interface StatusChecker { + + public String getStatus(); // uergibt den status, soll sein "ok", "false", "unset". + + public String getMessage(); // message for display + + public void setMessage(String message); // sets the message +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/StatusImage.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,80 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + + +import java.io.Serializable; + +import javax.faces.component.html.HtmlGraphicImage; + +//rich import com.icesoft.faces.component.ext.HtmlGraphicImage; + +public class StatusImage extends HtmlGraphicImage implements StatusChecker{ + + + public static String STATUS_OK = "ok"; + public static String STATUS_UNSET = "unset"; + public static String STATUS_FALSE = "false"; + private static String IMAGEDIR = "/resources/images"; + + private String status = STATUS_UNSET; + + private String message; + + public void setStatus(String status) { + this.status = status; + + if (status=="unset") { + setStatusUnset(); + } else if + (status=="ok") { + setStatusOk(); + } else if (status=="false") { + setStatusFalse(); + } + } + + public boolean isOk(){ + if(STATUS_OK.equals(status)) + return true; + return false; + } + + private void setStatusOk() { + setAlt("ok"); + + setUrl(IMAGEDIR+"/face-smile.png"); + + } + + private void setStatusFalse() { + setAlt("false"); + setUrl(IMAGEDIR+"/dialog-error.png"); + + } + + private void setStatusUnset() { + setAlt("false"); + setUrl(IMAGEDIR+"/dialog-warning.png"); + + } + + public String getStatus() { + return status; + } + + public StatusImage(){ + setStatus("unset"); + setHeight("20"); + setWidth("20"); + } + + public String getMessage() { + + return message; + } + + public void setMessage(String msg){ + message=msg; + } + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/util/guiComponents/TargetMisattribution.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,52 @@ +package de.mpiwg.itgroup.ismi.util.guiComponents; + +import org.mpi.openmind.repository.bo.Entity; +import org.mpiwg.itgroup.escidoc.bo.ESciDocItem; + +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; + +public class TargetMisattribution{ + private Entity person; + //private Publication pub; + private ESciDocItem item; + + public TargetMisattribution(Entity person, String refId, String notes, ApplicationBean appBean){ + this.person = person; + + this.item = appBean.getRefCache().getItem(refId); + if(this.item == null){ + this.item = new ESciDocItem(refId); + this.item.setErrorLoading(ESciDocItem.ESCIDOC_ERROR_ID_NO_FOUND); + } + this.item.getPublication().setAdditionalInformation(notes); + + /* + try{ + this.pub = ESciDocHandler.getPublicationById(refId); + }catch (Exception e) { + System.err.println("The references could not be loaded. The server did not respond."); + } + + if(this.pub == null){ + this.pub = new Publication(refId); + this.pub.setErrorLoading(Publication.ESCIDOC_ERROR_ID_NO_FOUND); + } + this.pub.setAdditionalInformation(notes); + */ + } + + public Entity getPerson() { + return person; + } + public void setPerson(Entity person) { + this.person = person; + } + + public ESciDocItem getItem() { + return item; + } + + public void setItem(ESciDocItem item) { + this.item = item; + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/utils/HTTPUtils.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,177 @@ +package de.mpiwg.itgroup.ismi.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.commons.io.IOUtils; +import org.w3c.dom.Document; + +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + + +public class HTTPUtils { + + + public static Document getDocument(String link){ + try { + Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(link); + return doc; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static String getResponse(String link) throws IOException{ + + URL url = new URL(link); + URLConnection uc = url.openConnection(); + BufferedReader in = new BufferedReader( + new InputStreamReader( + uc.getInputStream())); + String inputLine; + StringBuilder sb = new StringBuilder(); + while ((inputLine = in.readLine()) != null) + sb.append(inputLine); + in.close(); + + return null; + } + + + final static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { + @Override + public void checkClientTrusted( final X509Certificate[] chain, final String authType ) { + } + @Override + public void checkServerTrusted( final X509Certificate[] chain, final String authType ) { + } + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + } }; + + public static HttpResponse getHttpSSLResponse(String link) throws IOException, KeyManagementException, NoSuchAlgorithmException{ + + // Install the all-trusting trust manager + final SSLContext sslContext = SSLContext.getInstance( "SSL" ); + sslContext.init( null, trustAllCerts, new java.security.SecureRandom() ); + // Create an ssl socket factory with our all-trusting manager + final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); + + ///// + + URL url = new URL(link); + HttpURLConnection httpConn = (HttpURLConnection)url.openConnection(); + + ( (HttpsURLConnection) httpConn ).setSSLSocketFactory( sslSocketFactory ); + + + InputStream in; + if (httpConn.getResponseCode() >= 400) { + in = httpConn.getErrorStream(); + } else { + in = httpConn.getInputStream(); + } + + return new HttpResponse(httpConn.getResponseCode(), in); + } + + + public static HttpStringResponse getHttpSSLStringResponse(String link) throws IOException, KeyManagementException, NoSuchAlgorithmException{ + + // Install the all-trusting trust manager + final SSLContext sslContext = SSLContext.getInstance( "SSL" ); + sslContext.init( null, trustAllCerts, new java.security.SecureRandom() ); + // Create an ssl socket factory with our all-trusting manager + final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); + + URL url = new URL(link); + HttpURLConnection httpConn = (HttpURLConnection)url.openConnection(); + + ( (HttpsURLConnection) httpConn ).setSSLSocketFactory( sslSocketFactory ); + + + BufferedReader in = null; + if (httpConn.getResponseCode() >= 400) { + in = new BufferedReader( + new InputStreamReader( + httpConn.getErrorStream())); + } else { + in = new BufferedReader( + new InputStreamReader( + httpConn.getInputStream())); + } + + + String inputLine; + StringBuilder sb = new StringBuilder(); + while ((inputLine = in.readLine()) != null) + sb.append(inputLine + "\n"); + in.close(); + + return new HttpStringResponse(httpConn.getResponseCode(), sb.toString()); + } + + public static HttpStringResponse getHttpStringResponse(String link) throws IOException{ + + //System.out.println(link); + + URL url = new URL(link); + HttpURLConnection httpConn = (HttpURLConnection)url.openConnection(); + + BufferedReader in = null; + if (httpConn.getResponseCode() >= 400) { + in = new BufferedReader( + new InputStreamReader( + httpConn.getErrorStream())); + } else { + in = new BufferedReader( + new InputStreamReader( + httpConn.getInputStream())); + } + + + String inputLine; + StringBuilder sb = new StringBuilder(); + while ((inputLine = in.readLine()) != null) + sb.append(inputLine + "\n"); + in.close(); + + return new HttpStringResponse(httpConn.getResponseCode(), sb.toString()); + } + + public static class HttpStringResponse{ + public int code; + public String content; + public HttpStringResponse(int code, String content){ + this.code = code; + this.content = content; + } + } + + public static class HttpResponse{ + public int code; + public InputStream content; + public HttpResponse(int code, InputStream content){ + this.code = code; + this.content = content; + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/utils/ISMIUtils.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,59 @@ +package de.mpiwg.itgroup.ismi.utils; + +import java.util.List; + +import de.mpiwg.itgroup.ismi.util.guiComponents.Reference; + +public class ISMIUtils { + + public static boolean replaceRef(List<SelectableObject<Reference>> list, Reference old, Reference newRef){ + if(newRef != null){ + for(SelectableObject<Reference> so : list ){ + Reference ref = so.getObj(); + if(ref != null && old.equals(ref)){ + //replacing + so.setObj(newRef); + return true; + } + } + } + //adding in any case + list.add(new SelectableObject<Reference>(newRef)); + return false; + } + + public static boolean listContainsObj(List<SelectableObject<Reference>> list, Object obj){ + if(obj != null){ + for(SelectableObject<Reference> so : list ){ + Reference oInList = so.getObj(); + if(oInList != null && obj.equals(oInList)){ + return true; + } + } + } + return false; + } + + public static boolean removeObjFromList(List<SelectableObject<Reference>> list, Reference obj){ + + if(obj != null){ + for(SelectableObject<Reference> so : list ){ + Reference oInList = so.getObj(); + if(oInList != null && obj.equals(oInList)){ + list.remove(so); + return true; + } + } + } + + return false; + } + + public static boolean add2List(List<SelectableObject<Reference>> list, Reference obj){ + if(!listContainsObj(list, obj)){ + list.add(new SelectableObject<Reference>(obj)); + return true; + } + return false; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/utils/NaturalOrderComparator.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,192 @@ +package de.mpiwg.itgroup.ismi.utils; + +/* +NaturalOrderComparator.java -- Perform 'natural order' comparisons of strings in Java. +Copyright (C) 2003 by Pierre-Luc Paour <natorder@paour.com> + +Based on the C version by Martin Pool, of which this is more or less a straight conversion. +Copyright (C) 2000 by Martin Pool <mbp@humbug.org.au> + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not +claim that you wrote the original software. If you use this software +in a product, an acknowledgment in the product documentation would be +appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be +misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. +*/ + +import java.util.*; + +public class NaturalOrderComparator +{ + private static int compareRight(String a, String b) + { + int bias = 0; + int ia = 0; + int ib = 0; + + // The longest run of digits wins. That aside, the greatest + // value wins, but we can't know that it will until we've scanned + // both numbers to know that they have the same magnitude, so we + // remember it in BIAS. + for (;; ia++, ib++) + { + char ca = charAt(a, ia); + char cb = charAt(b, ib); + + if (!Character.isDigit(ca) && !Character.isDigit(cb)) + { + return bias; + } + else if (!Character.isDigit(ca)) + { + return -1; + } + else if (!Character.isDigit(cb)) + { + return +1; + } + else if (ca < cb) + { + if (bias == 0) + { + bias = -1; + } + } + else if (ca > cb) + { + if (bias == 0) + bias = +1; + } + else if (ca == 0 && cb == 0) + { + return bias; + } + } + } + + + + public static int compare(String a, String b) + { + //String a = o1.toString(); + //String b = o2.toString(); + + int ia = 0, ib = 0; + int nza = 0, nzb = 0; + char ca, cb; + int result; + + while (true) + { + // only count the number of zeroes leading the last number compared + nza = nzb = 0; + + ca = charAt(a, ia); + cb = charAt(b, ib); + + // skip over leading spaces or zeros + while (Character.isSpaceChar(ca) || ca == '0') + { + if (ca == '0') + { + nza++; + } + else + { + // only count consecutive zeroes + nza = 0; + } + + ca = charAt(a, ++ia); + } + + while (Character.isSpaceChar(cb) || cb == '0') + { + if (cb == '0') + { + nzb++; + } + else + { + // only count consecutive zeroes + nzb = 0; + } + + cb = charAt(b, ++ib); + } + + // process run of digits + if (Character.isDigit(ca) && Character.isDigit(cb)) + { + if ((result = compareRight(a.substring(ia), b.substring(ib))) != 0) + { + return result; + } + } + + if (ca == 0 && cb == 0) + { + // The strings compare the same. Perhaps the caller + // will want to call strcmp to break the tie. + return nza - nzb; + } + + if (ca < cb) + { + return -1; + } + else if (ca > cb) + { + return +1; + } + + ++ia; + ++ib; + } + } + + static char charAt(String s, int i) + { + if (i >= s.length()) + { + return 0; + } + else + { + return s.charAt(i); + } + } + + /* + public static void main(String[] args) + { + String[] strings = new String[] { "1-2", "1-02", "1-20", "10-20", "fred", "jane", "pic01", + "pic2", "pic02", "pic02a", "pic3", "pic4", "pic 4 else", "pic 5", "pic05", "pic 5", + "pic 5 something", "pic 6", "pic 7", "pic100", "pic100a", "pic120", "pic121", + "pic02000", "tom", "x2-g8", "x2-y7", "x2-y08", "x8-y8" }; + + List orig = Arrays.asList(strings); + + System.out.println("Original: " + orig); + + List scrambled = Arrays.asList(strings); + Collections.shuffle(scrambled); + + System.out.println("Scrambled: " + scrambled); + + Collections.sort(scrambled, new NaturalOrderComparator()); + + System.out.println("Sorted: " + scrambled); + } + */ +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/utils/SelectItemSort.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,24 @@ +package de.mpiwg.itgroup.ismi.utils; + +import java.util.Comparator; + +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; + +public class SelectItemSort implements Comparator<SelectItem>{ + + public int compare(SelectItem o1, SelectItem o2) { + + if(StringUtils.isNotEmpty(o1.getLabel()) + && StringUtils.isNotEmpty(o2.getLabel())){ + return o1.getLabel().compareTo(o2.getLabel()); + } + + if(StringUtils.isNotEmpty(o1.getLabel())){ + return 1; + }else{ + return -1; + } + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/utils/SelectableObject.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,42 @@ +package de.mpiwg.itgroup.ismi.utils; + +import java.io.Serializable; + +public class SelectableObject<N> implements Serializable{ + + private static final long serialVersionUID = 1L; + + private boolean selected; + private N obj; + private String label; + + public SelectableObject(N obj){ + this.obj = obj; + this.selected = false; + } + + public SelectableObject(N obj, String label){ + this.obj = obj; + this.selected = false; + this.label = label; + } + + public boolean isSelected() { + return selected; + } + public void setSelected(boolean selected) { + this.selected = selected; + } + public N getObj() { + return obj; + } + public void setObj(N obj) { + this.obj = obj; + } + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/utils/templates/AbstractTemplate.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,96 @@ +package de.mpiwg.itgroup.ismi.utils.templates; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpiwg.itgroup.escidoc.ESciDocHandler; +import org.mpiwg.itgroup.escidoc.bo.Publication; + +import de.mpiwg.itgroup.ismi.util.guiComponents.Reference; + +public abstract class AbstractTemplate implements Serializable{ + + private static final long serialVersionUID = -3998660931870870851L; + + + protected List<Entity> refEntityList = new ArrayList<Entity>(); + private List<ReferenceTemplate> referenceList = new ArrayList<AbstractTemplate.ReferenceTemplate>(); + + protected void loadRefernces(){ + try{ + for(Entity ref : refEntityList){ + this.referenceList.add(new ReferenceTemplate(ref)); + } + }catch (Exception e) { + e.printStackTrace(); + } + } + + public class ReferenceTemplate implements Serializable{ + + private static final long serialVersionUID = -8257628538319156038L; + + private String escidocLabel; + private String additionalInf; + private String endnoteId; + private String endnoteContent; + + public ReferenceTemplate(Entity ent){ + + Attribute att = ent.getAttributeByName(Reference.ESCIDOC_ID); + try { + if(att != null && StringUtils.isNotEmpty(att.getValue())){ + Publication pub = ESciDocHandler.getPublicationById(att.getValue()); + if(pub != null){ + this.escidocLabel = pub.getHTMLLabel(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + + this.additionalInf = (ent.getAttributeByName("additional_information") != null) ? ent.getAttributeByName("additional_information").getValue() : null; + this.endnoteId = (ent.getAttributeByName("endnote-id") != null) ? ent.getAttributeByName("endnote-id").getValue() : null; + this.endnoteContent = (ent.getAttributeByName("endnote-content") != null) ? ent.getAttributeByName("endnote-content").getValue() : null; + + } + + public String getEscidocLabel() { + return escidocLabel; + } + public void setEscidocLabel(String escidocLabel) { + this.escidocLabel = escidocLabel; + } + public String getAdditionalInf() { + return additionalInf; + } + public void setAdditionalInf(String additionalInf) { + this.additionalInf = additionalInf; + } + public String getEndnoteId() { + return endnoteId; + } + public void setEndnoteId(String endnoteId) { + this.endnoteId = endnoteId; + } + public String getEndnoteContent() { + return endnoteContent; + } + public void setEndnoteContent(String endnoteContent) { + this.endnoteContent = endnoteContent; + } + } + + public List<ReferenceTemplate> getReferenceList() { + return referenceList; + } + + public void setReferenceList(List<ReferenceTemplate> referenceList) { + this.referenceList = referenceList; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/utils/templates/AuthorTemplate.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,181 @@ +package de.mpiwg.itgroup.ismi.utils.templates; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.mpi.openmind.cache.WrapperService; +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.search.AbstractSearchService; +import org.mpiwg.itgroup.escidoc.ESciDocHandler; +import org.mpiwg.itgroup.escidoc.bo.Publication; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; +import de.mpiwg.itgroup.ismi.util.guiComponents.Calendar; + +public class AuthorTemplate extends AbstractTemplate{ + + private static Logger logger = Logger.getLogger(AuthorTemplate.class); + + private static String birth_date = "birth_date"; + + private static String lived_in = "lived_in"; + private static String has_role = "has_role"; + private static String was_student_of = "was_student_of"; + + public String privacity; + public String name; + public String nameTranslit; + public String bornInPlace; + public String diedInPlace; + public String primeAlias; + public String notes; + public String url; + public List<String> aliasList; + public List<String> roleList; + + public String birthDate; + public String deathDate; + + public Map<String, String> livedInPlaceMap; + + public AuthorTemplate(Entity entity, WrapperService om){ + + logger.info("Diplaying " + entity); + + if (entity.isLightweight()) { + entity = om.getEntityContent(entity); + } + this.aliasList = new ArrayList<String>(); + this.roleList = new ArrayList<String>(); + this.livedInPlaceMap = new HashMap<String, String>(); + this.privacity = entity.getPrivacity(); + + Attribute attName = entity.getAttributeByName("name"); + Attribute attNameTranslit = entity.getAttributeByName("name_translit"); + Attribute attNotes = entity.getAttributeByName("notes"); + Attribute attUrl = entity.getAttributeByName("url"); + this.name = (attName == null) ? null : attName.getValue(); + this.nameTranslit = (attNameTranslit == null) ? null : attNameTranslit.getValue(); + this.notes = (attNotes == null) ? null : attNotes.getValue(); + this.url = (attUrl == null) ? null : attUrl.getValue(); + + Calendar calDeathDate = AbstractISMIBean.updateCalendar(entity.getAttributeByName("death_date")); + this.deathDate = calDeathDate.getCalendarAsHtml(); + + Calendar calBirthDate = AbstractISMIBean.updateCalendar(entity.getAttributeByName(birth_date)); + this.birthDate = calBirthDate.getCalendarAsHtml(); + + //this.setCurrentId(entity.getId().toString()); + //this.loadAttributes(entity); + + for (Relation rel : entity.getSourceRelations()) { + if(StringUtils.isEmpty(rel.getOwnValue()) || StringUtils.isEmpty(rel.getTargetObjectClass())){ + try { + throw new Exception("Relation has no ownValue and/or targetObjCls " + rel); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + }else{ + Entity target = om.getEntityById(rel.getTargetId()); + if (rel.getOwnValue().equals("was_born_in")) { + this.bornInPlace = (target == null) ? "" : target.getOwnValue(); + } else if (rel.getOwnValue().equals(lived_in)) { + String date = (rel.getAttributeByName("date") != null) ? + new Calendar(rel.getAttributeByName("date").getOwnValue()).getCalendarAsHtml() : + ""; + this.livedInPlaceMap.put(target.getOwnValue(), date); + } else if (rel.getOwnValue().equals(was_student_of)) { + //this.studentOfList.add(target); + } else if (rel.getOwnValue().equals(has_role)) { + this.roleList.add(target.getOwnValue()); + } else if (rel.getOwnValue().equals("died_in")) { + this.diedInPlace = (target == null) ? "" : target.getOwnValue(); + } + } + } + + for (Relation rel : entity.getTargetRelations()) { + + if(StringUtils.isEmpty(rel.getOwnValue()) || StringUtils.isEmpty(rel.getSourceObjectClass())){ + try { + throw new Exception("Relation has no ownValue and/or sourceObjCls " + rel); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + }else{ + if (rel.getOwnValue().equals("was_created_by") && rel.getSourceObjectClass().equals("TEXT")) { + Entity title = om.getEntityById(rel.getSourceId()); + if(title != null && title.getObjectClass().equals("TEXT")){ + //this.titles.add(title); + //I remove this line cause the list in this way would not be sorted. + //this.titleItems.add(new SelectItem(title.getId().toString(), title.getOwnValue() + " [" + title.getId() + "]")); + } + } else if (rel.getOwnValue().equals("is_alias_name_of")) { + Entity alias = om.getEntityById(rel.getSourceId()); + this.aliasList.add(alias.getOwnValue()); + } else if (rel.getOwnValue().equals("is_prime_alias_name_of")) { + Entity alias = om.getEntityByIdWithContent(rel.getSourceId()); + this.primeAlias = alias.getAttributeByName("alias").getValue(); + } else if (rel.getOwnValue().equals("is_reference_of")) { + Entity ref = om.getEntityByIdWithContent(rel.getSourceId()); + this.refEntityList.add(ref); + } + } + + } + this.loadRefernces(); + } + + public String getPrivacity() { + return privacity; + } + public String getName() { + return name; + } + public String getNameTranslit() { + return nameTranslit; + } + public String getBornInPlace() { + return bornInPlace; + } + public String getDiedInPlace() { + return diedInPlace; + } + public String getPrimeAlias() { + return primeAlias; + } + public String getNotes() { + return notes; + } + public String getUrl() { + return url; + } + public List<String> getAliasList() { + return aliasList; + } + + public String getBirthDate() { + return birthDate; + } + public String getDeathDate() { + return deathDate; + } + public List<String> getRoleList() { + return roleList; + } + + public Map<String, String> getLivedInPlaceMap() { + return livedInPlaceMap; + } + + public Collection<String> getLivedInPlaceList(){ + return livedInPlaceMap.keySet(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/utils/templates/CodexTemplate.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,81 @@ +package de.mpiwg.itgroup.ismi.utils.templates; + +import java.util.List; + +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; + +public class CodexTemplate { + + public Long id; + public String ov; + public String identifier; + public String mpiwgId; + public String indexmetaFolder; + public String collection; + public String repository; + public String city; + public String country; + + public CodexTemplate(Entity entity, WrapperService om) { + this.id = entity.getId(); + this.ov = entity.getOwnValue(); + + Attribute tmp = om.getAttributeByName(entity.getId(), "identifier"); + this.identifier = (tmp != null) ? tmp.getValue() : null; + + tmp = om.getAttributeByName(entity.getId(), "mpiwg_id"); + this.mpiwgId = (tmp != null) ? tmp.getValue() : null; + + tmp = om.getAttributeByName(entity.getId(), "indexmeta_folder"); + this.indexmetaFolder = (tmp != null) ? tmp.getValue() : null; + + List<Entity> list = om.getTargetsForSourceRelation(entity.getId(), "is_part_of", "COLLECTION", 1); + if(list.size() > 0){ + this.collection = list.get(0).getOwnValue(); + list = om.getTargetsForSourceRelation(list.get(0).getId(), "is_part_of", "REPOSITORY", 1); + if(list.size() > 0){ + this.repository = list.get(0).getOwnValue(); + list = om.getTargetsForSourceRelation(list.get(0).getId(), "is_in", "PLACE", 1); + if(list.size() > 0){ + this.city = list.get(0).getOwnValue(); + list = om.getTargetsForSourceRelation(list.get(0).getId(), "is_part_of", "PLACE", 1); + if(list.size() > 0){ + this.country = list.get(0).getOwnValue(); + } + } + } + } + } + + public Long getId(){ + return this.id; + } + + public String getOv(){ + return this.ov; + } + + public String getIdentifier() { + return identifier; + } + + public String getCollection() { + return collection; + } + + public String getRepository() { + return repository; + } + + public String getCity() { + return city; + } + + public String getCountry() { + return country; + } + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/utils/templates/DigitalizationTemplate.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,73 @@ +package de.mpiwg.itgroup.ismi.utils.templates; + +import java.util.List; + +import org.mpi.openmind.cache.WrapperService; +import org.mpi.openmind.repository.bo.Entity; + +public class DigitalizationTemplate implements Comparable<DigitalizationTemplate>{ + + private String codexOv; + private String codexId; + private Entity entity; + private String pages; + private List<Entity> titlesInCodex; + + private WrapperService om; + private boolean initialized = false; + + private boolean hasCodex = false; + + public DigitalizationTemplate(Entity digi, WrapperService om){ + this.entity = digi; + this.om = om; + } + + public void init(){ + this.initialized = true; + this.pages = om.getAttributeByName(entity.getId(), "num_files").getValue(); + + List<Entity> list = om.getTargetsForSourceRelation(entity, "is_digitalization_of", "CODEX", 1); + if(list.size() > 0){ + Entity codex = list.get(0); + this.codexOv = codex.getOwnValue(); + this.codexId = codex.getId().toString(); + this.titlesInCodex = om.getSourcesForTargetRelation(codex, "is_part_of", "WITNESS", -1); + this.hasCodex = true; + } + } + + public boolean isHasCodex(){ + return this.hasCodex; + } + + public String getCodexId() { + if(!initialized) + this.init(); + return codexId; + } + + public Entity getEntity() { + return entity; + } + + public String getCodexOv(){ + return this.codexOv; + } + + public String getPages() { + if(!initialized) + this.init(); + return pages; + } + + public List<Entity> getTitlesInCodex() { + if(!initialized) + this.init(); + return titlesInCodex; + } + + public int compareTo(DigitalizationTemplate o) { + return this.entity.getOwnValue().compareTo(o.getEntity().getOwnValue()); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/utils/templates/TitleTemplate.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,204 @@ +package de.mpiwg.itgroup.ismi.utils.templates; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.log4j.Logger; +import org.mpi.openmind.cache.WrapperService; +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.utils.RomanizationLoC; + +import de.mpiwg.itgroup.ismi.util.guiComponents.Calendar; + +public class TitleTemplate extends AbstractTemplate{ + + private static Logger logger = Logger.getLogger(TitleTemplate.class); + + public String ov; + public String privacity; + public String fullTitle; + public String fullTitleTranslit; + public String language; + public String notes; + public String category; + public String createIn; + public String incipit; + public String explicit; + public String dedication; + public String tableOfContents; + public String author; + public Long authorId; + //extra + public List<String> aliasList; + public List<String> authorMisattributionList; + public String personDedicatedTo; + public String commentaryOnText; + public String translationOfText; + public String versionOfText; + + + public String creationDate; + + public TitleTemplate(Entity entity, WrapperService om, boolean useRomanization){ + + //logger.info("Diplaying " + entity); + + this.aliasList = new ArrayList<String>(); + this.authorMisattributionList = new ArrayList<String>(); + + if(entity != null){ + + this.privacity = entity.getPrivacity(); + + //attributes + Attribute att = om.getAttributeByName(entity.getId(), "full_title"); + this.fullTitle = (att != null) ? att.getOwnValue() : null; + this.fullTitle = (useRomanization) ? RomanizationLoC.convert(fullTitle) : fullTitle; + + att = om.getAttributeByName(entity.getId(), "full_title_translit"); + this.fullTitleTranslit = (att != null) ? att.getOwnValue() : null; + this.fullTitleTranslit = (useRomanization) ? RomanizationLoC.convert(fullTitleTranslit) : fullTitleTranslit; + + att = om.getAttributeByName(entity.getId(), "creation_date"); + if(att != null){ + Calendar creationDate = new Calendar(att.getOwnValue()); + this.creationDate = creationDate.getCalendarAsHtml(); + } + + att = om.getAttributeByName(entity.getId(), "language"); + this.language = (att != null) ? att.getOwnValue() : null; + + att = om.getAttributeByName(entity.getId(), "notes"); + this.notes = (att != null) ? att.getOwnValue() : null; + + att = om.getAttributeByName(entity.getId(), "incipit"); + this.incipit = (att != null) ? att.getOwnValue() : null; + + att = om.getAttributeByName(entity.getId(), "explicit"); + this.explicit = (att != null) ? att.getOwnValue() : null; + + att = om.getAttributeByName(entity.getId(), "dedication"); + this.dedication = (att != null) ? att.getOwnValue() : null; + + att = om.getAttributeByName(entity.getId(), "table_of_contents"); + this.tableOfContents = (att != null) ? att.getOwnValue() : null; + + List<Entity> tarList = om.getTargetsForSourceRelation(entity.getId(), "has_subject", "SUBJECT", 1); + this.category = (tarList.size() > 0) ? tarList.get(0).getOwnValue() : null ; + + tarList = om.getTargetsForSourceRelation(entity.getId(), "was_created_in", "PLACE", 1); + this.createIn = (tarList.size() > 0) ? tarList.get(0).getOwnValue() : null ; + + List<Entity> list0 = om.getSourcesForTargetRelation(entity.getId(), "is_reference_of", "REFERENCE", -1); + for(Entity ref : list0){ + this.refEntityList.add(om.getEntityContent(ref)); + } + + + + list0 = om.getTargetsForSourceRelation(entity.getId(), "was_created_by", "PERSON", -1); + if(list0.size() > 0){ + this.author = list0.get(0).getOwnValue(); + this.author = (useRomanization) ? RomanizationLoC.convert(author) : author; + this.authorId = list0.get(0).getId(); + } + + //extra fields ... + + list0 = om.getSourcesForTargetRelation(entity, "is_alias_title_of", "ALIAS", -1); + for(Entity alias : list0){ + this.aliasList.add(alias.getOwnValue()); + } + + list0 = om.getTargetsForSourceRelation(entity, "has_author_misattribution", "MISATTRIBUTION", -1); + for(Entity misatt : list0){ + List<Entity> authorMissattList = om.getTargetsForSourceRelation(misatt, "misattributed_to", "PERSON", 1); + if(authorMissattList.size() == 1){ + String authorMiss = authorMissattList.get(0).getOwnValue(); + authorMiss = (useRomanization) ? RomanizationLoC.convert(authorMiss) : authorMiss; + this.authorMisattributionList.add(authorMiss); + } + } + + list0 = om.getTargetsForSourceRelation(entity, "was_dedicated_to", "PERSON", 1); + this.personDedicatedTo = (list0.size() == 1) ? list0.get(0).getOwnValue() : null; + this.personDedicatedTo = (useRomanization) ? RomanizationLoC.convert(personDedicatedTo) : personDedicatedTo; + + list0 = om.getTargetsForSourceRelation(entity, "is_commentary_on", "TEXT", 1); + this.commentaryOnText = (list0.size() == 1) ? list0.get(0).getOwnValue() : null; + this.commentaryOnText = (useRomanization) ? RomanizationLoC.convert(commentaryOnText) : commentaryOnText; + + list0 = om.getTargetsForSourceRelation(entity, "is_translation_of", "TEXT", 1); + this.translationOfText = (list0.size() == 1) ? list0.get(0).getOwnValue() : null; + this.translationOfText = (useRomanization) ? RomanizationLoC.convert(translationOfText) : translationOfText; + + list0 = om.getTargetsForSourceRelation(entity, "is_version_of", "TEXT", 1); + this.versionOfText = (list0.size() == 1) ? list0.get(0).getOwnValue() : null; + this.versionOfText = (useRomanization) ? RomanizationLoC.convert(versionOfText) : versionOfText; + } + + this.loadRefernces(); + + } + + public String getOv() { + return ov; + } + public String getPrivacity() { + return privacity; + } + public String getFullTitle() { + return fullTitle; + } + public String getFullTitleTranslit() { + return fullTitleTranslit; + } + public String getLanguage() { + return language; + } + public String getNotes() { + return notes; + } + public String getCategory() { + return category; + } + public String getCreateIn() { + return createIn; + } + public String getIncipit() { + return incipit; + } + public String getExplicit() { + return explicit; + } + public String getDedication() { + return dedication; + } + public String getTableOfContents() { + return tableOfContents; + } + public List<String> getAliasList() { + return aliasList; + } + public String getCreationDate() { + return creationDate; + } + public String getAuthor() { + return author; + } + public Long getAuthorId() { + return authorId; + } + + public boolean getHasAuthor(){ + return this.authorId != null; + } + + public List<String> getAuthorMisattributionList() { + return authorMisattributionList; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/itgroup/ismi/utils/templates/WitnessTemplate.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,454 @@ +package de.mpiwg.itgroup.ismi.utils.templates; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.mpi.openmind.cache.WrapperService; +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.PersistenceService; +import org.mpi.openmind.repository.utils.RomanizationLoC; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; +import de.mpiwg.itgroup.ismi.entry.beans.ApplicationBean; +import de.mpiwg.itgroup.ismi.util.guiComponents.Calendar; +import de.mpiwg.itgroup.ismi.utils.NaturalOrderComparator; + +public class WitnessTemplate extends AbstractTemplate implements + Comparable<WitnessTemplate> { + + private static final long serialVersionUID = -8829977715724255324L; + + private static Logger logger = Logger.getLogger(WitnessTemplate.class); + + public String privacity; + public Long id; + public String ov; + public String title; + public Long titleId; + public String startPage; + public String endPage; + public String status; + public String tableOfContents; + public String notesOnTitleAuthor; + public String notesOnCollationAndCorrections; + public String notesOnOwnership; + public String notes; + public String codex; + public String collection; + public String repository; + public String city; + public String country; + public String folios; + public String ahlwardtNo; + public String colophon; + + public String incipit; + public String explicit; + public String subject; + + // public List<String> referenceList; + public Map<String, String> ownedByMap; + public Map<String, String> readByMap; + + //extras fields used by the json interface + public String titleAsWrittenInWitness; + public String authorAsWrittenInWitness; + public String copyist; + public String placeOfCopying; + + public String page_dimensions; + public String written_area_dimensions; + public String lines_per_page; + public String page_layout; + public String script; + public String writing_surface; + public List<String> wasStudiedByList; + public String fullTitle; + public String fullTitleTranslit; + public String authorName; + public String authorNameTranslit; + public String creationDate; + + public boolean useRomanization = false; + + public boolean isUnknown() { + return StringUtils.equals("UNKNOWN", this.title); + } + + public WitnessTemplate(Entity witness, WrapperService om, boolean useRomanization) { + this.init(witness, om, false, useRomanization); + } + + public WitnessTemplate(Entity witness, WrapperService om, boolean extended, boolean useRomanization) { + this.init(witness, om, extended, useRomanization); + } + + private void init(Entity witness, WrapperService om, boolean extended, boolean useRomanization) { + // this.referenceList = new ArrayList<String>(); + this.ownedByMap = new HashMap<String, String>(); + this.readByMap = new HashMap<String, String>(); + this.wasStudiedByList = new ArrayList<String>(); + + this.useRomanization = useRomanization; + + try { + if (witness != null) { + this.privacity = witness.getPrivacity(); + + this.id = witness.getId(); + this.ov = (useRomanization) ? RomanizationLoC.convert(witness.getOwnValue()) : witness.getOwnValue(); + + if (StringUtils.isEmpty(witness.getStatus())) { + this.status = ApplicationBean.STATUS_NOT_CHECKED; + } else { + this.status = witness.getStatus(); + } + + Attribute att0 = om.getAttributeByName(witness.getId(), "start_page"); + this.startPage = (att0 != null) ? att0.getValue() : null; + + att0 = om.getAttributeByName(witness.getId(), + "end_page"); + this.endPage = (att0 != null) ? att0.getValue() : null; + + att0 = om.getAttributeByName(witness.getId(), + "folios"); + this.folios = (att0 != null) ? att0.getValue() : null; + + att0 = om.getAttributeByName(witness.getId(), + "ahlwardt_no"); + this.ahlwardtNo = (att0 != null) ? att0.getValue() : null; + + att0 = om.getAttributeByName(witness.getId(), "colophon"); + this.colophon = (att0 != null) ? att0.getValue() : null; + + att0 = om.getAttributeByName(witness.getId(), "page_dimensions"); + this.page_dimensions = (att0 != null) ? att0.getValue() : null; + + att0 = om.getAttributeByName(witness.getId(), "written_area_dimensions"); + this.written_area_dimensions = (att0 != null) ? att0.getValue() : null; + + att0 = om.getAttributeByName(witness.getId(), "lines_per_page"); + this.lines_per_page = (att0 != null) ? att0.getValue() : null; + + att0 = om.getAttributeByName(witness.getId(), "page_layout"); + this.page_layout = (att0 != null) ? att0.getValue() : null; + + att0 = om.getAttributeByName(witness.getId(), "script"); + this.script = (att0 != null) ? att0.getValue() : null; + + att0 = om.getAttributeByName(witness.getId(), "writing_surface"); + this.writing_surface = (att0 != null) ? att0.getValue() : null; + + att0 = om.getAttributeByName(witness.getId(), "creation_date"); + Calendar creationDate0 = AbstractISMIBean.updateCalendar(att0); + this.creationDate = creationDate0.getCalendarAsHtml(); + + if(extended){ + Attribute incipit = om.getAttributeByName(witness.getId(), + "incipit"); + this.incipit = (incipit != null) ? incipit.getValue() : null; + + Attribute explicit = om.getAttributeByName(witness.getId(), + "explicit"); + this.explicit = (explicit != null) ? explicit.getValue() : null; + } + + Attribute table_of_contents = om.getAttributeByName( + witness.getId(), "table_of_contents"); + this.tableOfContents = (table_of_contents != null) ? table_of_contents + .getValue() : null; + + Attribute notes_on_title_author = om.getAttributeByName( + witness.getId(), "notes_on_title_author"); + if (notes_on_title_author != null) { + this.notesOnTitleAuthor = notes_on_title_author.getValue(); + } + + Attribute notes_on_collation_and_corrections = om + .getAttributeByName(witness.getId(), + "notes_on_collation_and_corrections"); + if (notes_on_collation_and_corrections != null) { + this.notesOnCollationAndCorrections = notes_on_collation_and_corrections + .getValue(); + } + + Attribute notes_on_ownership = om.getAttributeByName( + witness.getId(), "notes_on_ownership"); + if (notes_on_ownership != null) { + this.notesOnOwnership = notes_on_ownership.getValue(); + } + + att0 = om.getAttributeByName(witness.getId(), "notes"); + this.notes = (att0 != null) ? att0.getValue() : null; + + List<Entity> list0 = om.getTargetsForSourceRelation(witness.getId(), "is_exemplar_of", "TEXT", 1); + if (list0.size() > 0) { + this.title = (useRomanization) ? RomanizationLoC.convert(list0.get(0).getOwnValue()) : list0.get(0).getOwnValue(); + this.titleId = list0.get(0).getId(); + att0 = om.getAttributeByName(titleId, "full_title"); + this.fullTitle = (att0 != null) ? att0.getOwnValue() : null; + this.fullTitle = (useRomanization) ? RomanizationLoC.convert(fullTitle) : fullTitle; + + att0 = om.getAttributeByName(titleId, "full_title_translit"); + if(att0 != null){ + this.fullTitleTranslit = (useRomanization) ? RomanizationLoC.convert(att0.getOwnValue()) : att0.getOwnValue(); + } + + List<Entity> list1 = om.getTargetsForSourceRelation(this.titleId, "was_created_by", "PERSON", 1); + if(list1.size() > 0){ + Entity author = list1.get(0); + att0 = om.getAttributeByName(author.getId(), "name"); + this.authorName = (att0 == null) ? null : att0.getValue(); + this.authorName = (useRomanization) ? RomanizationLoC.convert(authorName) : authorName; + att0 = om.getAttributeByName(author.getId(), "name_translit"); + if(att0 != null){ + this.authorNameTranslit = (useRomanization) ? RomanizationLoC.convert(att0.getValue()) : att0.getValue(); + } + } + + if(extended){ + //Attribute subject = om.getAttributeByName(witness.getId(), "subject"); + list0 = om.getTargetsForSourceRelation(this.titleId, "has_subject", "SUBJECT", 1); + this.subject = (!list0.isEmpty()) ? list0.get(0).getOwnValue() : null; + + } + } + + list0 = om.getTargetsForSourceRelation(witness, "has_author_written_as", "ALIAS", 1); + if(list0.size() > 0){ + this.authorAsWrittenInWitness = (useRomanization) ? RomanizationLoC.convert(list0.get(0).getOwnValue()) : list0.get(0).getOwnValue(); + } + + list0 = om.getTargetsForSourceRelation(witness, "has_title_written_as", "ALIAS", 1); + if(list0.size() > 0){ + this.titleAsWrittenInWitness = (useRomanization) ? RomanizationLoC.convert(list0.get(0).getOwnValue()) : list0.get(0).getOwnValue(); + } + + list0 = om.getTargetsForSourceRelation(witness, "was_copied_by", "PERSON", 1); + if(list0.size() > 0){ + this.copyist = (useRomanization) ? RomanizationLoC.convert(list0.get(0).getOwnValue()) : list0.get(0).getOwnValue(); + } + + list0 = om.getTargetsForSourceRelation(witness, "was_copied_in", "PLACE", 1); + this.placeOfCopying = (list0.size() > 0) ? list0.get(0).getOwnValue() : null; + + + list0 = om.getTargetsForSourceRelation(witness, "was_studied_by", "PERSON", 1); + for(Entity ent : list0){ + this.wasStudiedByList.add((useRomanization) ? RomanizationLoC.convert(ent.getOwnValue()) : ent.getOwnValue()); + } + + List<Entity> list = om.getTargetsForSourceRelation( + witness.getId(), "is_part_of", "CODEX", 1); + if (list.size() > 0) { + Entity codex = list.get(0); + + Attribute att = om.getAttributeByName(codex.getId(), + "identifier"); + if (att != null && StringUtils.isNotEmpty(att.getValue())) { + this.codex = att.getValue(); + } + + for (Relation rel : om.getSourceRelations(codex, + "owned_by", "PERSON", -1)) { + String date = (rel.getAttributeByName("date") != null) ? new Calendar( + rel.getAttributeByName("date").getOwnValue()) + .getCalendarAsHtml() : ""; + String ov = om.getEntityById(rel.getTargetId()).getOwnValue(); + String ownedLabel = (useRomanization) ? RomanizationLoC.convert(ov) : ov; + this.ownedByMap.put(ownedLabel, date); + } + + for (Relation rel : om.getSourceRelations(codex, "read_by", + "PERSON", -1)) { + String date = (rel.getAttributeByName("date") != null) ? new Calendar( + rel.getAttributeByName("date").getOwnValue()) + .getCalendarAsHtml() : ""; + String ov = om.getEntityById(rel.getTargetId()).getOwnValue(); + String readerLabel = (useRomanization) ? RomanizationLoC.convert(ov) : ov; + this.readByMap.put(readerLabel, date); + } + + list = om.getTargetsForSourceRelation(codex.getId(), + "is_part_of", "COLLECTION", 1); + if (list.size() > 0) { + Entity collection = list.get(0); + this.collection = collection.getOwnValue(); + + list = om.getTargetsForSourceRelation( + collection.getId(), "is_part_of", "REPOSITORY", + 1); + + if (list.size() > 0) { + Entity repository = list.get(0); + this.repository = repository.getOwnValue(); + + list = om.getTargetsForSourceRelation( + repository.getId(), "is_in", "PLACE", 1); + + if (list.size() > 0) { + Entity city = list.get(0); + this.city = city.getOwnValue(); + + list = om.getTargetsForSourceRelation( + city.getId(), "is_part_of", "PLACE", 1); + if (list.size() > 0) { + Entity country = list.get(0); + this.country = country.getOwnValue(); + } + } + } + } + } + + list0 = om.getSourcesForTargetRelation(witness, + "is_reference_of", "REFERENCE", -1); + for (Entity ref : list0) { + System.out.println("### REF= " + ref.getId()); + this.refEntityList.add(om.getEntityContent(ref)); + } + } + + this.loadRefernces(); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + } + + public String getPrivacity() { + return privacity; + } + + public String getStatus() { + return status; + } + + public String getTableOfContents() { + return tableOfContents; + } + + public String getNotesOnTitleAuthor() { + return notesOnTitleAuthor; + } + + public String getNotesOnCollationAndCorrections() { + return notesOnCollationAndCorrections; + } + + public String getNotesOnOwnership() { + return notesOnOwnership; + } + + public String getNotes() { + return notes; + } + + public String getCodex() { + return codex; + } + + public String getCollection() { + return collection; + } + + public String getRepository() { + return repository; + } + + public String getCity() { + return city; + } + + public String getCountry() { + return country; + } + + /* + * public List<String> getReferenceList() { return referenceList; } + */ + + public Map<String, String> getOwnedByMap() { + return ownedByMap; + } + + public Map<String, String> getReadByMap() { + return readByMap; + } + + public Collection<String> getOwnedByList() { + return ownedByMap.keySet(); + } + + public Collection<String> getReadByList() { + return readByMap.keySet(); + } + + public static Logger getLogger() { + return logger; + } + + public String getStartPage() { + return startPage; + } + + public String getEndPage() { + return endPage; + } + + public Long getId() { + return id; + } + + public String getOv() { + return ov; + } + + public String getTitle() { + return this.title; + } + + public Long getTitleId() { + return this.titleId; + } + + public String getFolios() { + return this.folios; + } + + public boolean hasTitle(){ + return this.titleId != null; + } + + // 40b-49b + // 104b-111b + public int compareTo(WitnessTemplate other) { + // return this.empId - o.empId ; + + if (other == null) + return -1; + if (StringUtils.isEmpty(this.folios) + && StringUtils.isEmpty(other.folios)) + return this.title.compareTo(other.title); + if (StringUtils.isEmpty(this.folios)) + return 1; + if (StringUtils.isEmpty(other.folios)) + return -1; + + try { + return NaturalOrderComparator.compare(this.folios, other.folios); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + + return 0; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/javax/faces/model/SelectItem.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,373 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package javax.faces.model; + + +import java.io.Serializable; +import javax.faces.component.UISelectMany; +import javax.faces.component.UISelectOne; + + +/** + * <p><strong class="changed_modified_2_0 + * changed_modified_2_0_rev_a">SelectItem</strong> represents a single + * <em>item</em> in the list of supported <em>items</em> associated with + * a {@link UISelectMany} or {@link UISelectOne} component.</p> + */ + +public class SelectItem implements Serializable { + + private static final long serialVersionUID = 876782311414654999L; + + + // ------------------------------------------------------------ Constructors + + + /** + * <p>Construct a <code>SelectItem</code> with no initialized property + * values.</p> + */ + public SelectItem() { + + super(); + + } + + + /** + * <p>Construct a <code>SelectItem</code> with the specified value. The + * <code>label</code> property will be set to the value (converted to a + * String, if necessary), the <code>description</code> property will be + * set to <code>null</code>, the <code>disabled</code> property will be set to + * <code>false</code>, and the <code>escape</code> property will be set to + ( <code>true</code>.</p> + * + * @param value Value to be delivered to the model if this + * item is selected by the user + */ + public SelectItem(Object value) { + + this(value, value == null ? null : value.toString(), null, false, true, false); + + } + + + /** + * <p>Construct a <code>SelectItem</code> with the specified value and + * label. The <code>description</code> property will be set to + * <code>null</code>, the <code>disabled</code> property will be + * set to <code>false</code>, and the <code>escape</code> property will + * be set to <code>true</code>.</p> + * + * @param value Value to be delivered to the model if this + * item is selected by the user + * @param label Label to be rendered for this item in the response + */ + public SelectItem(Object value, String label) { + + this(value, label, null, false, true, false); + + } + + + /** + * <p>Construct a <code>SelectItem</code> instance with the specified + * value, label and description. This <code>disabled</code> property + * will be set to <code>false</code>, and the <code>escape</code> + * property will be set to <code>true</code>.</p> + * + * @param value Value to be delivered to the model if this + * item is selected by the user + * @param label Label to be rendered for this item in the response + * @param description Description of this item, for use in tools + */ + public SelectItem(Object value, String label, String description) { + + this(value, label, description, false, true, false); + + } + + + /** + * <p>Construct a <code>SelectItem</code> instance with the specified + * property values. The <code>escape</code> property will be set + * to <code>true</code>.</p> + * + * @param value Value to be delivered to the model if this + * item is selected by the user + * @param label Label to be rendered for this item in the response + * @param description Description of this item, for use in tools + * @param disabled Flag indicating that this option is disabled + */ + public SelectItem(Object value, String label, String description, + boolean disabled) { + + this(value, label, description, disabled, true, false); + + } + + /** + * <p>Construct a <code>SelectItem</code> instance with the specified + * property values.</p> + * + * @param value Value to be delivered to the model if this + * item is selected by the user + * @param label Label to be rendered for this item in the response + * @param description Description of this item, for use in tools + * @param disabled Flag indicating that this option is disabled + * @param escape Flag indicating that the text of this option should be + * escaped when rendered. + * @since 1.2 + */ + public SelectItem(Object value, String label, String description, + boolean disabled, boolean escape) { + + this(value, label, description, disabled, escape, false); + + } + + + /** + * <p>Construct a <code>SelectItem</code> instance with the specified + * property values.</p> + * + * @param value Value to be delivered to the model if this + * item is selected by the user + * @param label Label to be rendered for this item in the response + * @param description Description of this item, for use in tools + * @param disabled Flag indicating that this option is disabled + * @param escape Flag indicating that the text of this option should be + * escaped when rendered. + * @param noSelectionOption Flag indicating that the current option is a "no selection" option + * @since 1.2 + */ + public SelectItem(Object value, String label, String description, + boolean disabled, boolean escape, boolean noSelectionOption) { + + super(); + setValue(value); + setLabel(label); + setDescription(description); + setDisabled(disabled); + setEscape(escape); + setNoSelectionOption(noSelectionOption); + + } + + + + + // ------------------------------------------------------ Instance Variables + + + private String description = null; + private boolean disabled = false; + private String label = null; + //@author jurzua + private String style = null; + @SuppressWarnings({"NonSerializableFieldInSerializableClass"}) + private Object value = null; + + + // -------------------------------------------------------------- Properties + + + /** + * <p>Return a description of this item, for use in development tools. + */ + public String getDescription() { + + return (this.description); + + } + + + /** + * <p>Set the description of this item, for use in development tools.</p> + * + * @param description The new description + */ + public void setDescription(String description) { + + this.description = description; + + } + + + /** + * <p>Return the disabled flag for this item, which should modify the + * rendered output to make this item unavailable for selection by the user + * if set to <code>true</code>.</p> + */ + public boolean isDisabled() { + + return (this.disabled); + + } + + + /** + * <p>Set the disabled flag for this item, which should modify the + * rendered output to make this item unavailable for selection by the user + * if set to <code>true</code>.</p> + * + * @param disabled The new disabled flag + */ + public void setDisabled(boolean disabled) { + + this.disabled = disabled; + + } + + + /** + * <p>Return the label of this item, to be rendered visibly for the user. + */ + public String getLabel() { + + return (this.label); + + } + + + /** + * <p>Set the label of this item, to be rendered visibly for the user. + * + * @param label The new label + */ + public void setLabel(String label) { + + this.label = label; + + } + + + /** + * <p>Return the value of this item, to be delivered to the model + * if this item is selected by the user. + */ + public Object getValue() { + + return (this.value); + + } + + + /** + * <p>Set the value of this item, to be delivered to the model + * if this item is selected by this user. + * + * @param value The new value + * + */ + public void setValue(Object value) { + + this.value = value; + + } + + private boolean escape; + + /** + * <p class="changed_added_2_0_rev_a">If and only if this returns + * <code>true</code>, the code that renders this select item must + * escape the label using escaping syntax appropriate to the content + * type being rendered. </p> + * + * @since 2.0 + */ + public boolean isEscape() { + return this.escape; + } + + /** + * <p class="changed_added_2_0_rev_a">Set the value of the escape + * property. See {@link #isEscape}.</p> + * + * @since 2.0 + */ + public void setEscape(boolean escape) { + this.escape = escape; + } + + private boolean noSelectionOption = false; + + /** <p class="changed_added_2_0">Return the value of the + * <code>noSelectionOption</code> property. If the value of this + * property is <code>true</code>, the system interprets the option + * represented by this <code>SelectItem</code> instance as + * representing a "no selection" option. See {@link + * UISelectOne#validateValue} and {@link UISelectMany#validateValue} + * for usage.</p> + * + * @since 2.0 + */ + + public boolean isNoSelectionOption() { + return noSelectionOption; + } + + /** + * <p class="changed_added_2_0">Set the value of the + * <code>noSelectionOption</code> property.</p> + * + * @since 2.0 + */ + + public void setNoSelectionOption(boolean noSelectionOption) { + this.noSelectionOption = noSelectionOption; + } + + /** + * @author jurzua + */ + public void setStyle(String style){ + this.style = style; + } + + /** + * @author jurzua + */ + public String getStyle(){ + return (this.style); + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/docs/richfaces/RichBean.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,29 @@ +package org.docs.richfaces; + +import java.io.Serializable; + +import javax.annotation.PostConstruct; +import javax.faces.bean.ManagedBean; +import javax.faces.bean.ViewScoped; + +@ViewScoped +@ManagedBean +public class RichBean implements Serializable { + + private static final long serialVersionUID = -6239437588285327644L; + + private String name; + + @PostConstruct + public void postContruct() { + name = "John"; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/AbstractClient.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,376 @@ +package org.mpiwg.itgroup.escidoc; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.client.params.ClientPNames; +import org.apache.http.client.params.CookiePolicy; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.jdom.Attribute; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.JDOMException; +import org.jdom.input.SAXBuilder; +import org.jdom.xpath.XPath; +import org.mpiwg.itgroup.escidoc.bo.Creator; +import org.mpiwg.itgroup.escidoc.bo.ESciDocConstants; +import org.mpiwg.itgroup.escidoc.bo.ESciDocItem; +import org.mpiwg.itgroup.escidoc.bo.Publication; +import org.mpiwg.itgroup.escidoc.bo.Publishing; + +public class AbstractClient extends ESciDocConstants implements Serializable{ + + private static final long serialVersionUID = 8133780898394554218L; + + private String user; + private String password; + public String eScidocUrl; + private HttpClient httpclient = null; + + public AbstractClient(String eScidocServer, int eScidocPort, String user, + String password) { + this.user = user; + this.password = password; + this.eScidocUrl = "http://" + eScidocServer + ":" + + String.valueOf(eScidocPort); + } + + public HttpClient login() throws IOException { + httpclient = new DefaultHttpClient(); + + httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, + CookiePolicy.BROWSER_COMPATIBILITY); + + HttpPost httppost = new HttpPost(eScidocUrl + "/aa/login?target=/"); + + HttpResponse response = httpclient.execute(httppost); + // HttpEntity entity = httppost.getRes + + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + + HttpEntity entity = response.getEntity(); + if (entity != null) { + entity.consumeContent(); + } + + HttpGet httpget = new HttpGet(eScidocUrl + + "/aa/j_spring_security_check?j_username=" + user + + "&j_password=" + password); + + response = httpclient.execute(httpget); + // entity = response.getEntity(); + + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + + entity = response.getEntity(); + if (entity != null) { + entity.consumeContent(); + } + + // entity.consumeContent(); + return httpclient; + } + + public HttpClient getHttpClient() throws IOException { + //if (httpclient == null) { + //how can be detected that the timeout of the session??? + this.login(); + //} + return httpclient; + } + + public ESciDocItem eScidocPut(String command, InputStream body) + throws IOException, JDOMException, ESciDocException, Exception { + //create PUT /ir/item return item + //update PUT /ir/item/<item-id> return item + System.out.println("PUT " + eScidocUrl + command); + HttpPut httpput = new HttpPut(eScidocUrl + command); + return getItemFromDoc(eScidocRequestBase(httpput, command, body)); + } + + public String eScidocPost(String command, InputStream body) + throws IOException, JDOMException, ESciDocException, Exception { + ///ir/item/<item-id>/submit last-modification-date + ///ir/item/<item-id>/release last-modification-date within XML (result.xsd) + System.out.println("----------------------"); + System.out.println("POST " + eScidocUrl + command); + HttpPost httppost = new HttpPost(eScidocUrl + command); + + return getLastModificationDate(eScidocRequestBase(httppost, command, body)); + } + + public void eScidocDelete(String command, InputStream body) + throws IOException, JDOMException, ESciDocException, Exception { + //DELETE /ir/item/<item-id> + System.out.println("----------------------"); + System.out.println("DELETE " + eScidocUrl + command); + HttpDelete httppost = new HttpDelete(eScidocUrl + command); + + eScidocRequestBase(httppost, command, body); + return; + } + + public ESciDocItem eScidocGet(String command) throws IOException, + JDOMException, ESciDocException, Exception { + System.out.println("GET " + eScidocUrl + command); + HttpGet httpget = new HttpGet(eScidocUrl + command); + Document doc = eScidocRequestBase(httpget, command, null); + //System.out.println(new XMLOutputter().outputString(doc)); + return getItemFromDoc(doc); + } + + private Document eScidocRequestBase(HttpRequestBase httpBase, String command, + InputStream body) throws Exception { + + if (HttpEntityEnclosingRequestBase.class.isInstance(httpBase)) { + if (body != null) { + HttpEntity entity = new InputStreamEntity(body, -1); + ((HttpEntityEnclosingRequestBase) httpBase).setEntity(entity); + } + } + + HttpResponse status = getHttpClient().execute(httpBase); + + InputStream in = status.getEntity().getContent(); + Document doc = new SAXBuilder().build(in); + + //System.out.println("Resonse output for " + command + ":"); + //System.out.println(new XMLOutputter().outputString(doc)); + + // the response can be an exception for the cases UPDATE and GET + // The response can be a Item for GET + + isReponseException(doc); + + return doc; + } + + public static ESciDocItem getItemFromDoc(Document doc) throws Exception { + List<ESciDocItem> list = getItemsFromDoc(doc); + if (!list.isEmpty()) + return list.get(0); + return null; + } + + public static List<ESciDocItem> getItemsFromDoc(Document doc) + throws Exception { + List<ESciDocItem> list = new ArrayList<ESciDocItem>(); + + XPath xp = XPath.newInstance(".//escidocItem:item"); + xp.addNamespace("escidocItem", "http://www.escidoc.de/schemas/item/0.9"); + + List<Object> inputList = xp.selectNodes(doc); + for (Object obj : inputList) { + if (obj instanceof Element) { + Element eItem = (Element) obj; + + + + ESciDocItem escidocItem = new ESciDocItem(); + // FIXME: sometimes this is not the last version, therefore.... + escidocItem.setLastModificationDate(eItem.getAttributeValue("last-modification-date")); + addVersionToItem(eItem, escidocItem); + addPublicStatusItem(eItem, escidocItem); + addLatestVersionToItem(eItem, escidocItem); + addLatestRelease(eItem, escidocItem); + + escidocItem.setPublication(getPubFromXMLElement(eItem)); + Attribute objIdAtt = eItem.getAttribute("objid"); + String objId = (objIdAtt != null) ? objIdAtt.getValue() : null; + + if(StringUtils.isEmpty(objId)){ + //xlink:href="/ir/item/escidoc:127561" + objIdAtt = eItem.getAttribute("href", NS_XLINK); + objId = (objIdAtt != null) ? objIdAtt.getValue() : ""; + objId = objId.replace("/ir/item/", ""); + } + escidocItem.getPublication().setObjid(objId); + + list.add(escidocItem); + } else { + System.out.println(obj); + } + } + + return list; + } + + public static void addPublicStatusItem(Element eItem, ESciDocItem item){ + Element props = eItem.getChild("properties", NS_ESCIDOC_ITEM); + Element publicStatus = props.getChild("public-status", NS_PROP); + + item.setPublicStatus((publicStatus != null) ? publicStatus.getValue() : null); + } + + public static void addVersionToItem(Element eItem, ESciDocItem item){ + Element props = eItem.getChild("properties", NS_ESCIDOC_ITEM); + Element version = props.getChild("version", NS_PROP); + + if(version != null){ + String value = (version.getChild("number", NS_VERSION) != null) ? version.getChild("number", NS_VERSION).getValue() : null; + item.setVersionNumber(value); + + value = (version.getChild("date", NS_VERSION) != null) ? version.getChild("date", NS_VERSION).getValue() : null; + item.setVersionDate(value); + + value = (version.getChild("status", NS_VERSION) != null) ? version.getChild("status", NS_VERSION).getValue() : null; + item.setVersionStatus(value); + } + } + + public static void addLatestVersionToItem(Element eItem, ESciDocItem item){ + Element props = eItem.getChild("properties", NS_ESCIDOC_ITEM); + Element latestVersion = props.getChild("latest-version", NS_PROP); + + //Attribute hrefAtt = latestVersion.getAttribute("href", NS_XLINK); + //putting into item + item.setLatestVersionNumber(latestVersion.getChild("number", NS_VERSION).getValue()); + item.setLatestVersionDate(latestVersion.getChild("date", NS_VERSION).getValue()); + //item.setLatestVersionHref(hrefAtt.getValue()); + } + + + + private static void addLatestRelease(Element eItem, ESciDocItem item){ + Element props = eItem.getChild("properties", NS_ESCIDOC_ITEM); + Element latestRelease = props.getChild("latest-release", NS_PROP); + + if(latestRelease != null){ + //Attribute hrefAtt = latestRelease.getAttribute("href", NS_XLINK); + + //putting into item + item.setLatestReleaseNumber(latestRelease.getChild("number", NS_RELEASE).getValue()); + item.setLatestReleaseDate(latestRelease.getChild("date", NS_RELEASE).getValue()); + //item.setLatestReleasePid(latestRelease.getChild("pid", NS_RELEASE).getValue()); + //item.setLatestReleaseHref(hrefAtt.getValue()); + } + } + + private void isReponseException(Document doc) + throws JDOMException, IOException, ESciDocException { + + XPath xp = XPath.newInstance(".//exception"); + xp.addNamespace("escidocItem", "http://www.escidoc.de/schemas/item/0.9"); + + List<Object> inputList = xp.selectNodes(doc); + if (!inputList.isEmpty()) { + throw new ESciDocException((Element) inputList.get(0)); + } + } + + private String getLastModificationDate(Document doc) throws JDOMException{ + + if(doc.getRootElement().getName().equals("result")){ + Attribute lastModif = doc.getRootElement().getAttribute("last-modification-date"); + if(lastModif != null){ + return lastModif.getValue(); + } + } + return null; + } + + protected static Publication getPubFromXMLElement(Element item) { + + Publication reference = new Publication(getObjId(item.getAttribute( + "href", NS_XLINK))); + + Element md_records = item.getChild("md-records", NS_ESCIDOC_MD_RECORDS); + Element md_record = md_records.getChild("md-record", NS_ESCIDOC_MD_RECORDS); + Element publication = md_record.getChild("publication", NS_PUBLICATION); + + List<Object> creatorList = publication.getChildren("creator", NS_ETERMS); + Element title = publication.getChild("title", NS_DC); + List<Object> alternativeList = publication.getChildren("alternative", NS_DCTERMS); + Element publishing_info = publication.getChild("publishing-info", NS_ETERMS); + Element issued = publication.getChild("issued", NS_DCTERMS); + Element totalNumberOfPages = publication.getChild("total-number-of-pages", NS_ETERMS); + + //<dcterms:subject xmlns:dcterms="http://purl.org/dc/terms/"> + Element subject = publication.getChild("subject", NS_DCTERMS); + + // Filling the reference + + for (Object object : creatorList) { + if (object instanceof Element) { + Element creator = (Element) object; + Element person = creator.getChild("person", NS_PERSON); + + if (person != null) { + Element complete_name = person.getChild("complete-name", + NS_ETERMS); + Element family_name = person.getChild("family-name", + NS_ETERMS); + Element given_name = person.getChild("given-name", + NS_ETERMS); + Element organization = person.getChild("organization", + NS_ORGANIZATION); + + reference.addCreator(new Creator( + (complete_name != null) ? complete_name.getText() + : "", (family_name != null) ? family_name + .getText() : "", + (given_name != null) ? given_name.getText() : "")); + } + } + } + + reference.setTitle((title != null) ? title.getText() : ""); + + for (Object object : alternativeList) { + if (object instanceof Element) { + Element alternative = (Element) object; + reference.addAlternative(alternative.getText()); + } + } + + if (publishing_info != null) { + Element publisher = publishing_info.getChild("publisher", NS_DC); + Element place = publishing_info.getChild("place", NS_ETERMS); + Element edition = publishing_info.getChild("edition", NS_ETERMS); + + reference.setPublishing(new Publishing( + (publisher != null) ? publisher.getText() : "", + (place != null) ? place.getText() : "", + (edition != null) ? edition.getText() : "")); + } + + reference.setIssued + ((issued != null) ? issued.getText() : ""); + reference.setNumberOfPages + ((totalNumberOfPages != null) ? totalNumberOfPages.getText() : ""); + reference.setSubject + ((subject != null) ? subject.getText() : ""); + + return reference; + } + + private static String getObjId(Attribute att) { + // new Attribute("href", "/ir/item/"+ publication.getObjid() + // +"/md-records", NS_XLINK) + if (att != null) { + String objId = att.getValue().replace("/ir/item/", ""); + String[] array = objId.split(":"); + if (array.length == 3) { + return array[0] + ":" + array[1]; + } + return objId; + } + return null; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/AbstractESciDocCache.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,107 @@ +package org.mpiwg.itgroup.escidoc; + +import java.io.Serializable; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.mpiwg.itgroup.escidoc.bo.ESciDocItem; + +public class AbstractESciDocCache implements Serializable{ + + private static final long serialVersionUID = 2093872792493279298L; + + private static Integer SERVER_STATUS_OK = 0; + private static Integer SERVER_STATUS_DOWN = 1; + + public static int SORT_NONE = -1; + public static int SORT_DEFAULT = 0; + public static int SORT_TITLE = 1; + public static int SORT_CREATOR = 2; + + + private int serverStatus = SERVER_STATUS_OK; + private Long lastSynchronizationTimeExec; + private Date lastSynchronization; + private int lastSynchronizationMaxRecords; + private final static DateFormat dateformater = new SimpleDateFormat("yyyy.MM.dd-HH:mm"); + + protected ESciDocClient client = new ESciDocClient("escidoc.mpiwg-berlin.mpg.de", 8080, "jurzua", "221082"); + + private Map<String,ESciDocItem> itemMap; + private Integer maxRecords = 50; + + public Map<String,ESciDocItem> getItemMap(){ + if(itemMap == null || SERVER_STATUS_DOWN.equals(serverStatus)){ + this.synchronizeWithServer(); + } + return itemMap; + } + + public int getItemsSize(){ + return this.getItemMap().size(); + } + + public void synchronizeWithServer(){ + + System.out.println("synchronizeWithServer Pubman"); + + long start = System.currentTimeMillis(); + this.itemMap = new HashMap<String, ESciDocItem>(); + this.lastSynchronizationMaxRecords = this.maxRecords; + try { + //List<ESciDocItem> list = new ArrayList<ESciDocItem>(); //ESciDocClient.getAllItems(); + + List<ESciDocItem> list = new ArrayList<ESciDocItem>(); //ESciDocClient.getAllItems(this.maxRecords); + for(ESciDocItem item : list){ + this.itemMap.put(item.getPublication().getObjid(), item); + } + this.serverStatus = SERVER_STATUS_OK; + } catch (Exception e) { + e.printStackTrace(); + this.serverStatus = SERVER_STATUS_DOWN; + } finally{ + this.lastSynchronization = new Date(); + } + this.lastSynchronizationTimeExec = System.currentTimeMillis() - start; + } + + public String getServerStatus(){ + if(SERVER_STATUS_OK.equals(serverStatus)){ + return new String("OK"); + }else{ + return new String("Server did not respond."); + } + } + + public String getLastSynchronization() { + return dateformater.format(lastSynchronization); + } + + public boolean isServerStatusOK(){ + if(SERVER_STATUS_OK.equals(SERVER_STATUS_OK)) + return true; + return false; + } + + public Long getLastSynchronizationTimeExec() { + return lastSynchronizationTimeExec; + } + + public Integer getMaxRecords() { + return maxRecords; + } + + public void setMaxRecords(Integer maxRecords) { + this.maxRecords = maxRecords; + } + + public int getLastSynchronizationMaxRecords() { + return lastSynchronizationMaxRecords; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/BootcampClient.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,57 @@ +package org.mpiwg.itgroup.escidoc; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.json.JSONException; +import org.json.JSONObject; + +public class BootcampClient { + + public static String url = "http://localhost:8080/"; + + + public static void testPost() throws JSONException, ClientProtocolException, IOException{ + HttpPost httpBase = new HttpPost("http://localhost:8080/"); + + JSONObject json = new JSONObject(); + json.put("name", "Jorge hahaha"); + json.put("text", "jhakjhskhjdsahjdsahjkdsa"); + + + + InputStream body = new ByteArrayInputStream(json.toString().getBytes()); + if (HttpEntityEnclosingRequestBase.class.isInstance(httpBase)) { + if (body != null) { + HttpEntity entity = new InputStreamEntity(body, -1); + ((HttpEntityEnclosingRequestBase) httpBase).setEntity(entity); + } + } + + HttpResponse status = (new DefaultHttpClient()).execute(httpBase); + } + + /** + * @param args + */ + public static void main(String[] args) { + try { + System.out.println("TESTING BEGINING*******"); + testPost(); + System.out.println("TESTING END************"); + } catch (Exception e) { + e.printStackTrace(); + } + + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/ESciDocCache.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,160 @@ +package org.mpiwg.itgroup.escidoc; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.faces.event.ActionEvent; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.jdom.JDOMException; +import org.mpi.openmind.repository.utils.NormalizerUtils; +import org.mpiwg.itgroup.escidoc.bo.Creator; +import org.mpiwg.itgroup.escidoc.bo.ESciDocItem; +import org.mpiwg.itgroup.escidoc.bo.utils.SortItemByCreator; +import org.mpiwg.itgroup.escidoc.bo.utils.SortItemByTitle; + +public class ESciDocCache extends AbstractESciDocCache{ + + private static final long serialVersionUID = 2087364857910704625L; + + private static Logger logger = Logger.getLogger(ESciDocCache.class); + + public ESciDocCache(){ + this.synchronizeWithServer(); + } + + public ESciDocItem getItemFromServer(String id) throws IOException, JDOMException, ESciDocException, Exception{ + System.out.println("ESciDocCache.getItemFromServer " + id); + return this.client.getItemX(id); + } + + public ESciDocItem getItem(String id){ + System.out.println("ESciDocCache.getItem " + id); + return this.getItemMap().get(id); + } + + public void deleteItem(ESciDocItem item, String userName) throws Exception{ + logger.info("Deleting " + item.getObjId()); + + /* + if(item.getVersionStatus().equals("released")){ + //only doing a change, the update of the item will change its status to pending, + //otherwise I do not see a way to move from released to pending (in-revision would also work). + item.getPublication().setTitle(item.getPublication().getTitle() + "."); + item = this.client.updateItem(item); + item.setLastModificationDate(this.client.submitItem(item, userName)); + item.setLastModificationDate(this.client.reviseItem(item, userName)); + + }*/ + + if(item.getPublicStatus().equals("pending") || item.getPublicStatus().equals("in-revision")){ + this.client.deleteItem(item.getObjId()); + }else{ + this.client.withdrawItem(item, userName); + } + + + this.getItemMap().remove(item.getObjId()); + } + + public ESciDocItem saveItem(ESciDocItem item, String userName) throws Exception{ + + logger.info("Saving " + item.getObjId()); + + if(item != null && StringUtils.isNotEmpty(item.getObjId())){ + + item = this.client.updateItem(item); + + + }else if(StringUtils.isEmpty(item.getObjId())){ + + item = this.client.createItem(item); + + } + + if(item.getVersionStatus().equals("pending")){ + //Submitting + item.setLastModificationDate(this.client.submitItem(item, userName)); + item.setLastModificationDate(this.client.releaseItem(item, userName)); + } + + if(item.getVersionStatus().equals("submitted")){ + //Releasing + item.setLastModificationDate(this.client.releaseItem(item, userName)); + } + + this.getItemMap().put(item.getObjId(), item); + + return item; + } + + + public List<ESciDocItem> getAllItems(Integer sortBy){ + List<ESciDocItem> list = new ArrayList<ESciDocItem>(getItemMap().values()); + sort(sortBy, list); + return list; + } + + public static void sort(Integer sortBy, List<ESciDocItem> list){ + if(sortBy == null || sortBy.equals(SORT_NONE)){ + return; + }else if(sortBy.equals(SORT_DEFAULT)){ + Collections.sort(list); + }else if(sortBy.equals(SORT_TITLE)){ + Collections.sort(list, new SortItemByTitle()); + }else if(sortBy.equals(SORT_CREATOR)){ + Collections.sort(list, new SortItemByCreator()); + } + } + + public void listenerSynchronizeWithServer(ActionEvent event){ + this.synchronizeWithServer(); + } + + public List<ESciDocItem> searchItem(String term, Integer sortBy){ + List<ESciDocItem> rs = new ArrayList<ESciDocItem>(); + + if(StringUtils.isNotEmpty(term)){ + term = NormalizerUtils.normalize(term); + + for(ESciDocItem item : getItemMap().values()){ + if(itemContainsTerm(item, term)){ + rs.add(item); + } + } + sort(sortBy, rs); + } + return rs; + } + + private boolean itemContainsTerm(ESciDocItem item, String term){ + + if(item.getObjId().contains(term)) + return true; + + String secondTerm = item.getPublication().getNorTitle(); + if(secondTerm.contains(term)) + return true; + + secondTerm = item.getPublication().getNorSubject(); + if(secondTerm.contains(term)) + return true; + + for(String secondTerm0 : item.getPublication().getNorAlternativeList()){ + if(secondTerm0.contains(term)) + return true; + } + + for(Creator creator : item.getPublication().getCreatorList()){ + if(creator.containsTerm(term)) + return true; + } + + return false; + } + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/ESciDocClient.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,227 @@ +package org.mpiwg.itgroup.escidoc; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Serializable; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URL; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.params.ClientPNames; +import org.apache.http.client.params.CookiePolicy; +import org.apache.http.impl.client.DefaultHttpClient; +import org.jdom.Attribute; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.JDOMException; +import org.jdom.input.SAXBuilder; +import org.jdom.output.XMLOutputter; +import org.jdom.xpath.XPath; +import org.mpiwg.itgroup.escidoc.bo.Creator; +import org.mpiwg.itgroup.escidoc.bo.ESciDocConstants; +import org.mpiwg.itgroup.escidoc.bo.ESciDocItem; +import org.mpiwg.itgroup.escidoc.bo.Publication; +import org.mpiwg.itgroup.escidoc.bo.Publishing; + +public class ESciDocClient extends AbstractClient implements Serializable{ + + private static final long serialVersionUID = 4982908578268938883L; + public static String GET_ITEM = "http://escidoc.mpiwg-berlin.mpg.de:8080/ir/item/"; + public static String GET_CONTEXT = "http://escidoc.mpiwg-berlin.mpg.de:8080/ir/context/"; + public static String PUT_ITEM = GET_ITEM; + public static String CREATE_ITEM = GET_ITEM; + + public static String ISMI_CONTEXT_ID = "escidoc:79281"; + private static String ENCODING = "UTF-8"; + + public static String host = + "http://escidoc.mpiwg-berlin.mpg.de:8080/srw/search/escidoc_all?operation=searchRetrieve&maximumRecords=MAX_RECORDS&query="; + + public static String queryGetAll = + "escidoc.content-model.objid=escidoc:persistent4 and escidoc.context.objid=" + + ISMI_CONTEXT_ID; + + public static String queryGetObjectById = "escidoc.content-model.objid=escidoc:persistent4 and escidoc.context.objid=" + + ISMI_CONTEXT_ID + " and escidoc.objid="; + + public static String queryByTitle = "escidoc.content-model.objid=escidoc:persistent4 and escidoc.context.objid=" + + ISMI_CONTEXT_ID + " and escidoc.any-title:="; + + static { + try { + // PUT_ITEM = URLEncoder.encode(PUT_ITEM, ENCODING); + queryGetAll = URLEncoder.encode(queryGetAll, ENCODING); + queryGetObjectById = URLEncoder + .encode(queryGetObjectById, ENCODING); + queryByTitle = URLEncoder.encode(queryByTitle, ENCODING); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + public ESciDocClient(String eScidocServer, int eScidocPort, String user, + String password) { + super(eScidocServer, eScidocPort, user, password); + } + + public void deleteItem(String objId) throws Exception { + eScidocDelete("/ir/item/" + objId, null); + return; + } + + + + public ESciDocItem updateItem(ESciDocItem item) throws Exception { + String body = new XMLOutputter().outputString(item.toXMLESciDoc(UPDATE)); + byte[] data = body.getBytes("UTF-8"); + return this.eScidocPut("/ir/item/" + item.getObjId(), new ByteArrayInputStream(data)); + } + + public ESciDocItem createItem(ESciDocItem item) throws Exception { + if(item.getObjId() != null){ + throw new Exception("Trying to create a item that has already an object id."); + } + String body = new XMLOutputter().outputString(item.toXMLESciDoc(CREATE)); + //System.out.println("----------------- INPUT for CREATE"); + //System.out.println(body); + //System.out.println("-----------------"); + byte[] data = body.getBytes("UTF-8"); + return this.eScidocPut("/ir/item", new ByteArrayInputStream(data)); + } + + /** + * + * @param item + * @param comment + * @return the modification date of this action that should be updated in the cache + * @throws Exception + */ + public String releaseItem(ESciDocItem item, String comment) throws Exception { + return this.executeAction(item, comment, "release"); + } + + /** + * + * @param item + * @param comment + * @return the modification date of this action that should be updated in the cache + * @throws Exception + */ + public String submitItem(ESciDocItem item, String comment) throws Exception { + return this.executeAction(item, comment, "submit"); + } + + public String reviseItem(ESciDocItem item, String comment) throws Exception { + return this.executeAction(item, comment, "revise"); + } + + public String withdrawItem(ESciDocItem item, String comment) throws Exception { + return this.executeAction(item, comment, "withdraw"); + } + + private String executeAction(ESciDocItem item, String comment, String action) throws Exception{ + Element param = new Element("param"); + param.setAttribute(new Attribute("last-modification-date", item.getLastModificationDate())); + Document doc = new Document(param); + + Element eComment = new Element("comment"); + if(StringUtils.isNotEmpty(comment)){ + eComment.addContent(comment); + } + param.addContent(eComment); + + String body = new XMLOutputter().outputString(doc); + byte[] data = body.getBytes("UTF-8"); + return this.eScidocPost("/ir/item/" + item.getObjId() + "/" + action, new ByteArrayInputStream(data)); + } + + public static List<ESciDocItem> getAllItems(Integer maxRecords) throws Exception { + String host0 = host.replace("MAX_RECORDS", maxRecords.toString()); + System.out.println("getAllPublications=" + host0 + queryGetAll); + URI uri = new URI(host0 + queryGetAll); + URL url = uri.toURL(); + InputStream in = url.openStream(); + Document doc = new SAXBuilder().build(in); + return getItemsFromDoc(doc); + } + + public ESciDocItem getItemX(String objId) throws IOException, JDOMException, ESciDocException, Exception{ + return eScidocGet("/ir/item/" + objId); + + } + + public static ESciDocItem getItem(String escidocId) throws Exception { + return getItemFromDoc(getItem0(escidocId)); + } + + private static Document getItem0(String escidocId) throws Exception { + URL url = new URL(GET_ITEM + escidocId); + System.out.println("getItem0= " + GET_ITEM + escidocId); + + HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); + httpCon.setRequestMethod("GET"); + + InputStreamReader in = new InputStreamReader(httpCon.getInputStream(), ENCODING); + + Document doc = new SAXBuilder().build(in); + return doc; + } + + public static void testGet() { + try { + ESciDocItem item = getItem("escidoc:127561"); + System.out.println(new XMLOutputter().outputString(item + .toXMLESciDoc(null))); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void testGetAndSave() { + try { + + //ESciDocItem item = getItem("escidoc:127561"); + + //System.out.println(new XMLOutputter().outputString(item.toXMLESciDoc(UPDATE))); + + ESciDocClient client = new ESciDocClient("escidoc.mpiwg-berlin.mpg.de", 8080, "jurzua", "221082"); + + ESciDocItem item = client.getItemX("escidoc:127561"); + + System.out.println(item.getLastModificationDate()); + + //item.getPublication().setTitle(item.getPublication().getTitle() + " test"); + //item.getPublication().setTitle(item.getPublication().getTitle().replace(" test", "")); + + //client.updateItem(item); + //client.submitItem(item, "test"); + //item = client.getItemX("escidoc:127561"); + client.releaseItem(item, "test"); + + + + //System.out.println(new XMLOutputter().outputString(item0 + // .toElementXMLESciDoc(UPDATE))); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) throws IOException { + ESciDocClient.testGetAndSave(); + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/ESciDocException.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,59 @@ +package org.mpiwg.itgroup.escidoc; + +import org.jdom.Element; +import org.jdom.output.XMLOutputter; + +public class ESciDocException extends Exception{ + private static final long serialVersionUID = 798105291785018910L; + + private String message; + private String title; + private String stackTrace; + private String cls; + private boolean internalException = false; + + public ESciDocException(Element input){ + try{ + Element etitle = input.getChild("title"); + Element emessage = input.getChild("message"); + Element eclass = input.getChild("class"); + Element estackTrace = input.getChild("stack-trace"); + + this.title = (etitle != null) ? etitle.getValue() : null; + this.message = (emessage != null) ? emessage.getValue() : null; + this.cls = (eclass != null) ? eclass.getValue() : null; + this.stackTrace = (estackTrace != null) ? estackTrace.getValue() : null; + }catch (Exception e) { + this.stackTrace = new XMLOutputter().outputString(input); + this.internalException = true; + } + } + + @Override + public void printStackTrace() { + printStackTrace(System.err); + if(!internalException){ + String tmp = "Exception comming from sSciDoc Server: \n"; + tmp += title + "\n"; + tmp += message + "\n"; + tmp += cls + "\n"; + System.err.println(tmp + stackTrace); + }else{ + System.err.println(stackTrace); + } + } + + @Override + public String getMessage() { + return message; + } + + public String getTitle(){ + return title; + } + + public String getCls(){ + return cls; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/ESciDocHandler.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,204 @@ +package org.mpiwg.itgroup.escidoc; + +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URL; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.Namespace; +import org.jdom.input.SAXBuilder; +import org.jdom.output.Format; +import org.jdom.output.XMLOutputter; +import org.jdom.xpath.XPath; +import org.mpiwg.itgroup.escidoc.bo.Creator; +import org.mpiwg.itgroup.escidoc.bo.Publication; +import org.mpiwg.itgroup.escidoc.bo.Publishing; +import org.mpiwg.itgroup.escidoc.bo.utils.SortPublicationByTitle; + +public class ESciDocHandler { + + public static String ISMI_CONTEXT_ID = "escidoc:79281"; + private static String ENCODING = "UTF-8"; + public static String host = "http://escidoc.mpiwg-berlin.mpg.de:8080/srw/search/escidoc_all?operation=searchRetrieve&maximumRecords=5000&query="; + public static String queryGetAll = "escidoc.content-model.objid=escidoc:persistent4 and escidoc.context.objid=" + ISMI_CONTEXT_ID; + + public static String queryGetObjectById = "escidoc.content-model.objid=escidoc:persistent4 and escidoc.context.objid=" + ISMI_CONTEXT_ID + " and escidoc.objid="; + + public static String queryByTitle = "escidoc.content-model.objid=escidoc:persistent4 and escidoc.context.objid=" + ISMI_CONTEXT_ID + " and escidoc.any-title:="; + + static{ + try { + queryGetAll = URLEncoder.encode(queryGetAll, ENCODING); + queryGetObjectById = URLEncoder.encode(queryGetObjectById, ENCODING); + queryByTitle = URLEncoder.encode(queryByTitle, ENCODING); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + public static List<Publication> getAllPublications() throws Exception{ + List<Publication> list = null; + System.out.println("getAllPublications=" + host + queryGetAll); + URI uri = new URI(host + queryGetAll); + URL url = uri.toURL(); + + InputStream in = url.openStream(); + list = getPublicationsFromStream(new SAXBuilder().build(in)); + + Collections.sort(list, new SortPublicationByTitle()); + return list; + } + + public static List<Publication> searchPublicationByTitle(String title) throws Exception{ + List<Publication> list = new ArrayList<Publication>(); + URI uri = new URI(host + queryGetAll); + URL url = uri.toURL(); + InputStream in = url.openStream(); + List<Publication> pubList = getPublicationsFromStream(new SAXBuilder().build(in)); + + title = title.toLowerCase(); + + for(Publication pub : pubList){ + if(StringUtils.isNotEmpty(pub.getTitle())){ + String pubTitle = pub.getTitle().toLowerCase(); + if(pubTitle.contains(title)){ + list.add(pub); + } + } + } + return list; + } + + public static List<Publication> searchPublicationByAuthor(String author) throws Exception{ + List<Publication> list = new ArrayList<Publication>(); + + URI uri = new URI(host + queryGetAll); + URL url = uri.toURL(); + InputStream in = url.openStream(); + List<Publication> pubList = getPublicationsFromStream(new SAXBuilder().build(in)); + + //TODO + /* + author = author.toLowerCase(); + + for(Publication pub : pubList){ + if(pub.getCreator() != null && StringUtils.isNotEmpty(pub.getCreator().getCompleteName())){ + String pubAuthor = pub.getCreator().getCompleteName().toLowerCase(); + if(pubAuthor.contains(author)){ + list.add(pub); + } + } + } */ + return list; + } + + public static Publication getPublicationById(String objectId) throws Exception{ + List<Publication> list = null; + String urlString = host + queryGetObjectById + objectId; + System.out.println(urlString); + URI uri = new URI(urlString); + URL url = uri.toURL(); + InputStream in = url.openStream(); + list = getPublicationsFromStream(new SAXBuilder().build(in)); + if(list.size() > 0){ + return list.get(0); + } + return null; + } + + private static List<Publication> getPublicationsFromStream(Document doc) throws Exception { + + List<Publication> list = new ArrayList<Publication>(); + + XPath xp = XPath.newInstance(".//escidocItem:item"); + xp.addNamespace("escidocItem", "http://www.escidoc.de/schemas/item/0.9"); + + List<Object> inputList = xp.selectNodes(doc); + //System.out.println("inputList.size: " + inputList.size()); + for(Object obj : inputList){ + if(obj instanceof Element){ + Element item = (Element)obj; + Publication reference = new Publication(item.getAttributeValue("objid")); + //System.out.println(reference.getObjid()); + + Element md_records = item.getChild("md-records", Namespace.getNamespace("escidocMetadataRecords", "http://www.escidoc.de/schemas/metadatarecords/0.5")); + Element md_record = md_records.getChild("md-record", Namespace.getNamespace("escidocMetadataRecords", "http://www.escidoc.de/schemas/metadatarecords/0.5")); + Element publication = md_record.getChild("publication", Namespace.getNamespace("publication", "http://purl.org/escidoc/metadata/profiles/0.1/publication")); + + + + + Element title = publication.getChild("title", Namespace.getNamespace("dc", "http://purl.org/dc/elements/1.1/")); + Element publishing_info = publication.getChild("publishing-info", Namespace.getNamespace("eterms", "http://purl.org/escidoc/metadata/terms/0.1/")); + Element issued = publication.getChild("issued", Namespace.getNamespace("dcterms", "http://purl.org/dc/terms/")); + if(issued != null){ + reference.setIssued(issued.getText()); + } + Element subject = publication.getChild("subject", Namespace.getNamespace("dcterms", "http://purl.org/dc/terms/")); + + List<Object> creatorList = publication.getChildren("creator", Namespace.getNamespace("eterms", "http://purl.org/escidoc/metadata/terms/0.1/")); + for(Object object : creatorList){ + if(object instanceof Element){ + Element creator = (Element)object; + Element person = creator.getChild("person", Namespace.getNamespace("person", "http://purl.org/escidoc/metadata/profiles/0.1/person")); + + if(person != null){ + Element complete_name = person.getChild("complete-name", Namespace.getNamespace("eterms", "http://purl.org/escidoc/metadata/terms/0.1/")); + Element family_name = person.getChild("family-name", Namespace.getNamespace("eterms", "http://purl.org/escidoc/metadata/terms/0.1/")); + Element given_name = person.getChild("given-name", Namespace.getNamespace("eterms", "http://purl.org/escidoc/metadata/terms/0.1/")); + Element organization = person.getChild("organization", Namespace.getNamespace("organization", "http://purl.org/escidoc/metadata/profiles/0.1/organization")); + + reference.addCreator(new Creator( + (complete_name != null) ? complete_name.getText() : "", + (family_name != null) ? family_name.getText() : "", + (given_name != null) ? given_name.getText() : "")); + } + } + } + + + if(publishing_info != null){ + Element publisher = publishing_info.getChild("publisher", Namespace.getNamespace("dc", "http://purl.org/dc/elements/1.1/")); + Element place = publishing_info.getChild("place", Namespace.getNamespace("eterms", "http://purl.org/escidoc/metadata/terms/0.1/")); + Element edition = publishing_info.getChild("edition", Namespace.getNamespace("eterms", "http://purl.org/escidoc/metadata/terms/0.1/")); + + reference.setPublishing( + new Publishing( + (publisher != null) ? publisher.getText() : "", + (place != null) ? place.getText() : "", + (edition != null) ? edition.getText() : "")); + } + + reference.setSubject((subject != null) ? subject.getText() : ""); + reference.setTitle((title != null) ? title.getText() : ""); + //System.out.println(reference.toString()); + list.add(reference); + + }else{ + System.out.println(obj); + } + } + + return list; + } + + public static void main(String[] args) { + try { + //ESciDocHandler.getAllPublications(); + + Publication pub = ESciDocHandler.getPublicationById("escidoc:127561"); + XMLOutputter outputter1 = new XMLOutputter(Format.getPrettyFormat()); + outputter1.output(pub.toXMLESciDoc(null), System.out); + + } catch (Exception e) { + e.printStackTrace(); + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/Test.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,131 @@ +package org.mpiwg.itgroup.escidoc; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.client.params.ClientPNames; +import org.apache.http.client.params.CookiePolicy; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.jdom.Document; +import org.jdom.output.XMLOutputter; +import org.mpiwg.itgroup.escidoc.bo.ESciDocItem; + +public class Test { + + //private String eScidocServer; + //private int eScidocPort; + private String user; + private String password; + public String eScidocUrl; + private HttpClient httpclient = null; + + public Test(String eScidocServer, int eScidocPort, String user, + String password) { + // this.eScidocServer=eScidocServer; + // this.eScidocPort=eScidocPort; + this.user = user; + this.password = password; + this.eScidocUrl = "http://" + eScidocServer + ":" + String.valueOf(eScidocPort); + } + + public HttpClient login() throws IOException { + httpclient = new DefaultHttpClient(); + + httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, + CookiePolicy.BROWSER_COMPATIBILITY); + + HttpPost httppost = new HttpPost(eScidocUrl + "/aa/login?target=/"); + + HttpResponse response = httpclient.execute(httppost); + // HttpEntity entity = httppost.getRes + + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + + HttpEntity entity = response.getEntity(); + if (entity != null) { + entity.consumeContent(); + } + + HttpGet httpget = new HttpGet(eScidocUrl + + "/aa/j_spring_security_check?j_username=" + user + + "&j_password=" + password); + + response = httpclient.execute(httpget); + // entity = response.getEntity(); + + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + + entity = response.getEntity(); + if (entity != null) { + entity.consumeContent(); + } + + // entity.consumeContent(); + return httpclient; + } + + public HttpResponse eScidocPut(String command, InputStream body) + throws IOException { + HttpPut httpput = new HttpPut(eScidocUrl + command); + return eScidocRequestBase(httpput, command, body); + } + + private HttpResponse eScidocRequestBase(HttpRequestBase httpBase, String command, InputStream body) throws IOException { + if (httpclient == null) + login(); + + if (HttpEntityEnclosingRequestBase.class.isInstance(httpBase)) { + if (body != null) { + HttpEntity entity = new InputStreamEntity(body, -1); + ((HttpEntityEnclosingRequestBase) httpBase).setEntity(entity); + } + } + + HttpResponse status = httpclient.execute(httpBase); + return status; + } + + public static Document testGetAndSave(){ + try { + ESciDocItem item = ESciDocClient.getItem("escidoc:127561"); + //System.out.println(new XMLOutputter().outputString(item.toXMLESciDoc(null))); + + return item.toXMLESciDoc(ESciDocClient.UPDATE); + + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + + + public static void main(String[] args) throws IOException { + /* + Document doc = Test.testGetAndSave(); + + String body = new XMLOutputter().outputString(doc); + byte[] data = body.getBytes("UTF-8"); + + Test test = new Test("escidoc-test.mpiwg-berlin.mpg.de", 8080, "jurzua", "221082"); + test.eScidocPut("/ir/item/escidoc:127561", new ByteArrayInputStream(data)); + */ + + String s = new String("CODEX:distinguishing_features&CODEX¬es_on_ownership&CODEX:notes"); + String[] array = s.split("&"); + System.out.println(array.length); + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/bo/Creator.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,148 @@ +package org.mpiwg.itgroup.escidoc.bo; + +import java.io.Serializable; + +import org.apache.commons.lang.StringUtils; +import org.jdom.Element; +import org.jdom.output.Format; +import org.jdom.output.XMLOutputter; +import org.mpi.openmind.repository.utils.NormalizerUtils; + +public class Creator extends ESciDocConstants implements Serializable{ + private static final long serialVersionUID = 1L; + + + //completeName familyName givenName + + private String completeName; + private String familyName; + private String givenName; + + private String norCompleteName; + private String norFamilyName; + private String norGivenName; + + public Creator(String completeName, String familyName, String givenName){ + this.setCompleteName(completeName); + this.setFamilyName(familyName); + this.setGivenName(givenName); + } + + public String getCompleteName() { + return completeName; + } + public void setCompleteName(String completeName) { + this.completeName = completeName; + if(StringUtils.isEmpty(completeName)){ + this.norCompleteName = new String(); + }else{ + this.norCompleteName = NormalizerUtils.normalize(completeName); + } + + } + public String getFamilyName() { + return familyName; + } + public void setFamilyName(String familyName) { + this.familyName = familyName; + if(StringUtils.isEmpty(familyName)){ + this.norFamilyName = new String(); + }else{ + this.norFamilyName = NormalizerUtils.normalize(familyName); + } + } + public String getGivenName() { + return givenName; + } + public void setGivenName(String givenName) { + this.givenName = givenName; + if(StringUtils.isEmpty(givenName)){ + this.norGivenName = new String(); + }else{ + this.norGivenName = NormalizerUtils.normalize(givenName); + } + } + + public String getNorCompleteName() { + return norCompleteName; + } + + public String getNorFamilyName() { + return norFamilyName; + } + + public String getNorGivenName() { + return norGivenName; + } + + /** + * term must be normalized before calling this method + * @param term + * @return + */ + public boolean containsTerm(String term){ + String secondTerm = this.getNorCompleteName(); + + if(secondTerm.contains(term)) + return true; + + secondTerm = this.getNorFamilyName(); + if(secondTerm.contains(term)) + return true; + + secondTerm = this.getNorGivenName(); + if(secondTerm.contains(term)) + return true; + + return false; + + } + + @Override + public Element toElementXMLESciDoc(Integer mode){ + Element root = new Element("person", NS_PERSON); + + Element completeName = new Element("complete-name", NS_ETERMS); + Element familyName = new Element("family-name", NS_ETERMS); + Element givenName = new Element("given-name", NS_ETERMS); + + completeName.addContent(this.completeName); + familyName.addContent(this.familyName); + givenName.addContent(this.givenName); + + root.addContent(completeName); + root.addContent(familyName); + root.addContent(givenName); + + Element organization = new Element("organization", NS_ORGANIZATION); + + Element orgTitle = new Element("title", NS_DC); + orgTitle.addContent("Max Planck Society"); + Element orgIdentifier = new Element("identifier", NS_DC); + + organization.addContent(orgTitle); + organization.addContent(orgIdentifier); + + root.addContent(organization); + + return root; + } + + public static void main(String[] args){ + try{ + Creator c = new Creator("Jorge Urzua", "Urzua", "Jorge"); + XMLOutputter outputter1 = new XMLOutputter(Format.getPrettyFormat()); + outputter1.output(c.toXMLESciDoc(null), System.out); + }catch (Exception e) { + e.printStackTrace(); + } + } + + + @Override + public String toString(){ + + return "Creator [completeName="+ completeName +", familyName="+ familyName +", givenName=" + givenName + "]"; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/bo/ESciDocConstants.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,93 @@ +package org.mpiwg.itgroup.escidoc.bo; + +import java.io.Serializable; + +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.Namespace; + +public class ESciDocConstants implements Serializable{ + + + + /** + * + */ + private static final long serialVersionUID = 7156928908863818464L; + public static Integer DEBUG = -1; + public static Integer CREATE = 0; + public static Integer UPDATE = 1; + + + public static Namespace NS_PERSON = Namespace.getNamespace("person", "http://purl.org/escidoc/metadata/profiles/0.1/person"); + public static Namespace NS_ORGANIZATION = Namespace.getNamespace("organization", "http://purl.org/escidoc/metadata/profiles/0.1/organization"); + + public static Namespace NS_DC = Namespace.getNamespace("dc", "http://purl.org/dc/elements/1.1/"); + public static Namespace NS_ETERMS = Namespace.getNamespace("eterms", "http://purl.org/escidoc/metadata/terms/0.1/"); + + public static Namespace NS_DCTERMS = Namespace.getNamespace("dcterms", "http://purl.org/dc/terms/"); + + //xmlns:publication="http://purl.org/escidoc/metadata/profiles/0.1/publication" + public static Namespace NS_PUBLICATION = Namespace.getNamespace("publication", "http://purl.org/escidoc/metadata/profiles/0.1/publication"); + + //xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + public static Namespace NS_XSI = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); + + //xsi:type="dcterms:W3CDTF" + //public static Namespace NS_XSI = Namespace.getNamespace("xsi", "dcterms:W3CDTF"); + + //xmlns:relations="http://www.escidoc.de/schemas/relations/0.3" + public static Namespace NS_RELATIONS = Namespace.getNamespace("relations", "http://www.escidoc.de/schemas/relations/0.3"); + + // xmlns:escidocMetadataRecords="http://www.escidoc.de/schemas/metadatarecords/0.5" + public static Namespace NS_ESCIDOC_MD_RECORDS = Namespace.getNamespace("escidocMetadataRecords", "http://www.escidoc.de/schemas/metadatarecords/0.5"); + + // xmlns:escidocContentStreams="http://www.escidoc.de/schemas/contentstreams/0.7" + public static Namespace NS_ESCIDOC_CONTENT_STREAMS = Namespace.getNamespace("escidocContentStreams", "http://www.escidoc.de/schemas/contentstreams/0.7"); + + // xmlns:escidocComponents="http://www.escidoc.de/schemas/components/0.9" + public static Namespace NS_ESCIDOC_COMPONENTS = Namespace.getNamespace("escidocComponents", "http://www.escidoc.de/schemas/components/0.9"); + + // xmlns:version="http://escidoc.de/core/01/properties/version/" + public static Namespace NS_VERSION = Namespace.getNamespace("version", "http://escidoc.de/core/01/properties/version/"); + + // xmlns:release="http://escidoc.de/core/01/properties/release/" + public static Namespace NS_RELEASE = Namespace.getNamespace("release", "http://escidoc.de/core/01/properties/release/"); + + // xmlns:escidocItem="http://www.escidoc.de/schemas/item/0.9" + public static Namespace NS_ESCIDOC_ITEM = Namespace.getNamespace("escidocItem", "http://www.escidoc.de/schemas/item/0.9"); + + // xmlns:prop="http://escidoc.de/core/01/properties/" + public static Namespace NS_PROP = Namespace.getNamespace("prop", "http://escidoc.de/core/01/properties/"); + + // xmlns:srel="http://escidoc.de/core/01/structural-relations/" + public static Namespace NS_SREL = Namespace.getNamespace("srel", "http://escidoc.de/core/01/structural-relations/"); + + // xmlns:xlink="http://www.w3.org/1999/xlink" + public static Namespace NS_XLINK = Namespace.getNamespace("xlink", "http://www.w3.org/1999/xlink"); + + // xml:base="http://escidoc.mpiwg-berlin.mpg.de:8080" + //public static Namespace NS_BASE = Namespace.getNamespace("base", "http://escidoc.mpiwg-berlin.mpg.de:8080"); + + // xlink:type="simple" + //public static Namespace NS_ = Namespace.getNamespace("", ""); + + // xlink:title="Max Planck Society" + //public static Namespace NS_ = Namespace.getNamespace("", ""); + + // xlink:href="/ir/item/escidoc:127561" + //public static Namespace NS_ = Namespace.getNamespace("", ""); + + public Element toElementXMLESciDoc(Integer mode){ + return null; + } + + public Document toXMLESciDoc(Integer mode){ + Document doc = new Document(); + + doc.setRootElement(this.toElementXMLESciDoc(mode)); + + return doc; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/bo/ESciDocItem.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,366 @@ +package org.mpiwg.itgroup.escidoc.bo; + +import org.apache.commons.lang.StringUtils; +import org.jdom.Attribute; +import org.jdom.Element; +import org.jdom.output.Format; +import org.jdom.output.XMLOutputter; + +public class ESciDocItem extends ESciDocConstants implements Cloneable, Comparable<ESciDocItem>{ + + public static int ESCIDOC_ERROR_ID_NO_FOUND = 0; + public static int ESCIDOC_ERROR_SERVER_NO_RESPONDED = 1; + + private Integer errorLoading; + + private Publication publication = null; + + private String lastModificationDate; + + //Properties TODO: this should be configurable + private static String CONTEXT_ID = "escidoc:79281"; + private static String CONTENT_MODEL = "escidoc:persistent4"; + + private String publicStatus; + + //item/properties/latest-version + //private String latestVersionHref; + private String latestVersionNumber; + private String latestVersionDate; + + //item/properties/latest-release + private String latestReleaseNumber; + private String latestReleaseDate; + //private String latestReleasePid; + + //item/properties/version + private String versionNumber; + private String versionDate; + private String versionStatus; + + + public ESciDocItem(String id){ + publication = new Publication(id); + } + + public ESciDocItem(){ + publication = new Publication(null); + } + + @Override + public Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + } + return null; + } + + @Override + public Element toElementXMLESciDoc(Integer mode){ + Element root = new Element("item", NS_ESCIDOC_ITEM); + + root.addNamespaceDeclaration(NS_RELATIONS); + root.addNamespaceDeclaration(NS_ESCIDOC_MD_RECORDS); + root.addNamespaceDeclaration(NS_ESCIDOC_CONTENT_STREAMS); + root.addNamespaceDeclaration(NS_ESCIDOC_COMPONENTS); + root.addNamespaceDeclaration(NS_VERSION); + root.addNamespaceDeclaration(NS_RELEASE); + root.addNamespaceDeclaration(NS_PROP); + root.addNamespaceDeclaration(NS_SREL); + root.addNamespaceDeclaration(NS_XLINK); + //root.addNamespaceDeclaration(NS_BASE); + + if(UPDATE.equals(mode)){ + // discarded for UPDATE and CREATE + root.setAttribute(new Attribute("type", "simple", NS_XLINK)); + root.setAttribute(new Attribute("title", "Max Planck Society", NS_XLINK)); + root.setAttribute(new Attribute("href", "/ir/item/" + publication.getObjid(), NS_XLINK)); + + root.setAttribute(new Attribute("last-modification-date", this.lastModificationDate)); + } + + // CREATE=required, UPDATE=optional + //if(CREATE.equals(mode)) + root.addContent(getESciDocItemProperties(mode)); + + root.addContent(getESciDocMDRecords(mode)); + + //item/components UPDATE, CREATE = required + Element components = new Element("components", NS_ESCIDOC_COMPONENTS); + if(mode == null){ + components.setAttribute(new Attribute("type", "simple", NS_XLINK)); + components.setAttribute(new Attribute("title", "Components of Item " + publication.getObjid(), NS_XLINK)); + components.setAttribute(new Attribute("href", "/ir/item/"+ publication.getObjid() +"/components", NS_XLINK)); + } + + root.addContent(components); + + if(UPDATE.equals(mode)){ + //item/relations UPDATE, CREATE = optional + Element relations = new Element("relations", NS_RELATIONS); + relations.setAttribute(new Attribute("type", "simple", NS_XLINK)); + relations.setAttribute(new Attribute("title", "Relations of Item", NS_XLINK)); + relations.setAttribute(new Attribute("href", "/ir/item/"+this.publication.getObjid()+"/relations", NS_XLINK)); + + //item/resources UPDATE, CREATE = discarded + Element resources = new Element("resources", NS_ESCIDOC_ITEM); + resources.setAttribute(new Attribute("type", "simple", NS_XLINK)); + resources.setAttribute(new Attribute("title", "Resources", NS_XLINK)); + resources.setAttribute(new Attribute("href", "/ir/item/"+this.publication.getObjid()+"/resources", NS_XLINK)); + } + + return root; + } + + private Element getESciDocItemProperties(Integer mode){ + + Element root = new Element("properties", NS_ESCIDOC_ITEM); + + //CREATE, UPDATE discard = xlink:type, xlink:title, xlink:href, xml:base + //UPDATE requests = last-modification-date + + //item/properties + if(UPDATE.equals(mode)){ + root.setAttribute(new Attribute("type", "simple", NS_XLINK)); + root.setAttribute(new Attribute("title", "Properties", NS_XLINK)); + root.setAttribute(new Attribute("href", "/ir/item/" + this.publication.getObjid() + "/properties", NS_XLINK)); + } + + + //item/properties/context + Element context = new Element("context", NS_SREL); + context.setAttribute(new Attribute("type", "simple", NS_XLINK)); + context.setAttribute(new Attribute("title", "ISMI", NS_XLINK)); + context.setAttribute(new Attribute("href", "/ir/context/" + CONTEXT_ID, NS_XLINK)); + root.addContent(context); + + //item/properties/content-model + Element contentModel = new Element("content-model", NS_SREL); + if(UPDATE.equals(mode)){ + contentModel.setAttribute(new Attribute("type", "simple", NS_XLINK)); + contentModel.setAttribute(new Attribute("title", "ct", NS_XLINK)); + } + contentModel.setAttribute(new Attribute("href", "/cmm/content-model/" + CONTENT_MODEL, NS_XLINK)); + root.addContent(contentModel); + + + //item/properties/latest-version + if(mode == null){ + Element latestVersion = new Element("latest-version", NS_PROP); + //latestVersion.setAttribute(new Attribute("href", this.latestVersionHref, NS_XLINK)); + + Element eVersionNumber = new Element("number", NS_VERSION); + Element eVersionDate = new Element("date", NS_VERSION); + + eVersionNumber.addContent(this.latestVersionNumber); + eVersionDate.addContent(this.latestVersionDate); + + latestVersion.addContent(eVersionNumber); + latestVersion.addContent(eVersionDate); + + root.addContent(latestVersion); + } + + //item/properties/latest-release + if(mode == null){ + Element latestRelease = new Element("latest-release", NS_PROP); + //latestRelease.setAttribute(new Attribute("href", this.latestReleaseHref, NS_XLINK)); + + Element eReleaseNumber = new Element("number", NS_RELEASE); + Element eReleaseDate = new Element("date", NS_RELEASE); + //Element eReleasePid = new Element("pid", NS_RELEASE); + + eReleaseNumber.addContent(this.latestReleaseNumber); + eReleaseDate.addContent(this.latestReleaseDate); + //eReleasePid.addContent(this.latestReleasePid); + + latestRelease.addContent(eReleaseNumber); + latestRelease.addContent(eReleaseDate); + //latestRelease.addContent(eReleasePid); + + root.addContent(latestRelease); + } + + return root; + } + + private Element getESciDocMDRecords(Integer mode){ + Element root = new Element("md-records", NS_ESCIDOC_MD_RECORDS); + + if(UPDATE.equals(mode)){ + root.setAttribute(new Attribute("type", "simple", NS_XLINK)); + root.setAttribute(new Attribute("title", "Metadata Records of Item " + publication.getObjid(), NS_XLINK)); + root.setAttribute(new Attribute("href", "/ir/item/"+ publication.getObjid() +"/md-records", NS_XLINK)); + } + if(UPDATE.equals(mode)){ + //TODO last-modification-date + } + + Element record = new Element("md-record", NS_ESCIDOC_MD_RECORDS); + record.setAttribute(new Attribute("name", "escidoc")); + + if(UPDATE.equals(mode)){ + record.setAttribute(new Attribute("type", "simple", NS_XLINK)); + record.setAttribute(new Attribute("title", "escidoc", NS_XLINK)); + record.setAttribute(new Attribute("href", "/ir/item/"+ this.publication.getObjid() +"/md-records/md-record/escidoc", NS_XLINK)); + } + + record.addContent(this.publication.toElementXMLESciDoc(mode)); + + root.addContent(record); + + return root; + } + + public Publication getPublication() { + return publication; + } + + public void setPublication(Publication publication) { + this.publication = publication; + } + + public String getLastModificationDate() { + return lastModificationDate; + } + + public void setLastModificationDate(String lastModificationDate) { + this.lastModificationDate = lastModificationDate; + } + + public Integer getErrorLoading() { + return errorLoading; + } + + public void setErrorLoading(Integer errorLoading) { + this.errorLoading = errorLoading; + } + + public String getObjId(){ + if(publication != null) + return this.publication.getObjid(); + return null; + } + + public String getLatestVersionNumber() { + return latestVersionNumber; + } + + public void setLatestVersionNumber(String latestVersionNumber) { + this.latestVersionNumber = latestVersionNumber; + } + + public String getLatestVersionDate() { + return latestVersionDate; + } + + public void setLatestVersionDate(String latestVersionDate) { + this.latestVersionDate = latestVersionDate; + } + + public String getLatestReleaseNumber() { + return latestReleaseNumber; + } + + public void setLatestReleaseNumber(String latestReleaseNumber) { + this.latestReleaseNumber = latestReleaseNumber; + } + + public String getLatestReleaseDate() { + return latestReleaseDate; + } + + public void setLatestReleaseDate(String latestReleaseDate) { + this.latestReleaseDate = latestReleaseDate; + } + + @Override + public int compareTo(ESciDocItem arg0) { + if(this.publication != null && arg0.publication != null){ + if(StringUtils.isNotEmpty(this.publication.getObjid()) && StringUtils.isNotEmpty(arg0.publication.getObjid())){ + return this.getPublication().getObjid().compareTo(arg0.publication.getObjid()); + }else if(StringUtils.isNotEmpty(this.publication.getObjid())){ + return -1; + }else if(StringUtils.isNotEmpty(arg0.publication.getObjid())){ + return 1; + } + } + return 0; + } + + public static void main(String[] args){ + try{ + + Publication pub = new Publication(null); + + Publishing publishing = new Publishing("Jorge Urzua", "Chile", "JIJI"); + pub.setPublishing(publishing); + + Creator creator0 = new Creator("Jorge Urzua", "Urzua", "Jorge"); + Creator creator1 = new Creator("Valeria Mouzas", "Mouzas", "Valeria"); + pub.getCreatorList().add(creator0); + pub.getCreatorList().add(creator1); + + pub.setIssued("1982"); + pub.getAlternativeList().add("alternative01"); + pub.getAlternativeList().add("alternative02"); + pub.getAlternativeList().add("alternative03"); + + pub.setTitle("Por Dios..."); + + XMLOutputter outputter1 = new XMLOutputter(Format.getPrettyFormat()); + outputter1.output(pub.toXMLESciDoc(CREATE), System.out); + + }catch (Exception e) { + e.printStackTrace(); + } + } + + public String getVersionNumber() { + return versionNumber; + } + + public void setVersionNumber(String versionNumber) { + this.versionNumber = versionNumber; + } + + public String getVersionDate() { + return versionDate; + } + + public void setVersionDate(String versionDate) { + this.versionDate = versionDate; + } + + public String getVersionStatus() { + return versionStatus; + } + + public void setVersionStatus(String versionStatus) { + this.versionStatus = versionStatus; + } + + public String getPublicStatus() { + return publicStatus; + } + + public void setPublicStatus(String publicStatus) { + this.publicStatus = publicStatus; + } + + public String getInfo(){ + StringBuilder sb = new StringBuilder(); + + sb.append("publicStatus=" + this.publicStatus); + sb.append(", versionNumber=" + this.versionNumber); + sb.append(", versionStatus=" + this.versionStatus); + sb.append(", versionDate=" + this.versionDate); + sb.append(", releaseNumber=" + this.latestReleaseNumber); + sb.append(", releaseDate=" + this.latestReleaseDate); + + return sb.toString(); + + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/bo/Publication.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,311 @@ +package org.mpiwg.itgroup.escidoc.bo; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.jdom.Attribute; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.output.Format; +import org.jdom.output.XMLOutputter; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.utils.NormalizerUtils; + +public class Publication extends ESciDocConstants implements Comparable<Publication>, Serializable, Cloneable{ + + private static final long serialVersionUID = 1L; + private String objid; + private List<Creator> creatorList = new ArrayList<Creator>(); + private String title; + private List<String> alternativeList = new ArrayList<String>(); + + private Publishing publishing = new Publishing(null, null, null); + private String subject; + private String issued; + private String numberOfPages; + + + private String norTitle; + private List<String> norAlternativeList = new ArrayList<String>(); + private String norSubject; + + + + private String additionalInformation; + private Entity entity; + + private static String HTML_LABEL = "<span style=\"font-family: Arial;\">" + + "<font size=\"2\">" + + "[ID]AUTHORDATE <i>TITLE</i>PUBLISHER" + + "</font></span>"; + + @Override + public Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + } + return null; + } + + + public String getHTMLLabel(){ + + String html = HTML_LABEL.replace("TITLE", (StringUtils.isNotEmpty(this.title) ? this.title : "")); + String creators = this.getCreatorsAsString(); + html = html.replace("AUTHOR", (creators != null) ? " " + creators + "." : ""); + html = html.replace("PUBLISHER", (publishing != null) ? " " + publishing.getPublisher() + "." : ""); + html = html.replace("DATE", (StringUtils.isNotEmpty(this.issued)? " (" + issued + ")." : "")); + html = html.replace("ID", (StringUtils.isNotEmpty(this.objid)? this.objid : "NO ID")); + return html; + } + + public String getCreatorsAsString(){ + StringBuilder sb = new StringBuilder(); + for(Creator c : creatorList){ + if(StringUtils.isNotEmpty(sb.toString())){ + sb.append(", "); + } + sb.append(c.getFamilyName() + " " + c.getGivenName()); + } + return sb.toString(); + } + + public void addCreator(Creator creator){ + this.creatorList.add(creator); + } + + public Publication(String objid){ + this.objid = objid; + } + + public List<Creator> getCreatorList() { + return creatorList; + } + + public void setCreatorList(List<Creator> creatorList) { + this.creatorList = creatorList; + } + + + public String getObjid() { + return objid; + } + + public void setObjid(String objid) { + this.objid = objid; + } + + public String getTitle() { + return title; + } + + public String getNorTitle(){ + return norTitle; + } + + public List<String> getNorAlternativeList() { + + return norAlternativeList; + } + + + public String getNorSubject() { + return norSubject; + } + + + public void setTitle(String title) { + this.title = title; + if(StringUtils.isEmpty(title)){ + this.norTitle = new String(); + }else{ + this.norTitle = NormalizerUtils.normalize(title); + } + } + + public Publishing getPublishing() { + return publishing; + } + + public void setPublishing(Publishing publishing) { + this.publishing = publishing; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + if(StringUtils.isEmpty(subject)){ + this.norSubject = new String(); + }else{ + this.norSubject = NormalizerUtils.normalize(subject); + } + } + + public String getAdditionalInformation() { + return additionalInformation; + } + + public void setAdditionalInformation(String additionalInformation) { + this.additionalInformation = additionalInformation; + } + + public Entity getEntity() { + return entity; + } + + public void setEntity(Entity entity) { + this.entity = entity; + } + + public String getIssued() { + return issued; + } + + public void setIssued(String issued) { + this.issued = issued; + } + + public List<String> getAlternativeList() { + return alternativeList; + } + + + public void setAlternativeList(List<String> alternativeList) { + this.alternativeList = alternativeList; + for(String term : alternativeList){ + this.norAlternativeList.add(NormalizerUtils.normalize(term)); + } + } + + public void addAlternative(String alternative){ + this.alternativeList.add(alternative); + this.norAlternativeList.add(NormalizerUtils.normalize(alternative)); + } + + public String getNumberOfPages() { + return numberOfPages; + } + + + public void setNumberOfPages(String numberOfPages) { + this.numberOfPages = numberOfPages; + } + + @Override + public Element toElementXMLESciDoc(Integer mode){ + Element root = new Element("publication", NS_PUBLICATION); + root.setAttribute(new Attribute("type", "http://purl.org/eprint/type/Book")); + + Element creator = new Element("creator", NS_ETERMS); + creator.setAttribute(new Attribute("role", "http://www.loc.gov/loc.terms/relators/AUT")); + for(Creator person : this.creatorList){ + creator.addContent(person.toElementXMLESciDoc(mode)); + } + root.addContent(creator); + + Element title = new Element("title", NS_DC); + title.addContent(this.title); + root.addContent(title); + + for(String s : this.alternativeList){ + Element alternative = new Element("alternative", NS_DCTERMS); + alternative.addContent(s); + root.addContent(alternative); + } + + root.addContent(this.publishing.toElementXMLESciDoc(mode)); + + + //<dcterms:issued xmlns:dcterms="http://purl.org/dc/terms/" + // xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="dcterms:W3CDTF"> + Element issued = new Element("issued", NS_DCTERMS); + issued.addNamespaceDeclaration(NS_XSI); + issued.setAttribute(new Attribute("type", "dcterms:W3CDTF", NS_XSI)); + issued.addContent(this.issued); + root.addContent(issued); + + + Element numberOfPages = new Element("total-number-of-pages", NS_ETERMS); + numberOfPages.addContent(this.numberOfPages); + root.addContent(numberOfPages); + + Element subject = new Element("subject", NS_DCTERMS); + subject.addContent(this.subject); + root.addContent(subject); + + return root; + } + + + @Override + public boolean equals(Object object) { + // TODO: Warning - this method won't work in the case the id fields are not set + if (!(object instanceof Publication)) { + return false; + } + Publication other = (Publication) object; + + if(this.objid != null && other.getObjid() != null && this.objid == other.objid) + return true; + + return false; + } + + + + @Override + public String toString(){ + return "Publication [objid="+objid+ + ", title="+ title + + ", subject="+ subject + + ", " + creatorList + + ", " + publishing + "]"; + } + + @Override + public int compareTo(Publication arg0) { + if(StringUtils.isNotEmpty(this.objid) && StringUtils.isNotEmpty(arg0.objid)){ + return this.objid.compareTo(arg0.objid); + }else if(StringUtils.isNotEmpty(this.objid)){ + return -1; + }else if(StringUtils.isNotEmpty(arg0.objid)){ + return 1; + } + return 0; + } + + public static void main(String[] args){ + try{ + + Publication pub = new Publication(null); + + Publishing publishing = new Publishing("Jorge Urzua", "Chile", "JIJI"); + pub.setPublishing(publishing); + + Creator creator0 = new Creator("Jorge Urzua", "Urzua", "Jorge"); + Creator creator1 = new Creator("Valeria Mouzas", "Mouzas", "Valeria"); + pub.getCreatorList().add(creator0); + pub.getCreatorList().add(creator1); + + pub.setIssued("1982"); + pub.getAlternativeList().add("alternative01"); + pub.getAlternativeList().add("alternative02"); + pub.getAlternativeList().add("alternative03"); + + pub.setTitle("Por Dios..."); + + XMLOutputter outputter1 = new XMLOutputter(Format.getPrettyFormat()); + outputter1.output(pub.toXMLESciDoc(null), System.out); + + }catch (Exception e) { + e.printStackTrace(); + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/bo/Publishing.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,75 @@ +package org.mpiwg.itgroup.escidoc.bo; + +import java.io.Serializable; + +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.output.Format; +import org.jdom.output.XMLOutputter; + +public class Publishing extends ESciDocConstants implements Serializable{ + private static final long serialVersionUID = 1L; + + private String publisher; + private String place; + private String edition; + + public Publishing(String publisher, String place, String edition){ + this.publisher = publisher; + this.place = place; + this.edition = edition; + } + + public String getPublisher() { + return publisher; + } + public void setPublisher(String publisher) { + this.publisher = publisher; + } + public String getPlace() { + return place; + } + public void setPlace(String place) { + this.place = place; + } + public String getEdition() { + return edition; + } + public void setEdition(String edition) { + this.edition = edition; + } + + @Override + public Element toElementXMLESciDoc(Integer mode){ + Element root = new Element("publishing-info", NS_ETERMS); + Element publisher = new Element("publisher", NS_DC); + Element place = new Element("place", NS_ETERMS); + Element edition = new Element("edition", NS_ETERMS); + + publisher.addContent(this.publisher); + place.addContent(this.place); + edition.addContent(this.edition); + + root.addContent(publisher); + root.addContent(place); + root.addContent(edition); + + return root; + } + + @Override + public String toString(){ + return "Publishing [publisher="+ publisher +", place="+ place +", edition="+ edition +"]"; + } + + public static void main(String[] args){ + try{ + Publishing c = new Publishing("Jorge Urzua", "Chile", "JIJI"); + XMLOutputter outputter1 = new XMLOutputter(Format.getPrettyFormat()); + outputter1.output(c.toXMLESciDoc(null), System.out); + }catch (Exception e) { + e.printStackTrace(); + } + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/bo/utils/SortItemByCreator.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,38 @@ +package org.mpiwg.itgroup.escidoc.bo.utils; + +import java.util.Comparator; + +import org.apache.commons.lang.StringUtils; +import org.mpiwg.itgroup.escidoc.bo.ESciDocItem; +import org.mpiwg.itgroup.escidoc.bo.Publication; + +public class SortItemByCreator implements Comparator<ESciDocItem> { + + + public int compare(ESciDocItem e1, ESciDocItem e2) { + Publication p1 = e1.getPublication(); + Publication p2 = e2.getPublication(); + + if(p1 != null && p2 != null){ + String c1 = replace(p1.getCreatorsAsString()); + String c2 = replace(p2.getCreatorsAsString()); + + if(StringUtils.isNotEmpty(c1) && StringUtils.isNotEmpty(c2)){ + return c1.compareTo(c2); + }else if(StringUtils.isNotEmpty(c1)){ + return -1; + }else if(StringUtils.isNotEmpty(c2)){ + return 1; + } + } + return 0; + } + + public static String replace(String s){ + if(StringUtils.isNotEmpty(s)){ + s = s.replace("(", ""); + s = s.replace(")", ""); + } + return s; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/bo/utils/SortItemByTitle.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,40 @@ +package org.mpiwg.itgroup.escidoc.bo.utils; + +import java.util.Comparator; + +import org.apache.commons.lang.StringUtils; +import org.mpiwg.itgroup.escidoc.bo.ESciDocItem; +import org.mpiwg.itgroup.escidoc.bo.Publication; + +public class SortItemByTitle implements Comparator<ESciDocItem>{ + + public int compare(ESciDocItem e1, ESciDocItem e2) { + Publication p1 = e1.getPublication(); + Publication p2 = e2.getPublication(); + + if(p1 != null && p2 != null){ + + String t1 = replace(p1.getNorTitle()); + String t2 = replace(p2.getNorTitle()); + + if (StringUtils.isNotEmpty(t1) && StringUtils.isNotEmpty(t2)) { + return t1.compareTo(t2); + } else if (StringUtils.isNotEmpty(t1)) { + return -1; + } else if (StringUtils.isNotEmpty(t2)) { + return 1; + } + } + System.out.println("equals titles"); + return 0; + } + + public static String replace(String s){ + if(StringUtils.isNotEmpty(s)){ + s = s.replace("(", ""); + s = s.replace(")", ""); + } + return s; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/bo/utils/SortPublicationByCreator.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,25 @@ +package org.mpiwg.itgroup.escidoc.bo.utils; + +import java.util.Comparator; + +import org.apache.commons.lang.StringUtils; +import org.mpiwg.itgroup.escidoc.bo.Publication; + +public class SortPublicationByCreator implements Comparator<Publication> { + + + public int compare(Publication e1, Publication e2) { + String creators1 = e1.getCreatorsAsString(); + String creators2 = e2.getCreatorsAsString(); + + if(StringUtils.isNotEmpty(creators1) && StringUtils.isNotEmpty(creators2)){ + return creators1.compareTo(creators2); + }else if(StringUtils.isNotEmpty(creators1)){ + return -1; + }else if(StringUtils.isNotEmpty(creators2)){ + return 1; + } + return 0; + } + +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/bo/utils/SortPublicationByTitle.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,22 @@ +package org.mpiwg.itgroup.escidoc.bo.utils; + +import java.util.Comparator; + +import org.apache.commons.lang.StringUtils; +import org.mpiwg.itgroup.escidoc.bo.Publication; + +public class SortPublicationByTitle implements Comparator<Publication> { + + public int compare(Publication e1, Publication e2) { + if (StringUtils.isNotEmpty(e1.getTitle()) && StringUtils.isNotEmpty(e2.getTitle())) { + return e1.getTitle().compareTo(e2.getTitle()); + } else if (StringUtils.isNotEmpty(e1.getTitle())) { + return -1; + } else if (StringUtils.isNotEmpty(e2.getTitle())) { + return 1; + } else { + return 0; + } + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/utils/ESciDocItemDataTable.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,163 @@ +package org.mpiwg.itgroup.escidoc.utils; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.event.ValueChangeEvent; +import javax.faces.model.SelectItem; + +import org.mpiwg.itgroup.escidoc.ESciDocCache; +import org.mpiwg.itgroup.escidoc.bo.ESciDocItem; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractBean; +import de.mpiwg.itgroup.ismi.entry.beans.AbstractISMIBean; +import de.mpiwg.itgroup.ismi.util.guiComponents.MisattributionDataTable; + +public class ESciDocItemDataTable extends AbstractBean{ + + private List<ESciDocItem> items = new ArrayList<ESciDocItem>(); + private String term; + + private boolean showDialog = false; + private AbstractISMIBean entityForm; + private MisattributionDataTable misattDataTable; + + private int sortBy = ESciDocCache.SORT_DEFAULT; + + private static List<SelectItem> sortAlternatives; + + static{ + sortAlternatives = new ArrayList<SelectItem>(); + sortAlternatives.add(new SelectItem(ESciDocCache.SORT_DEFAULT, "Id")); + sortAlternatives.add(new SelectItem(ESciDocCache.SORT_TITLE, "Title")); + sortAlternatives.add(new SelectItem(ESciDocCache.SORT_CREATOR, "Authors")); + } + + public ESciDocItemDataTable(AbstractISMIBean entityForm){ + this.entityForm = entityForm; + this.reset(); + } + + public ESciDocItemDataTable(MisattributionDataTable misattDataTable){ + this.misattDataTable = misattDataTable; + this.reset(); + } + + public void listenerSort(ValueChangeEvent event){ + if(event.getNewValue() != null) + ESciDocCache.sort(new Integer(event.getNewValue().toString()), items); + } + + public void listenerSelectRefItem(ActionEvent event){ + ESciDocItem item = (ESciDocItem)getRequestBean("refItem"); + if(item != null){ + if(entityForm != null){ + SelectedESciDocItems selectedPubs = this.entityForm.getSelectedItems(); + if(selectedPubs != null){ + if(!selectedPubs.addESciDocItem((ESciDocItem)item.clone())){ + getSessionBean().addGeneralMsg("The reference was already selected."); + } + } + }else if(misattDataTable != null){ + misattDataTable.setESciDocItem(item); + } + this.showDialog = false; + } + } + + public void listenerEditItem(ActionEvent event){ + ESciDocItem item = (ESciDocItem)getRequestBean("refItem"); + getSessionBean().geteSciDocForm().setItem(item); + this.term = null; + this.items = null; + this.showDialog = false; + } + + public void listenerCreateReference(){ + getSessionBean().geteSciDocForm().createItem(); + this.close(); + } + + public void listenerReset(ActionEvent event){ + this.reset(); + } + + public void listenerFilter(ActionEvent event){ + this.filter(); + } + + public void listenerOpen(ActionEvent event){ + this.open(); + } + + public void open(){ + this.reset(); + this.showDialog = true; + } + + public void listenerClose(ActionEvent event){ + this.close(); + } + + public void close(){ + this.term = null; + this.items = null; + this.showDialog = false; + } + + public void reset(){ + /* + this.term = null; + List<ESciDocItem> list = this.getAppBean().getRefCache().getAllItems(sortBy); + if(list != null){ + this.items = new ArrayList<ESciDocItem>(list); + }else{ + this.items = new ArrayList<ESciDocItem>(); + }*/ + } + + public void filter(){ + this.items = this.getAppBean().getRefCache().searchItem(term, sortBy); + } + public int getItemsSize(){ + if(items == null) + return 0; + return items.size(); + } + + public List<ESciDocItem> getItems() { + return items; + } + + public void setItems(List<ESciDocItem> items) { + this.items = items; + } + + public String getTerm() { + return term; + } + + public void setTerm(String term) { + this.term = term; + } + + public boolean isShowDialog() { + return showDialog; + } + + public void setShowDialog(boolean showDialog) { + this.showDialog = showDialog; + } + public int getSortBy() { + return sortBy; + } + + public void setSortBy(int sortBy) { + this.sortBy = sortBy; + } + + public List<SelectItem> getSortAlternatives() { + return sortAlternatives; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/utils/SelectedESciDocItems.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,55 @@ +package org.mpiwg.itgroup.escidoc.utils; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.mpiwg.itgroup.escidoc.bo.ESciDocItem; + + +public class SelectedESciDocItems implements Serializable{ + + private static final long serialVersionUID = -756497439159524677L; + private transient List<ESciDocItem> list = new ArrayList<ESciDocItem>(); + private Map<String, Boolean> map = new HashMap<String, Boolean>(); + + public boolean addESciDocItem(ESciDocItem pub) { + if (!map.containsKey(pub.getPublication().getObjid())) { + this.list.add(pub); + this.map.put(pub.getPublication().getObjid(), false); + return true; + } + return false; + } + + public void removeById(String id) { + ESciDocItem pp = null; + for (ESciDocItem pub : this.list) { + if (id.equals(pub.getPublication().getObjid())) { + pp = pub; + break; + } + } + this.list.remove(pp); + this.map.remove(id); + } + + public List<ESciDocItem> getList() { + return list; + } + + public void setList(List<ESciDocItem> list) { + this.list = list; + } + + public Map<String, Boolean> getMap() { + return map; + } + + public void setMap(Map<String, Boolean> map) { + this.map = map; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/escidoc/web/ESciDocItemForm.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,199 @@ +package org.mpiwg.itgroup.escidoc.web; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ActionEvent; +import javax.faces.model.SelectItem; + +import org.apache.commons.lang.StringUtils; +import org.mpiwg.itgroup.escidoc.bo.Creator; +import org.mpiwg.itgroup.escidoc.bo.ESciDocItem; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractBean; +import de.mpiwg.itgroup.ismi.utils.SelectableObject; + +public class ESciDocItemForm extends AbstractBean { + + private ESciDocItem item; + private String itemId; + + private List<SelectableObject> creatorList = new ArrayList<SelectableObject>(); + private List<SelectableObject> alternativeNameList = new ArrayList<SelectableObject>(); + + + private boolean visible; + + public ESciDocItemForm(){ + this.reset(); + } + + private void reset(){ + this.item = new ESciDocItem(); + this.itemId = null; + this.creatorList = new ArrayList<SelectableObject>(); + this.alternativeNameList = new ArrayList<SelectableObject>(); + } + + public void listenerCleanForm(ActionEvent event){ + this.reset(); + } + + public void listenerDelete(ActionEvent event){ + try { + + getAppBean().getRefCache().deleteItem(item, getSessionBean().getUsername()); + + addGeneralMsg("The publication has been deleted successfully."); + this.visible = false; + this.item = null; + } catch (Exception e) { + addErrorMsg(e.getMessage()); + e.printStackTrace(); + } + } + + public void listenerSave(ActionEvent event){ + + List<String> alternativeNames = new ArrayList<String>(); + for(SelectableObject so : this.alternativeNameList){ + alternativeNames.add((String)so.getObj()); + } + List<Creator> creators = new ArrayList<Creator>(); + for(SelectableObject so : this.creatorList){ + creators.add((Creator)so.getObj()); + } + this.item.getPublication().setAlternativeList(alternativeNames); + this.item.getPublication().setCreatorList(creators); + try { + + this.item = getAppBean().getRefCache().saveItem(item, getSessionBean().getUsername()); + + this.setItem(getAppBean().getRefCache().getItem(item.getObjId())); + addGeneralMsg("The publication has been saved successfully."); + } catch (Exception e) { + addErrorMsg(e.getMessage()); + e.printStackTrace(); + } + } + + public String getButtonSaveLabel(){ + if(StringUtils.isEmpty(item.getObjId())){ + return "Create"; + } + return "Save"; + } + + public boolean isDisplayDeleteBtn(){ + if(item == null || StringUtils.isEmpty(item.getObjId())){ + return false; + } + return true; + } + + public void listenerReloadItem(ActionEvent event){ + if(StringUtils.isNotEmpty(itemId)){ + this.item = getAppBean().getRefCache().getItem(itemId); + + if(item == null){ + addGeneralMsg("No item found " + itemId); + }else{ + this.item = (ESciDocItem)this.item.clone(); + } + }else{ + addGeneralMsg("Item id can not be empty"); + } + } + + public void listenerAddAlternativeName(ActionEvent event){ + this.alternativeNameList.add(new SelectableObject(new String("..."))); + } + + public void listenerRemoveAlternativeName(ActionEvent event){ + List<SelectableObject> toDelete = new ArrayList<SelectableObject>(); + for(SelectableObject so : this.alternativeNameList){ + if(so.isSelected()){ + toDelete.add(so); + } + } + for(SelectableObject so : toDelete){ + this.alternativeNameList.remove(so); + } + } + + public void listenerAddCreator(ActionEvent event){ + this.creatorList.add(new SelectableObject(new Creator("completeName", "familyName", "givenName"))); + } + + public void listenerRemoveCreator(ActionEvent event){ + List<SelectableObject> toDelete = new ArrayList<SelectableObject>(); + for(SelectableObject so : this.creatorList){ + if(so.isSelected()){ + toDelete.add(so); + } + } + for(SelectableObject so : toDelete){ + this.creatorList.remove(so); + } + } + + public void listenerClose(ActionEvent event){ + this.visible = false; + this.item = null; + } + + public ESciDocItem getItem() { + return item; + } + + public void createItem(){ + this.reset(); + this.visible = true; + } + + public void setItem(ESciDocItem item) { + this.reset(); + try { + + this.item = getAppBean().getRefCache().getItemFromServer(item.getObjId()); + this.visible = true; + + for(String s : this.item.getPublication().getAlternativeList()){ + this.alternativeNameList.add(new SelectableObject(s)); + } + + for(Creator creator : this.item.getPublication().getCreatorList()){ + this.creatorList.add(new SelectableObject(creator)); + } + + } catch (Exception e) { + e.printStackTrace(); + addGeneralMsg(e.getMessage()); + } + } + + public boolean isVisible() { + return visible; + } + + public void setVisible(boolean visible) { + this.visible = visible; + } + + public List<SelectableObject> getCreatorList() { + return creatorList; + } + + public void setCreatorList(List<SelectableObject> creatorList) { + this.creatorList = creatorList; + } + + public List<SelectableObject> getAlternativeNameList() { + return alternativeNameList; + } + + public void setAlternativeNameList(List<SelectableObject> alternativeNameList) { + this.alternativeNameList = alternativeNameList; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/geonames/GeonameForm.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,225 @@ +package org.mpiwg.itgroup.geonames; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.ActionEvent; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONObject; +import org.mpi.openmind.repository.bo.Attribute; +import org.mpi.openmind.repository.bo.Entity; +import org.mpi.openmind.repository.utils.NormalizerUtils; +import org.mpiwg.itgroup.geonames.bo.Geoname; + +import de.mpiwg.itgroup.ismi.entry.beans.AbstractBean; + +public class GeonameForm extends AbstractBean{ + + private static String GEONAME_ID = "geoname_id"; + + + private String searchPlaceTerm; + private List<Entity> places; + private Entity selectedPlace; + + private String searchGeoTerm; + private List<Geoname> geonames; + private Geoname selectedGeoname; + private JSONObject selectedJSONGeoname; + + private boolean showGeonamePopup = false; + + public void listenerSelectPlace(ActionEvent event){ + Entity place = (Entity)getRequestBean("place"); + if(place != null){ + this.redirect(null, "?placeId=" + place.getId()); + loadPlace(place); + } + } + + public void loadPlace(Entity place){ + this.selectedPlace = place; + if(place != null){ + this.searchGeoTerm = this.selectedPlace.getOwnValue(); + this.searchGeonames(selectedPlace.getOwnValue()); + } + } + + public void listenerLoadAllPlaces(ActionEvent event){ + this.loadPlaces(null); + } + + public void listenerSearchPlaces(ActionEvent event){ + this.loadPlaces(this.searchPlaceTerm); + } + /* + public void listenerOpenPopup(ActionEvent event){ + this.selectedPlace = (Entity)getRequestBean("place"); + this.searchGeonames(selectedPlace.getOwnValue()); + this.showGeonamePopup = true; + }*/ + + public void listenerCloseSearchPopup(ActionEvent event){ + this.closeSearchPopup(); + } + + public void listenerSearchGeonames(ActionEvent event){ + this.searchGeonames(this.searchGeoTerm); + } + + public String actionDisplayGeonameMap(){ + this.selectedGeoname = (Geoname)getRequestBean("geoname"); + if(selectedGeoname != null){ + try { + this.selectedJSONGeoname = GeonameUtils.getJSONGeoname(selectedGeoname.getId()); + } catch (Exception e) { + addErrorMsg(e.getMessage()); + e.printStackTrace(); + } + } + return "geo_map"; + } + + public void loadPlaces(String term){ + + String nTerm = NormalizerUtils.normalize(term); + + System.out.println("Loading place in GeonameForm"); + List<Entity> list = getAppBean().getWrapper().getEntitiesByDef("PLACE"); + this.places = new ArrayList<Entity>(); + for(Entity pl : list){ + Attribute att = getAppBean().getWrapper().getAttributeByName(pl.getId(), GEONAME_ID); + if(att == null || StringUtils.isEmpty(att.getValue())){ + if(StringUtils.isEmpty(nTerm)){ + this.places.add(pl); + }else if(pl.getNormalizedOwnValue().contains(nTerm)){ + this.places.add(pl); + } + } + } + } + + private void searchGeonames(String term){ + + try { + this.searchGeoTerm = term; + this.geonames = GeonameUtils.search(searchGeoTerm); + } catch (Exception e) { + addErrorMsg(e.getMessage()); + e.printStackTrace(); + } + } + + public void listenerAssignGeoname2Place(ActionEvent event){ + + this.selectedGeoname = (Geoname)getRequestBean("geoname"); + + if(this.selectedGeoname != null){ + try { + if(selectedPlace.isLightweight()){ + this.selectedPlace = getAppBean().getWrapper().getEntityContent(selectedPlace); + } + + if(this.selectedPlace.containsAttribute(GEONAME_ID)){ + this.selectedPlace.getAttributeByName(GEONAME_ID).setValue(this.selectedGeoname.getId().toString()); + }else{ + this.selectedPlace.addAttribute(new Attribute(GEONAME_ID, "geoname-id", this.selectedGeoname.getId().toString())); + } + + getAppBean().getWrapper().saveEntity(this.selectedPlace, getSessionBean().getUsername()); + + addGeneralMsg("The geoname " + selectedGeoname.getId() + " has been assigned successfully to the place " + + selectedPlace.getOwnValue() + " [ID=" +selectedPlace.getId() + "]"); + + this.loadPlaces(null); + this.closeSearchPopup(); + } catch (Exception e) { + addErrorMsg(e.getMessage()); + e.printStackTrace(); + } + }else{ + System.err.println("AHHHHH"); + } + } + + private void closeSearchPopup(){ + this.showGeonamePopup = false; + this.searchGeoTerm = null; + this.geonames = null; + this.selectedPlace = null; + this.redirect(null, ""); + + } + + public String getSearchGeoTerm() { + return searchGeoTerm; + } + + public void setSearchGeoTerm(String searchGeoTerm) { + this.searchGeoTerm = searchGeoTerm; + } + + public List<Entity> getPlaces() { + return places; + } + + public void setPlaces(List<Entity> places) { + this.places = places; + } + + public Entity getSelectedPlace() { + return selectedPlace; + } + + public void setSelectedPlace(Entity selectedPlace) { + this.selectedPlace = selectedPlace; + } + + public int getGeonamesSize(){ + if(geonames == null) + return 0; + return geonames.size(); + } + + public List<Geoname> getGeonames() { + return geonames; + } + + public void setGeonames(List<Geoname> geonames) { + this.geonames = geonames; + } + + public Geoname getSelectedGeoname() { + return selectedGeoname; + } + + public void setSelectedGeoname(Geoname selectedGeoname) { + this.selectedGeoname = selectedGeoname; + } + + public boolean isShowGeonamePopup() { + return showGeonamePopup; + } + + public void setShowGeonamePopup(boolean showGeonamePopup) { + this.showGeonamePopup = showGeonamePopup; + } + + public JSONObject getSelectedJSONGeoname() { + return selectedJSONGeoname; + } + + public void setSelectedJSONGeoname(JSONObject selectedJSONGeoname) { + this.selectedJSONGeoname = selectedJSONGeoname; + } + + public String getSearchPlaceTerm() { + return searchPlaceTerm; + } + + public void setSearchPlaceTerm(String searchPlaceTerm) { + this.searchPlaceTerm = searchPlaceTerm; + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/geonames/GeonameUtils.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,149 @@ +package org.mpiwg.itgroup.geonames; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URL; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.mpiwg.itgroup.geonames.bo.Geoname; + +public class GeonameUtils { + + public static final String GEONAME_SEARCH = "https://openmind-ismi-dev.mpiwg-berlin.mpg.de/geonames/service?method=search&maxRows=1000&mode=json&q="; + public static final String GEONAME_GET_BY_ID = + "https://openmind-ismi-dev.mpiwg-berlin.mpg.de/geonames/service?method=getGeoname&mode=json&geonameId="; + private static final int BUFFER_SIZE = 1024; + + public static List<Geoname> search(String term) throws Exception{ + List<Geoname> list = new ArrayList<Geoname>(); + + JSONObject jsonRS = JSONFromURL(GEONAME_SEARCH + term); + + JSONArray jsonGeoList = jsonRS.getJSONArray("geonames"); + for(int i=0; i < jsonGeoList.length(); i++){ + list.add(json2Geoname(jsonGeoList.getJSONObject(i))); + } + return list; + } + + public static JSONObject getJSONGeoname(Integer id) throws Exception{ + JSONObject jsonRS = JSONFromURL(GEONAME_GET_BY_ID + id); + + JSONArray jsonGeoList = jsonRS.getJSONArray("geonames"); + if(jsonGeoList.length() > 0) + return jsonGeoList.getJSONObject(0); + return null; + } + + //gets the JSONObject at the specified URL + public static JSONObject JSONFromURL(String url) throws Exception { + trustAll(); + URL realURL = new URL(url); + BufferedReader reader = read(realURL); + int charsRead; + char[] copyBuffer = new char[BUFFER_SIZE]; + StringBuffer sb = new StringBuffer(); + while ((charsRead = reader.read(copyBuffer, 0, BUFFER_SIZE)) != -1) + sb.append(copyBuffer, 0, charsRead); + JSONObject result = new JSONObject( sb.toString() ); + return result; + } + + public static Geoname json2Geoname(JSONObject json){ + Geoname geo = new Geoname(); + try { + + geo.setId(json.getInt("geonameId")); + + if(json.has("lng")) + geo.setLng(json.getDouble("lng")); + + if(json.has("lat")) + geo.setLat(json.getDouble("lat")); + + if(json.has("countryCode")) + geo.setCountryCode(json.getString("countryCode")); + + if(json.has("countryName")) + geo.setCountryName(json.getString("countryName")); + + if(json.has("name")) + geo.setName(json.getString("name")); + + if(json.has("toponymName")) + geo.setToponymName(json.getString("toponymName")); + + if(json.has("population")) + geo.setPopulation(json.getInt("population")); + + if(json.has("alternateNames")){ + JSONArray array = json.getJSONArray("alternateNames"); + for(int i=0; i<array.length(); i++){ + geo.getAlternateNames().add(array.getString(i)); + } + } + + JSONObject jsonCls = json.getJSONObject("class"); + + if(jsonCls.has("fcl")) + geo.setfCls(jsonCls.getString("fcl")); + if(jsonCls.has("fcode")) + geo.setfCode(jsonCls.getString("fcode")); + if(jsonCls.has("description")) + geo.setClsDescription(jsonCls.getString("description")); + if(jsonCls.has("name")) + geo.setClsName(jsonCls.getString("name")); + + } catch (JSONException e) { + e.printStackTrace(); + } + return geo; + } + + //allows us to access https connections without verifying the certificate + public static void trustAll() throws Exception { + // Create a trust manager that does not validate certificate chains + TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + public void checkClientTrusted(X509Certificate[] certs, String authType) { + } + public void checkServerTrusted(X509Certificate[] certs, String authType) { + } + } + }; + + // Install the all-trusting trust manager + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + + // Create all-trusting host name verifier + HostnameVerifier allHostsValid = new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + + // Install the all-trusting host verifier + HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); + } + + //get a BufferedReader for a webpage from its URL + public static BufferedReader read(URL url) throws Exception { + return new BufferedReader(new InputStreamReader(url.openStream(),"utf-8")); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpiwg/itgroup/geonames/bo/Geoname.java Wed Oct 29 14:00:28 2014 +0000 @@ -0,0 +1,175 @@ +package org.mpiwg.itgroup.geonames.bo; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +import org.apache.commons.lang.StringUtils; + +public class Geoname implements Serializable{ + private static final long serialVersionUID = -3256085837090516807L; + + private Integer id; + private List<String> alternateNames = new ArrayList<String>(); + private String countryName; + private String toponymName; + private String name; + private String countryCode; + private Double lng; + private Double lat; + private Integer population; + + private String fCls; + private String fCode; + private String clsDescription; + private String clsName; + + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } + + public List<String> getMoreInfo(){ + + List<String> rs = new ArrayList<String>(); + rs.add("Lat/Lng: " + lat + "/" + lng); + rs.add("Population: " + population); + rs.add("Class name: " + clsName); + /* + rs.add("Class description: " + clsDescription); + rs.add("Class name: " + clsName); + rs.add("Class name: " + clsName); + rs.add(fCls + ", " + fCode); + */ + /* + if(StringUtils.isNotEmpty(countryName)){ + if(sb.length() > 0) + sb.append(", "); + sb.append("Country: " + countryName); + } + if(StringUtils.isNotEmpty(countryCode)){ + if(sb.length() > 0) + sb.append(", "); + sb.append("Country code: " + countryCode); + }*/ + + return rs; + } + + public List<String> getSomeAlternateName(){ + List<String> rs = new ArrayList<String>(); + + if(this.alternateNames.size() > 0){ + int counter = 0; + Queue<String> queue = new LinkedList<String>(this.alternateNames); + + int namesPerLine = 3; + + while(!queue.isEmpty() && (namesPerLine * 5) > counter){ + + if(counter % namesPerLine == 0){ + rs.add(queue.poll()); + }else{ + String name = rs.remove(rs.size() - 1); + name += ", " + queue.poll(); + rs.add(name); + } + counter++; + } + } + + return rs; + } + + public String getAlternateNamesAsString(){ + StringBuilder sb = new StringBuilder(); + int count = 0; + for(String s : this.alternateNames){ + if(count > 0){ + sb.append(", "); + } + sb.append(s); + count++; + } + return sb.toString(); + } + + public List<String> getAlternateNames() { + return alternateNames; + } + + public void setAlternateNames(List<String> alternateNames) { + this.alternateNames = alternateNames; + } + public String getCountryName() { + return countryName; + } + public void setCountryName(String countryName) { + this.countryName = countryName; + } + public String getToponymName() { + return toponymName; + } + public void setToponymName(String toponymName) { + this.toponymName = toponymName; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getCountryCode() { + return countryCode; + } + public void setCountryCode(String countryCode) { + this.countryCode = countryCode; + } + public Double getLng() { + return lng; + } + public void setLng(Double lng) { + this.lng = lng; + } + public Double getLat() { + return lat; + } + public void setLat(Double lat) { + this.lat = lat; + } + public Integer getPopulation() { + return population; + } + public void setPopulation(Integer population) { + this.population = population; + } + public String getfCls() { + return fCls; + } + public void setfCls(String fCls) { + this.fCls = fCls; + } + + public String getfCode() { + return fCode; + } + public void setfCode(String fCode) { + this.fCode = fCode; + } + public String getClsDescription() { + return clsDescription; + } + public void setClsDescription(String clsDescription) { + this.clsDescription = clsDescription; + } + public String getClsName() { + return clsName; + } + public void setClsName(String clsName) { + this.clsName = clsName; + } +}