Example usage for org.dom4j DocumentHelper createElement

List of usage examples for org.dom4j DocumentHelper createElement

Introduction

In this page you can find the example usage for org.dom4j DocumentHelper createElement.

Prototype

public static Element createElement(String name) 

Source Link

Usage

From source file:org.neuclear.xml.AbstractElementProxy.java

License:LGPL

protected AbstractElementProxy(final QName qname) {
    this.element = DocumentHelper.createElement(qname);
}

From source file:org.neuclear.xml.AbstractElementProxy.java

License:LGPL

/**
 * Adds another Element with the given QName to this Element
 * //from  w  w w .  java  2 s  . com
 * @param child 
 */
protected final Element addElement(final QName child) {
    Element element = DocumentHelper.createElement(child);
    addElement(element);
    return element;
}

From source file:org.neuclear.xml.AbstractElementProxy.java

License:LGPL

/**
 * Adds another Element with the given name and the same Namespace as this element to this element.
 * //from w  ww  . j a  v a  2  s.c  o m
 * @param child 
 */
protected final Element addElement(final String child) {
    Element element = DocumentHelper.createElement(createQName(child));
    addElement(element);
    return element;
}

From source file:org.nuclos.server.transfer.ejb3.XmlExportFacadeBean.java

License:Open Source License

/**
 * Exports a GO with all Depandents/*from  w  ww.  j  a v a  2 s  .  c  om*/
 *
 * @param sEntityName
 * @param entityId
 * @param parent
 * @throws CommonFinderException
 * @throws CommonFinderException
 * @throws CommonFinderException
 * @throws CommonPermissionException
 * @throws CommonPermissionException
 * @throws IOException
 * @throws IOException
 * @throws CreateException
 * @throws CommonCreateException
 * @throws NuclosBusinessRuleException
 */
private void exportGOEntity(String sEntityName, Object entityId, Element parent, Boolean deepexport,
        Boolean bExportDependants, Boolean bImportData) throws CommonFinderException, CommonPermissionException,
        IOException, CommonCreateException, NuclosBusinessRuleException {
    Element entity = DocumentHelper.createElement("entity");

    // get id for the exported Module on the source system
    Integer moduleId = modules.getModuleIdByEntityName(sEntityName);

    info("Export GenericObject Entity: " + sEntityName + " ModuleId: " + moduleId + " Entity-Id: " + entityId);

    GenericObjectVO govo;
    try {
        govo = getGenericObjectFacade().get((Integer) entityId);
    } catch (Exception e) {
        String sMessage = MessageFormat.format(
                localeFacade.getResourceById(localeFacade.getUserLocale(), "xmlexport.error.creating.entity"),
                sEntityName, entityId, e);
        //"Modul-Entit\u00e4t ["+sEntityName+"] mit der ID ["+entityId+"] konnte nicht exportiert werden. "+e;
        getProtocolFacade().writeExportImportLogEntry(iProtocolId,
                XmlExportImportHelper.EXPIMP_MESSAGE_LEVEL_ERROR, XmlExportImportHelper.EXPIMP_ACTION_READ,
                sMessage, iActionNumber++);
        throw new NuclosFatalException(StringUtils
                .getParameterizedExceptionMessage("xmlexport.error.creating.entity", sEntityName, entityId, e));
    }

    Collection<DynamicAttributeVO> attcol = govo.getAttributes();
    Iterator<DynamicAttributeVO> attrIt = attcol.iterator();

    entity.addAttribute("id", entityId.toString());
    entity.addAttribute("type", "genericObject");
    entity.addAttribute("name", sEntityName);

    DynamicAttributeVO dynamicAttributeVO = govo.getAttribute(NuclosEOField.PROCESS.getMetaData().getField(),
            AttributeCache.getInstance());
    String sProcess = (dynamicAttributeVO == null) ? ""
            : dynamicAttributeVO.getCanonicalValue(AttributeCache.getInstance());

    entity.addAttribute("process", (sProcess == null) ? "" : sProcess);

    entity.addAttribute("import", bImportData.toString());

    if (govo.getParentId() != null) {
        entity.addAttribute("parentId", govo.getParentId().toString());
    } else {
        entity.addAttribute("parentId", "null");
    }
    entity.addAttribute("deleted", String.valueOf(govo.isRemoved()));

    exportedIds.add(new Pair<String, Integer>(sEntityName, (Integer) entityId));

    while (attrIt.hasNext()) {
        DynamicAttributeVO davo = attrIt.next();
        AttributeCVO attrCVO = genericObjectMetaDataCache.getAttribute(davo.getAttributeId());
        Element attr2 = entity.addElement("attribute");
        attr2.addAttribute("id", (davo.getId() == null) ? "0" : davo.getId().toString());
        attr2.addAttribute("name", attrCVO.getName());
        if (attrCVO.getExternalEntity() != null) {
            attr2.addAttribute("hasReference", "true");
            Element attrval = attr2.addElement("value");
            if (attrCVO.getJavaClass().getName().equals("java.util.Date")) {
                attrval.setText(dateFormat.format((Date) davo.getValue()));
            } else {
                attrval.setText(davo.getValue().toString());
            }

            Element attrref = attr2.addElement("referenceId");
            attrref.setText(davo.getValueId().toString());
            if (deepexport) {
                xmlExportHelper(attrCVO.getExternalEntity(), davo.getValueId(), parent, deepexport,
                        bExportDependants, bImportData);
            } else {
                xmlExportHelper(attrCVO.getExternalEntity(), davo.getValueId(), parent, deepexport, false,
                        false);
            }
        } else {
            attr2.addAttribute("hasReference", "false");
            Element attrval = attr2.addElement("value");
            String sValue = davo.getCanonicalValue(AttributeCache.getInstance());
            attrval.setText((sValue == null) ? "" : sValue);

            // check whether attribute has a value list
            if (!attrCVO.getValues().isEmpty()) {
                Element attrvalId = attr2.addElement("valueId");
                Integer iValueId = davo.getValueId();
                attrvalId.setText((iValueId == null) ? "" : iValueId.toString());
            }
        }
    }
    parent.add(entity);

    String sMessage = MessageFormat.format(
            localeFacade.getResourceById(localeFacade.getUserLocale(), "xmlexport.message.successful"),
            sEntityName, entityId);
    //"Module-entity ["+sEntityName+"] with the ID ["+entityId+"] successful exported.";
    info(sMessage);
    getProtocolFacade().writeExportImportLogEntry(iProtocolId, XmlExportImportHelper.EXPIMP_MESSAGE_LEVEL_INFO,
            XmlExportImportHelper.EXPIMP_ACTION_READ, sMessage, iActionNumber++);

    // subform
    Map<EntityAndFieldName, String> subformtree_with_fkeys = new HashMap<EntityAndFieldName, String>();
    if (bImportData) {
        if (!mpGoSubFormsWithForeignKeys.containsKey(govo.getModuleId())) {
            for (Integer iLayoutId : genericObjectMetaDataCache.getLayoutIdsByModuleId(govo.getModuleId(),
                    false)) {
                LayoutFacadeLocal layoutFacade = ServerServiceLocator.getInstance()
                        .getFacade(LayoutFacadeLocal.class);
                Map<EntityAndFieldName, String> subformtree = layoutFacade
                        .getSubFormEntityAndParentSubFormEntityNamesByLayoutId(iLayoutId);
                for (EntityAndFieldName eafn : subformtree.keySet()) {
                    String sParentEntity = sEntityName;
                    if (subformtree.get(eafn) != null) {
                        sParentEntity = subformtree.get(eafn);
                    }

                    String s1 = eafn.getEntityName();
                    String s2 = XmlExportImportHelper.getForeignKeyFieldName(sParentEntity, eafn.getFieldName(),
                            eafn.getEntityName());
                    subformtree_with_fkeys.put(new EntityAndFieldName(s1, s2), subformtree.get(eafn));
                }
            }
            mpGoSubFormsWithForeignKeys.put(govo.getModuleId(), subformtree_with_fkeys);
        }

        //special handling for relation entity
        subformtree_with_fkeys.put(new EntityAndFieldName(NuclosEntity.GENERICOBJECTRELATION, "source"), null);
        subformtree_with_fkeys.put(new EntityAndFieldName(NuclosEntity.GENERICOBJECTRELATION, "destination"),
                null);

        mpMdSubFormsWithForeignKeys.put(sEntityName, subformtree_with_fkeys);

        exportMDSubform(mpGoSubFormsWithForeignKeys.get(govo.getModuleId()), null, entityId, parent,
                deepexport);
    }
}

From source file:org.nuclos.server.transfer.ejb3.XmlExportFacadeBean.java

License:Open Source License

/**
 * Exports a MD Entity with all Dependants
 *
 * @param sEntityName//from  w w  w .  j  a  va  2  s. c o m
 * @param entityId
 * @param parent
 * @throws CommonFinderException
 * @throws CommonFinderException
 * @throws CommonPermissionException
 * @throws CommonPermissionException
 * @throws IOException
 * @throws IOException
 * @throws CreateException
 * @throws CommonCreateException
 * @throws NuclosBusinessRuleException
 */
private void exportMDEntity(String sEntityName, Object entityId, Element parent, Boolean deepexport,
        Boolean bExportDependants, Boolean bImportData) throws CommonFinderException, CommonPermissionException,
        IOException, CommonCreateException, NuclosBusinessRuleException {
    info("Export MasterData Entity: " + sEntityName + " Entity-Id: " + entityId);

    Element entity = DocumentHelper.createElement("entity");

    MasterDataVO md;
    try {
        md = getMasterDataFacade().get(sEntityName, entityId);
    } catch (Exception e) {
        String sMessage = MessageFormat.format(
                localeFacade.getResourceById(localeFacade.getUserLocale(), "xmlexport.error.creating.mdentity"),
                sEntityName, entityId, e);
        //"Master data entity ["+sEntityName+"] with the ID ["+entityId+"] could not be exported. "+e;
        getProtocolFacade().writeExportImportLogEntry(iProtocolId,
                XmlExportImportHelper.EXPIMP_MESSAGE_LEVEL_ERROR, XmlExportImportHelper.EXPIMP_ACTION_READ,
                sMessage, iActionNumber++);
        throw new NuclosFatalException(StringUtils.getParameterizedExceptionMessage(
                "xmlexport.error.creating.mdentity", sEntityName, entityId, e));
    }

    MasterDataMetaVO mdm = getMasterDataFacade().getMetaData(sEntityName);
    List<MasterDataMetaFieldVO> metafields = mdm.getFields();

    Iterator<MasterDataMetaFieldVO> fieldIt = metafields.iterator();
    MasterDataMetaFieldVO field;

    entity.addAttribute("id", entityId.toString());
    entity.addAttribute("type", "masterdata");
    entity.addAttribute("name", sEntityName);
    entity.addAttribute("import", bImportData.toString());
    Object objFieldValue;

    //exportedIds.add(new Pair<String, Integer>(sEntityName, (Integer)entityId));

    while (fieldIt.hasNext()) {
        field = fieldIt.next();

        // case 1:1 referenceces
        if (field.getForeignEntity() != null) {
            objFieldValue = md.getField(field.getFieldName() + "Id");
            if (objFieldValue != null) {
                Element attr = entity.addElement(field.getFieldName() + "Id");
                attr.setText(objFieldValue.toString());

                if (deepexport) {
                    xmlExportHelper(field.getForeignEntity(), objFieldValue, parent, deepexport,
                            bExportDependants, bImportData);
                } else {
                    // special handling for statemodel - if the statemodel is exported, then set the import flag to true
                    // for all state entities
                    if (NuclosEntity.ROLESUBFORM.checkEntityName(sEntityName)
                            && NuclosEntity.STATE.checkEntityName(field.getForeignEntity())
                            || NuclosEntity.ROLEATTRIBUTEGROUP.checkEntityName(sEntityName)
                                    && NuclosEntity.STATE.checkEntityName(field.getForeignEntity())
                            || NuclosEntity.STATETRANSITION.checkEntityName(sEntityName)
                                    && NuclosEntity.STATE.checkEntityName(field.getForeignEntity())) {
                        xmlExportHelper(field.getForeignEntity(), objFieldValue, parent, deepexport, false,
                                true);
                    }
                    // special handling for entity genericobjectrelation, because the foreignkey entity is set to generalsearch
                    // for the fields source and destination and therefore it's not possible to determine the corresponding foreign entity
                    else if (NuclosEntity.GENERICOBJECTRELATION.checkEntityName(sEntityName)
                            && (field.getFieldName().equals("source")
                                    || field.getFieldName().equals("destination"))) {
                        Integer iModuleId = getGenericObjectFacade().get((Integer) objFieldValue).getModuleId();
                        String sForeignEntityName = Modules.getInstance().getEntityNameByModuleId(iModuleId);
                        xmlExportHelper(sForeignEntityName, objFieldValue, parent, deepexport, false, false);
                    }
                }
            }
        }
        // case no references
        else {
            File expimpDir = NuclosSystemParameters.getDirectory(NuclosSystemParameters.EXPORT_IMPORT_PATH);
            File expimpResourceDir = new File(expimpDir, "" + today.getTime() + "/ressource");

            objFieldValue = md.getField(field.getFieldName());
            Element attr2 = entity.addElement(field.getFieldName());
            if (field.getJavaClass().getName().equals("java.util.Date") && objFieldValue != null) {
                attr2.setText(dateFormat.format((Date) objFieldValue));
            } else if (field.getJavaClass().getName().equals("java.lang.Object") && objFieldValue != null) {
                String sFileName = sEntityName + "_" + field.getFieldName() + "_" + entityId;

                XmlExportImportHelper.writeObjectToFile(objFieldValue, expimpResourceDir, sFileName);
                attr2.setText(sFileName);
            } else if (objFieldValue != null) {
                if (objFieldValue.getClass().getName().equals("org.nuclos.server.report.ByteArrayCarrier")) {
                    ByteArrayCarrier bac = (ByteArrayCarrier) objFieldValue;
                    attr2.setText(Base64.encode(bac.getData()));
                } else if (objFieldValue.getClass().getName()
                        .equals("org.nuclos.server.resource.valueobject.ResourceFile")) {
                    ResourceFile rf = (ResourceFile) objFieldValue;
                    attr2.addAttribute("filename", StringUtils.emptyIfNull(rf.getFilename()));
                    attr2.addAttribute("documentFileId",
                            rf.getDocumentFileId() == null ? "" : rf.getDocumentFileId().toString());
                    attr2.setText(Base64.encode(rf.getContents()));
                } else if (objFieldValue instanceof byte[]) {
                    attr2.setText(Base64.encode((byte[]) objFieldValue));
                } else
                    attr2.setText(objFieldValue.toString());
            } else {
                attr2.setText("");
            }

            String sFileName = "";
            // copy Document Files if available
            if (objFieldValue != null && !objFieldValue.equals("") && (field.getJavaClass().getName()
                    .equals("org.nuclos.server.genericobject.valueobject.GenericObjectDocumentFile"))) {
                try {
                    File documentDir = NuclosSystemParameters
                            .getDirectory(NuclosSystemParameters.DOCUMENT_PATH);

                    if (field.getJavaClass().getName()
                            .equals("org.nuclos.server.genericobject.valueobject.GenericObjectDocumentFile")) {
                        sFileName = md.getId() + "." + md.getField("file").toString();
                    }

                    XmlExportImportHelper.copyDocumentFile(documentDir, expimpResourceDir, sFileName,
                            md.getId(), md.getId());
                } catch (IOException e) {
                    String sMessage = MessageFormat.format(
                            localeFacade.getResourceById(localeFacade.getUserLocale(),
                                    "xmlexport.error.copying.file"),
                            md.getField("filename").toString(), sEntityName, entityId, e);
                    //"Error copying the file ["+md.getField("filename").toString()+"] of the master data entity ["+sEntityName+"] with the Id ["+entityId+"]";
                    getProtocolFacade().writeExportImportLogEntry(iProtocolId,
                            XmlExportImportHelper.EXPIMP_MESSAGE_LEVEL_ERROR,
                            XmlExportImportHelper.EXPIMP_ACTION_READ, sMessage, iActionNumber++);
                    throw new IOException(
                            StringUtils.getParameterizedExceptionMessage("xmlexport.error.copying.file",
                                    md.getField("filename").toString(), sEntityName, entityId, e));
                    //"Fehler beim Kopieren der Datei ["+sFileName+"] der Stammdaten-Entit\u00e4t ["+sEntityName+"] mt der Id ["+entityId+"]: "+e);
                }
            }
        }
    }
    // additional meta Information
    if ((md.getCreatedBy() != null)) {
        Element attr3 = entity.addElement("attribute");
        attr3.addAttribute("name", NuclosEOField.CREATEDBY.getMetaData().getField());
        attr3.setText(md.getCreatedBy());
    }

    if ((md.getChangedBy() != null)) {
        Element attr4 = entity.addElement("attribute");
        attr4.addAttribute("name", NuclosEOField.CHANGEDBY.getMetaData().getField());
        attr4.setText(md.getChangedBy());
    }

    if ((md.getChangedAt() != null)) {
        Element attr5 = entity.addElement("attribute");
        attr5.addAttribute("name", NuclosEOField.CHANGEDAT.getMetaData().getField());
        attr5.setText(dateFormat.format(md.getChangedAt()));
    }

    if ((md.getCreatedAt() != null)) {
        Element attr6 = entity.addElement("attribute");
        attr6.addAttribute("name", NuclosEOField.CREATEDAT.getMetaData().getField());
        attr6.setText(dateFormat.format(md.getCreatedAt()));
    }

    if (md.getVersion() != 0) {
        Element attr7 = entity.addElement("attribute");
        attr7.addAttribute("name", "[version]");
        attr7.setText(String.valueOf(md.getVersion()));
    }

    if (wasExported(new Pair<String, Integer>(sEntityName, (Integer) entityId))) {
        return;
    }

    parent.add(entity);

    exportedIds.add(new Pair<String, Integer>(sEntityName, (Integer) entityId));

    String sMessage = MessageFormat.format(
            localeFacade.getResourceById(localeFacade.getUserLocale(), "xmlexport.message.successful.2"),
            sEntityName, entityId);
    //"Master data entity ["+sEntityName+"] with the ID ["+entityId+"] successful exported.";
    info(sMessage);
    getProtocolFacade().writeExportImportLogEntry(iProtocolId, XmlExportImportHelper.EXPIMP_MESSAGE_LEVEL_INFO,
            XmlExportImportHelper.EXPIMP_ACTION_READ, sMessage, iActionNumber++);

    // subform 1:n references
    if (bExportDependants) {
        if (!mpMdSubFormsWithForeignKeys.containsKey(sEntityName)) {
            LayoutFacadeLocal layoutFacade = ServerServiceLocator.getInstance()
                    .getFacade(LayoutFacadeLocal.class);
            mpMdSubFormsWithForeignKeys.put(sEntityName,
                    layoutFacade.getSubFormEntityAndParentSubFormEntityNames(sEntityName, (Integer) entityId,
                            true, ServerParameterProvider.getInstance()
                                    .getValue(ParameterProvider.KEY_LAYOUT_CUSTOM_KEY)));
        }

        exportMDSubform(mpMdSubFormsWithForeignKeys.get(sEntityName), null, entityId, parent, deepexport);
    }
}

From source file:org.nuxeo.ecm.core.storage.marklogic.MarkLogicStateSerializer.java

License:Apache License

private static Element serialize(String key, State state) {
    boolean update = state instanceof StateDiff;
    Element element = DocumentHelper.createElement(MarkLogicHelper.serializeKey(key));
    for (Entry<String, Serializable> entry : state.entrySet()) {
        Optional<Element> child = serialize(entry.getKey(), entry.getValue());
        if (child.isPresent()) {
            element.add(child.get());/* w  ww  . j ava2  s  . co m*/
        } else if (update) {
            element.add(createNullElement(entry.getKey()));
        }
    }
    return element;
}

From source file:org.nuxeo.ecm.core.storage.marklogic.MarkLogicStateSerializer.java

License:Apache License

private static Optional<Element> serialize(String key, Object value) {
    Optional<Element> result;
    if (value == null) {
        result = Optional.empty();
    } else if (value instanceof State) {
        State state = (State) value;
        if (state.isEmpty()) {
            result = Optional.empty();
        } else {/* w  ww .  j  av  a2  s.  c  om*/
            result = Optional.of(serialize(key, state));
        }
    } else if (value instanceof ListDiff) {
        result = Optional.of(serialize(key, (ListDiff) value));
    } else if (value instanceof List) {
        @SuppressWarnings("unchecked")
        List<Object> values = (List<Object>) value;
        if (values.isEmpty()) {
            result = Optional.empty();
        } else {
            result = Optional.of(serialize(key, values));
        }
    } else if (value instanceof Object[]) {
        Object[] array = (Object[]) value;
        if (array.length == 0) {
            result = Optional.empty();
        } else {
            result = Optional.of(serialize(key, Arrays.asList(array)));
        }
    } else {
        String nodeValue = serializeValue(value);
        Element element = DocumentHelper.createElement(MarkLogicHelper.serializeKey(key));
        element.addAttribute(MarkLogicHelper.ATTRIBUTE_XSI_TYPE, ElementType.getType(value).get());
        element.setText(nodeValue);
        result = Optional.of(element);
    }
    return result;
}

From source file:org.nuxeo.ecm.core.storage.marklogic.MarkLogicStateSerializer.java

License:Apache License

private static Element serialize(String key, ListDiff listDiff) {
    Element diffParent = DocumentHelper.createElement(MarkLogicHelper.serializeKey(key));

    // diff serialization
    Element diff = DocumentHelper.createElement(MarkLogicHelper.serializeKey("diff"));
    if (listDiff.diff != null) {
        for (Object object : listDiff.diff) {
            diff.add(serialize(key + MarkLogicHelper.ARRAY_ITEM_KEY_SUFFIX, object)
                    .orElseGet(() -> createNullElement(key + MarkLogicHelper.ARRAY_ITEM_KEY_SUFFIX)));
        }//  w  ww .j a v a 2 s  . c  o  m
    }
    diffParent.add(diff);

    // rpush serialization
    List<Object> rpush = listDiff.rpush;
    if (rpush == null) {
        rpush = Collections.emptyList();
    }
    diffParent.add(serialize("rpush", key + MarkLogicHelper.ARRAY_ITEM_KEY_SUFFIX, rpush));
    return diffParent;
}

From source file:org.nuxeo.ecm.core.storage.marklogic.MarkLogicStateSerializer.java

License:Apache License

private static Element serialize(String key, String itemKey, List<Object> list) {
    Element array = DocumentHelper.createElement(MarkLogicHelper.serializeKey(key));
    for (Object object : list) {
        serialize(itemKey, object).ifPresent(array::add);
    }/* w ww.  j a v  a  2  s.  co  m*/
    return array;
}

From source file:org.nuxeo.ecm.core.storage.marklogic.MarkLogicStateSerializer.java

License:Apache License

private static Element createNullElement(String key) {
    Element element = DocumentHelper.createElement(MarkLogicHelper.serializeKey(key));
    element.setText("NULL");
    return element;
}