Example usage for org.dom4j DocumentHelper createDocument

List of usage examples for org.dom4j DocumentHelper createDocument

Introduction

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

Prototype

public static Document createDocument() 

Source Link

Usage

From source file:com.bluexml.side.Framework.alfresco.dataGenerator.serialization.mapping.XMLForACPMappingBuilder.java

License:Open Source License

/**
 * build the dom4j Document containing instances's metadata
 * @return the created dom4j Document //w  ww.j  a va2s  . c o  m
 */
public Document build() {

    document = DocumentHelper.createDocument();
    document.setXMLEncoding("UTF-8");
    Element root = helper.createRoot();
    mapsAllNodes(root);
    mapsAllArcs(root);
    return document;

}

From source file:com.bsoft.baseframe.baseframe_utils.beanUtils.CreateXMLFile.java

License:Open Source License

/**
 * xml??/*w  w w  .ja  va 2s. c om*/
 * @return ??
 */
public boolean createXMLFile() {
    String clsName = FileUtils.getClassName(tbName);
    String fileName = path + clsName + ".xml";
    String beanName = beanPkg + "." + clsName;

    List<GenaBean> list = GenaBeanDBUtils.getFields(tbName);
    if (list.size() == 0) {
        return false;
    }
    StringBuffer fields = new StringBuffer();
    StringBuffer values = new StringBuffer();
    GenaBean gb = null;
    String fn = null;
    for (int i = 0; i < list.size(); i++) {
        gb = list.get(i);
        fn = gb.getColumnName();
        fields.append(fn);
        if ("delflag".equals(fn)) {
            values.append("'0'");
        } else if ("ctb1".equals(fn)) {
            values.append("getdate()");
        } else {
            values.append("#").append(fn).append("#");
        }
        if (i != list.size() - 1) {
            fields.append(", ");
            values.append(", ");
        }
    }
    System.out.println(fields.toString());
    System.out.println(values.toString());

    //Document
    Document document = DocumentHelper.createDocument();

    //
    document.addDocType("sqlMap", "-//ibatis.apache.org//DTD SQL Map 2.0//EN",
            "http://ibatis.apache.org/dtd/sql-map-2.dtd");

    // document
    Element rootElement = document.addElement("sqlMap");

    //??
    rootElement.addAttribute("namespace", clsName.toUpperCase());

    //insert
    Element insertNode = rootElement.addElement("insert");
    insertNode.addAttribute("id", "add" + clsName);
    insertNode.addAttribute("parameterClass", beanName);
    insertNode.setText("insert into " + tbName + "(" + fields + ") values (" + values + ")");

    //?
    Element removeNode = rootElement.addElement("delete");
    removeNode.addAttribute("id", "remove" + clsName);
    removeNode.addAttribute("parameterClass", beanName);
    removeNode.setText("delete from " + tbName + " where id = #id#");

    //
    Element deleteNode = rootElement.addElement("update");
    deleteNode.addAttribute("id", "del" + clsName);
    deleteNode.addAttribute("parameterClass", beanName);
    deleteNode.setText("update " + tbName + " set delflag=#delflag# where id = #id#");

    //selectOne
    Element selectOneNode = rootElement.addElement("select");
    selectOneNode.addAttribute("id", "getOne" + clsName);
    selectOneNode.addAttribute("parameterClass", beanName);
    selectOneNode.addAttribute("resultClass", beanName);
    selectOneNode.setText("select *  from " + tbName + " where id = #id# ");

    //select
    Element selectNode = rootElement.addElement("select");
    selectNode.addAttribute("id", "queryCount");
    selectNode.addAttribute("resultClass", "int");
    selectNode.setText("select count(*) as countnum from " + tbName + " where 1=1");

    //select
    Element selectNode2 = rootElement.addElement("select");
    selectNode2.addAttribute("id", "list" + clsName);
    selectNode2.addAttribute("resultClass", beanName);
    selectNode2.addAttribute("parameterClass", "java.util.Map");
    selectNode2.setText("select * from (select top  $endNum$ row_number()over(order by TT.id) as RN,* from"
            + "(SELECT * FROM " + tbName + " where 1=1) as TT)as H where RN > #startNum#");

    //update
    Element updateNode = rootElement.addElement("update");
    updateNode.addAttribute("id", "upSap" + clsName);
    updateNode.addAttribute("parameterClass", beanName);
    updateNode.setText("UPDATE " + tbName + " ");
    Element erElement = updateNode.addElement("dynamic");
    erElement.addAttribute("prepend", "set");
    for (int i = 0; i < list.size(); i++) {
        gb = list.get(i);
        fn = gb.getColumnName();
        if (!"id".equals(fn)) {
            Element saElement = erElement.addElement("isNotNull");
            saElement.addAttribute("property", fn);
            saElement.addAttribute("removeFirstPrepend", "true");
            saElement.addAttribute("prepend", ",");
            saElement.setText(fn + "=#" + fn + "#");
        }
    }
    updateNode.addText(" where ");
    Element terElement = updateNode.addElement("isNotNull");
    terElement.addAttribute("property", "id");
    terElement.setText(" id = #id# ");

    //update
    Element updateSimpleNode = rootElement.addElement("update");
    updateSimpleNode.addAttribute("id", "update" + clsName);
    updateSimpleNode.addAttribute("parameterClass", beanName);

    StringBuffer sb = new StringBuffer();
    sb.append("update ").append(tbName).append(" set ");

    for (int i = 0; i < list.size(); i++) {
        gb = list.get(i);
        fn = gb.getColumnName();
        if (!"id".equals(fn)) {
            if ("ctb3".equals(fn)) {
                sb.append(fn).append("=").append("getdate()");
            } else {
                sb.append(fn).append("=#").append(fn).append("#");
            }
            if (i != list.size() - 1) {
                sb.append(", ");
            }

        }
    }
    sb.append(" where id = #id# ");
    updateSimpleNode.setText(sb.toString());
    return FileUtils.wrieteXML2Doc(document, new File(fileName));
}

From source file:com.bullx.cacconfig.CACConfig.java

License:Open Source License

public Document getRequest() {
    Document doc = DocumentHelper.createDocument();
    Element request = doc.addElement("request");

    DOMElement configsData = getConfigs();
    request.add(configsData);/*  w  w  w.  j  a  v  a2  s  .c o m*/
    return doc;
}

From source file:com.bullx.cacdata.CACData.java

License:Open Source License

public Document getRequest() {
    Document doc = DocumentHelper.createDocument();
    Element request = doc.addElement("request");

    DOMElement monitorData = getMonitorData();
    request.add(monitorData);/*from w ww  .j  a v a 2s  .co m*/

    return doc;
}

From source file:com.bullx.demo.xml.XMLParser.java

License:Open Source License

public static void bookListToXML(List<Book> books) {
    Document document = DocumentHelper.createDocument();
    // XMLbooks/*from  www  .  ja v a2s.  c  om*/
    Element booksElement = document.addElement("books");
    //  
    booksElement.addComment("This is a test for dom4j, liubida, 2012.8.11");

    for (Book book : books) {
        // 
        Element bookElement = booksElement.addElement("book");
        // : show
        bookElement.addAttribute("show", book.getShow() ? "yes" : "no");
        // title
        bookElement.addElement("title").setText(book.getTitle());
        // express
        bookElement.addElement("express").setText(book.getExpress());
    }

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    StringWriter out = new StringWriter();
    XMLWriter xmlWriter = new XMLWriter(out, format);
    try {
        xmlWriter.write(document);
        xmlWriter.flush();
        String s = out.toString();
        System.out.println(s);
        Log.info("xml done!");
    } catch (Exception e) {
        Log.error("xml error!");
    } finally {
        try {
            if (null != xmlWriter) {
                xmlWriter.close();
            }
            if (null != out) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.chingo247.structureapi.plan.document.PlanDocumentGenerator.java

License:Open Source License

public void generate(File targetFolder) {
    // Scan the folder called 'SchematicToPlan' for schematic files
    Iterator<File> it = FileUtils.iterateFiles(targetFolder, new String[] { "schematic" }, true);
    System.out.println("Files: " + targetFolder.listFiles().length);

    int count = 0;
    long start = System.currentTimeMillis();

    // Generate Plans
    while (it.hasNext()) {
        File schematic = it.next();

        Document d = DocumentHelper.createDocument();
        d.addElement(Elements.ROOT).addElement(Elements.SETTLERCRAFT).addElement(Elements.SCHEMATIC)
                .setText(schematic.getName());

        File plan = new File(schematic.getParent(), FilenameUtils.getBaseName(schematic.getName()) + ".xml");

        try {//from  ww w.ja  v a 2s. c o  m

            XMLWriter writer = new XMLWriter(new FileWriter(plan));
            writer.write(d);
            writer.close();

            StructurePlan sp = new StructurePlan();
            PlanDocument pd = new PlanDocument(structureAPI.getPlanDocumentManager(), plan);
            pd.putPluginElement("SettlerCraft", new PlanDocumentPluginElement("SettlerCraft", pd,
                    (Element) d.selectSingleNode("StructurePlan/SettlerCraft")));
            sp.load(pd);

            if (sp.getCategory().equals("Default")
                    && !schematic.getParentFile().getName().equals(targetFolder.getName())) {
                sp.setCategory(schematic.getParentFile().getName());
            }

            sp.save();

        } catch (DocumentException ex) {
            Logger.getLogger(StructurePlanManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | StructureDataException ex) {
            Logger.getLogger(StructurePlanManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        count++;
    }
    if (count > 0) {
        StructureAPI.print("Generated " + count + " plans in " + (System.currentTimeMillis() - start) + "ms");
    }
}

From source file:com.chingo247.structureapi.plan.io.export.StructurePlanExporter.java

License:Open Source License

public void export(IStructurePlan plan, File destinationDirectory, String fileName, boolean prettyPrint)
        throws IOException, UnsupportedPlacementException {
    Preconditions.checkArgument(destinationDirectory.isDirectory());

    IPlacement placement = plan.getPlacement();
    if (!(placement instanceof IExportablePlacement)) {
        throw new UnsupportedPlacementException("Placement does not implement IWriteablePlacement");
    }/*from w  ww  . j  a  v a2 s. c  o m*/

    Document d = DocumentHelper.createDocument();

    Element root = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_ROOT_ELEMENT);
    d.add(root);

    Element nameElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_NAME_ELEMENT);
    nameElement.setText(plan.getName());
    root.add(nameElement);

    Element priceElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_PRICE_ELEMENT);
    priceElement.setText(String.valueOf(plan.getPrice()));
    root.add(priceElement);

    Element categoryElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_CATEGORY_ELEMENT);
    categoryElement.setText(plan.getCategory() == null ? "None" : plan.getCategory());
    root.add(categoryElement);

    Element descriptionElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_DESCRIPTION_ELEMENT);
    descriptionElement.setText(plan.getDescription() == null ? "None" : plan.getDescription());
    root.add(descriptionElement);

    Element placementElement = PlacementAPI.getInstance().handle((IExportablePlacement) plan.getPlacement());
    root.add(placementElement);

    //        if (plan instanceof SubStructuresPlan) {
    //            SubStructuresPlan ssp = (SubStructuresPlan) plan;
    //            
    //            Element substructuresElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_SUBSTRUCTURES);
    //            root.add(substructuresElement);
    //            
    //            for(Placement p : ssp.getSubPlacements()) {
    //                try {
    //                    Element e = PlacementAPI.getInstance().handle(p);
    //                    e.setName(StructurePlanXMLConstants.STRUCTURE_PLAN_SUBSTRUCTURE);
    //                    substructuresElement.add(e);
    //                } catch (PlacementException ex) {
    //                    System.err.println(ex.getMessage());
    //                }
    //            }
    //            
    //            int index = 0;
    //            for(StructurePlan p : ssp.getSubStructurePlans()) {
    //                File exportPlan = new File(destinationDirectory, p.getFile().getName() + "-" + index);
    //                
    //                try {
    //                    export(plan, destinationDirectory, exportPlan.getName(), prettyPrint);
    //                } catch (Exception e){
    //                    continue;
    //                }
    //                
    //                Element substructureElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_SUBSTRUCTURE);
    //                
    //                // TODO add position + direction
    //                
    //                Element typeElement = new BaseElement(PlacementXMLConstants.PLACEMENT_TYPE_ELEMENT);
    //                typeElement.setText(PlacementTypes.EMBEDDED);
    //                substructureElement.add(typeElement);
    //                
    //                Element pathElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_RELATIVE_PATH_ELEMENT);
    //                pathElement.setText(exportPlan.getName());
    //                substructureElement.add(pathElement);
    //                
    //                substructuresElement.add(substructureElement);
    //                
    //            }
    //            
    //        }

    OutputFormat format;
    if (prettyPrint) {
        format = OutputFormat.createPrettyPrint();
    } else {
        format = OutputFormat.createCompactFormat();
    }
    XMLWriter writer = new XMLWriter(new FileWriter(new File(destinationDirectory, fileName)), format);
    writer.write(d);
    writer.close();

}

From source file:com.chingo247.structureapi.plan.PlanGenerator.java

License:Open Source License

private static void generatePlanFromSchematic(File file, File rootDirectory) throws IOException {
    String name = FilenameUtils.getBaseName(file.getName());
    File directory = file.getParentFile();

    Document d = DocumentHelper.createDocument();
    Element root = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_ROOT_ELEMENT);
    d.add(root);// ww w  .  j  a  v  a  2  s . co  m

    Element nameElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_NAME_ELEMENT);
    nameElement.setText(name);
    root.add(nameElement);

    Element priceElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_PRICE_ELEMENT);
    priceElement.setText("0");
    root.add(priceElement);

    Element description = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_DESCRIPTION_ELEMENT);
    description.setText("None");
    root.add(description);

    Element categoryElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_CATEGORY_ELEMENT);
    String category = rootDirectory.getName().equals(directory.getName()) ? "Default" : directory.getName();
    categoryElement.setText(category);
    root.add(categoryElement);

    Element placementElment = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_PLACEMENT);

    Element typeElement = new BaseElement(PlacementXMLConstants.TYPE_ELEMENT);
    typeElement.setText(PlacementTypes.SCHEMATIC);

    Element schematicElement = new BaseElement(PlacementXMLConstants.SCHEMATIC_ELEMENT);
    schematicElement.setText(file.getName());

    placementElment.add(typeElement);
    placementElment.add(schematicElement);

    root.add(placementElment);

    File planFile = new File(directory, name + ".xml");
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(planFile), format);
    writer.write(d);
    writer.close();
}

From source file:com.collabnet.ccf.core.ga.GenericArtifactHelper.java

License:Open Source License

/**
 * Creates a generic artifact XML representation out of the Java object
 * /*  w w w  . j  av  a 2s.c  om*/
 * @param genericArtifact
 *            Java object that will be represented as XML document
 * @return XML representation of generic artifact
 */
public static Document createGenericArtifactXMLDocument(GenericArtifact genericArtifact)
        throws GenericArtifactParsingException {
    Document document = DocumentHelper.createDocument();
    document.setXMLEncoding(EncodingAwareObject.UTF_8);
    // Create XML elements with attributes
    Element root = addRootElement(document, ARTIFACT_ROOT_ELEMENT_NAME, CCF_ARTIFACT_NAMESPACE);

    switch (genericArtifact.getArtifactAction()) {
    case CREATE: {
        addAttribute(root, ARTIFACT_ACTION, ARTIFACT_ACTION_CREATE);
        break;
    }
    case DELETE: {
        addAttribute(root, ARTIFACT_ACTION, ARTIFACT_ACTION_DELETE);
        break;
    }
    case IGNORE: {
        addAttribute(root, ARTIFACT_ACTION, ARTIFACT_ACTION_IGNORE);
        break;
    }
    case UPDATE: {
        addAttribute(root, ARTIFACT_ACTION, ARTIFACT_ACTION_UPDATE);
        break;
    }
    case RESYNC: {
        addAttribute(root, ARTIFACT_ACTION, ARTIFACT_ACTION_RESYNC);
        break;
    }
    case UNKNOWN: {
        addAttribute(root, ARTIFACT_ACTION, ARTIFACT_ACTION_UNKNOWN);
        break;
    }
    default: {
        throw new GenericArtifactParsingException(
                "Non valid value for root-attribute " + ARTIFACT_ACTION + " specified.");
    }
    }

    switch (genericArtifact.getArtifactMode()) {
    case CHANGEDFIELDSONLY: {
        addAttribute(root, ARTIFACT_MODE, ARTIFACT_MODE_CHANGED_FIELDS_ONLY);
        break;
    }
    case COMPLETE: {
        addAttribute(root, ARTIFACT_MODE, ARTIFACT_MODE_COMPLETE);
        break;
    }
    case UNKNOWN: {
        addAttribute(root, ARTIFACT_MODE, ARTIFACT_MODE_UNKNOWN);
        break;
    }
    default: {
        throw new GenericArtifactParsingException(
                "Non valid value for root-attribute " + ARTIFACT_MODE + "specified.");
    }
    }

    ArtifactTypeValue artifactType = genericArtifact.getArtifactType();
    switch (artifactType) {
    case ATTACHMENT: {
        addAttribute(root, ARTIFACT_TYPE, ARTIFACT_TYPE_ATTACHMENT);
        String content = genericArtifact.getArtifactValue();
        // TODO BASE64 validation?
        if (content != null)
            // embed content in CDATA section
            setValue(root, content, true);
        break;
    }
    case DEPENDENCY: {
        addAttribute(root, ARTIFACT_TYPE, ARTIFACT_TYPE_DEPENDENCY);
        break;
    }
    case PLAINARTIFACT: {
        addAttribute(root, ARTIFACT_TYPE, ARTIFACT_TYPE_PLAIN_ARTIFACT);
        break;
    }
    case UNKNOWN: {
        addAttribute(root, ARTIFACT_TYPE, ARTIFACT_TYPE_UNKNOWN);
        break;
    }
    default: {
        throw new GenericArtifactParsingException(
                "Non valid value for root-attribute " + ARTIFACT_TYPE + " specified.");
    }
    }

    switch (genericArtifact.getIncludesFieldMetaData()) {
    case TRUE: {
        addAttribute(root, INCLUDES_FIELD_META_DATA, INCLUDES_FIELD_META_DATA_TRUE);
        break;
    }
    case FALSE: {
        addAttribute(root, INCLUDES_FIELD_META_DATA, INCLUDES_FIELD_META_DATA_FALSE);
        break;
    }
    default: {
        throw new GenericArtifactParsingException(
                "Non valid value for root-attribute " + ARTIFACT_MODE + "specified.");
    }
    }

    addAttribute(root, SOURCE_ARTIFACT_LAST_MODIFICATION_DATE,
            genericArtifact.getSourceArtifactLastModifiedDate());
    addAttribute(root, TARGET_ARTIFACT_LAST_MODIFICATION_DATE,
            genericArtifact.getTargetArtifactLastModifiedDate());
    // addAttribute(root, ARTIFACT_LAST_READ_TRANSACTION_ID, genericArtifact
    // .getLastReadTransactionId());
    addAttribute(root, ERROR_CODE, genericArtifact.getErrorCode());
    addAttribute(root, SOURCE_ARTIFACT_VERSION, genericArtifact.getSourceArtifactVersion());
    addAttribute(root, TARGET_ARTIFACT_VERSION, genericArtifact.getTargetArtifactVersion());
    addAttribute(root, CONFLICT_RESOLUTION_PRIORITY, genericArtifact.getConflictResolutionPriority());

    // only create optional attributes if necessary
    if (artifactType == ArtifactTypeValue.DEPENDENCY || artifactType == ArtifactTypeValue.ATTACHMENT
            || artifactType == ArtifactTypeValue.PLAINARTIFACT) {
        addAttribute(root, DEP_PARENT_SOURCE_ARTIFACT_ID, genericArtifact.getDepParentSourceArtifactId());
        addAttribute(root, DEP_PARENT_SOURCE_REPOSITORY_ID, genericArtifact.getDepParentSourceRepositoryId());
        addAttribute(root, DEP_PARENT_SOURCE_REPOSITORY_KIND,
                genericArtifact.getDepParentSourceRepositoryKind());
        addAttribute(root, DEP_PARENT_TARGET_ARTIFACT_ID, genericArtifact.getDepParentTargetArtifactId());
        addAttribute(root, DEP_PARENT_TARGET_REPOSITORY_ID, genericArtifact.getDepParentTargetRepositoryId());
        addAttribute(root, DEP_PARENT_TARGET_REPOSITORY_KIND,
                genericArtifact.getDepParentTargetRepositoryKind());
    }

    // dependencies have even more optional attributes
    if (artifactType == ArtifactTypeValue.DEPENDENCY) {
        addAttribute(root, DEP_CHILD_SOURCE_ARTIFACT_ID, genericArtifact.getDepChildSourceArtifactId());
        addAttribute(root, DEP_CHILD_SOURCE_REPOSITORY_ID, genericArtifact.getDepChildSourceRepositoryId());
        addAttribute(root, DEP_CHILD_SOURCE_REPOSITORY_KIND, genericArtifact.getDepChildSourceRepositoryKind());
        addAttribute(root, DEP_CHILD_TARGET_ARTIFACT_ID, genericArtifact.getDepChildTargetArtifactId());
        addAttribute(root, DEP_CHILD_TARGET_REPOSITORY_ID, genericArtifact.getDepChildTargetRepositoryId());
        addAttribute(root, DEP_CHILD_TARGET_REPOSITORY_KIND, genericArtifact.getDepChildTargetRepositoryKind());
    }

    addAttribute(root, SOURCE_ARTIFACT_ID, genericArtifact.getSourceArtifactId());
    addAttribute(root, SOURCE_REPOSITORY_ID, genericArtifact.getSourceRepositoryId());
    addAttribute(root, SOURCE_REPOSITORY_KIND, genericArtifact.getSourceRepositoryKind());
    addAttribute(root, SOURCE_SYSTEM_ID, genericArtifact.getSourceSystemId());
    addAttribute(root, SOURCE_SYSTEM_KIND, genericArtifact.getSourceSystemKind());
    addAttribute(root, TARGET_ARTIFACT_ID, genericArtifact.getTargetArtifactId());
    addAttribute(root, TARGET_REPOSITORY_ID, genericArtifact.getTargetRepositoryId());
    addAttribute(root, TARGET_REPOSITORY_KIND, genericArtifact.getTargetRepositoryKind());
    addAttribute(root, TARGET_SYSTEM_ID, genericArtifact.getTargetSystemId());
    addAttribute(root, TARGET_SYSTEM_KIND, genericArtifact.getTargetSystemKind());
    addAttribute(root, SOURCE_SYSTEM_TIMEZONE, genericArtifact.getSourceSystemTimezone());
    addAttribute(root, TARGET_SYSTEM_TIMEZONE, genericArtifact.getTargetSystemTimezone());
    // addAttribute(root, SOURCE_SYSTEM_ENCODING, genericArtifact
    // .getSourceSystemEncoding());
    // addAttribute(root, TARGET_SYSTEM_ENCODING, genericArtifact
    // .getTargetSystemEncoding());
    addAttribute(root, TRANSACTION_ID, genericArtifact.getTransactionId());

    if (genericArtifact.getAllGenericArtifactFields() != null) {
        // now add fields
        for (GenericArtifactField genericArtifactField : genericArtifact.getAllGenericArtifactFields()) {
            Element field = addElement(root, ARTIFACT_FIELD_ELEMENT_NAME, CCF_ARTIFACT_NAMESPACE);
            switch (genericArtifactField.getFieldAction()) {
            case APPEND: {
                addAttribute(field, FIELD_ACTION, FIELD_ACTION_APPEND);
                break;
            }
            case DELETE: {
                addAttribute(field, FIELD_ACTION, FIELD_ACTION_DELETE);
                break;
            }
            case REPLACE: {
                addAttribute(field, FIELD_ACTION, FIELD_ACTION_REPLACE);
                break;
            }
            case UNKNOWN: {
                addAttribute(field, FIELD_ACTION, FIELD_ACTION_UNKNOWN);
                break;
            }
            default: {
                throw new GenericArtifactParsingException(
                        "Non valid value for field-attribute " + FIELD_ACTION + " specified.");
            }
            }

            addAttribute(field, FIELD_NAME, genericArtifactField.getFieldName());
            addAttribute(field, FIELD_TYPE, genericArtifactField.getFieldType());
            if (genericArtifactField.getFieldValueHasChanged()) {
                addAttribute(field, FIELD_VALUE_HAS_CHANGED, FIELD_VALUE_HAS_CHANGED_TRUE);
            } else {
                addAttribute(field, FIELD_VALUE_HAS_CHANGED, FIELD_VALUE_HAS_CHANGED_FALSE);
            }

            if (genericArtifact.getIncludesFieldMetaData()
                    .equals(GenericArtifact.IncludesFieldMetaDataValue.TRUE)) {
                addAttribute(field, MIN_OCCURS, genericArtifactField.getMinOccursValue());
                addAttribute(field, MAX_OCCURS, genericArtifactField.getMaxOccursValue());
                addAttribute(field, NULL_VALUE_SUPPORTED, genericArtifactField.getNullValueSupported());
            } else if (!GenericArtifactField.VALUE_UNKNOWN
                    .equals(genericArtifactField.getAlternativeFieldName())
                    && genericArtifactField.getAlternativeFieldName() != null) {
                // if the alternative field name field has been set, we will ship it even if the other meta data has not been populated
                addAttribute(field, ALTERNATIVE_FIELD_NAME, genericArtifactField.getAlternativeFieldName());
            }

            setFieldValue(field, genericArtifactField.getFieldValue(),
                    genericArtifactField.getFieldValueType());
        }
    }
    root.addAttribute(
            new QName(SCHEMA_LOCATION_ATTRIBUTE, new Namespace(SCHEMA_NAMESPACE_PREFIX, SCHEMA_NAMESPACE)),
            CCF_SCHEMA_LOCATION);
    return document;
}

From source file:com.collabnet.ccf.core.GenericArtifactHelper.java

License:Apache License

/**
 * Creates a generic artifact XML representation out of the Java object
 * //  ww w . ja v a  2s.  c o  m
 * @param genericArtifact
 *            Java object that will be represented as XML document
 * @return XML representation of generic artifact
 */
public static Document createGenericArtifactXMLDocument(GenericArtifact genericArtifact)
        throws GenericArtifactParsingException {
    Document document = DocumentHelper.createDocument();
    document.setXMLEncoding("UTF-8");
    // Create XML elements with attributes
    Element root = addRootElement(document, ARTIFACT_ROOT_ELEMENT_NAME, CCF_ARTIFACT_NAMESPACE);

    switch (genericArtifact.getArtifactAction()) {
    case CREATE: {
        addAttribute(root, ARTIFACT_ACTION, ARTIFACT_ACTION_CREATE);
        break;
    }
    case DELETE: {
        addAttribute(root, ARTIFACT_ACTION, ARTIFACT_ACTION_DELETE);
        break;
    }
    case IGNORE: {
        addAttribute(root, ARTIFACT_ACTION, ARTIFACT_ACTION_IGNORE);
        break;
    }
    case UPDATE: {
        addAttribute(root, ARTIFACT_ACTION, ARTIFACT_ACTION_UPDATE);
        break;
    }
    case RESYNC: {
        addAttribute(root, ARTIFACT_ACTION, ARTIFACT_ACTION_RESYNC);
        break;
    }
    case UNKNOWN: {
        addAttribute(root, ARTIFACT_ACTION, ARTIFACT_ACTION_UNKNOWN);
        break;
    }
    default: {
        throw new GenericArtifactParsingException(
                "Non valid value for root-attribute " + ARTIFACT_ACTION + " specified.");
    }
    }

    switch (genericArtifact.getArtifactMode()) {
    case CHANGEDFIELDSONLY: {
        addAttribute(root, ARTIFACT_MODE, ARTIFACT_MODE_CHANGED_FIELDS_ONLY);
        break;
    }
    case COMPLETE: {
        addAttribute(root, ARTIFACT_MODE, ARTIFACT_MODE_COMPLETE);
        break;
    }
    case UNKNOWN: {
        addAttribute(root, ARTIFACT_MODE, ARTIFACT_MODE_UNKNOWN);
        break;
    }
    default: {
        throw new GenericArtifactParsingException(
                "Non valid value for root-attribute " + ARTIFACT_MODE + "specified.");
    }
    }

    ArtifactTypeValue artifactType = genericArtifact.getArtifactType();
    switch (artifactType) {
    case ATTACHMENT: {
        addAttribute(root, ARTIFACT_TYPE, ARTIFACT_TYPE_ATTACHMENT);
        String content = genericArtifact.getArtifactValue();
        // TODO BASE64 validation?
        if (content != null)
            // embed content in CDATA section
            setValue(root, content, true);
        break;
    }
    case DEPENDENCY: {
        addAttribute(root, ARTIFACT_TYPE, ARTIFACT_TYPE_DEPENDENCY);
        break;
    }
    case PLAINARTIFACT: {
        addAttribute(root, ARTIFACT_TYPE, ARTIFACT_TYPE_PLAIN_ARTIFACT);
        break;
    }
    case UNKNOWN: {
        addAttribute(root, ARTIFACT_TYPE, ARTIFACT_TYPE_UNKNOWN);
        break;
    }
    default: {
        throw new GenericArtifactParsingException(
                "Non valid value for root-attribute " + ARTIFACT_TYPE + " specified.");
    }
    }

    switch (genericArtifact.getIncludesFieldMetaData()) {
    case TRUE: {
        addAttribute(root, INCLUDES_FIELD_META_DATA, INCLUDES_FIELD_META_DATA_TRUE);
        break;
    }
    case FALSE: {
        addAttribute(root, INCLUDES_FIELD_META_DATA, INCLUDES_FIELD_META_DATA_FALSE);
        break;
    }
    default: {
        throw new GenericArtifactParsingException(
                "Non valid value for root-attribute " + ARTIFACT_MODE + "specified.");
    }
    }

    addAttribute(root, SOURCE_ARTIFACT_LAST_MODIFICATION_DATE,
            genericArtifact.getSourceArtifactLastModifiedDate());
    addAttribute(root, TARGET_ARTIFACT_LAST_MODIFICATION_DATE,
            genericArtifact.getTargetArtifactLastModifiedDate());
    // addAttribute(root, ARTIFACT_LAST_READ_TRANSACTION_ID, genericArtifact
    // .getLastReadTransactionId());
    addAttribute(root, ERROR_CODE, genericArtifact.getErrorCode());
    addAttribute(root, SOURCE_ARTIFACT_VERSION, genericArtifact.getSourceArtifactVersion());
    addAttribute(root, TARGET_ARTIFACT_VERSION, genericArtifact.getTargetArtifactVersion());
    addAttribute(root, CONFLICT_RESOLUTION_PRIORITY, genericArtifact.getConflictResolutionPriority());

    // only create optional attributes if necessary
    if (artifactType == ArtifactTypeValue.DEPENDENCY || artifactType == ArtifactTypeValue.ATTACHMENT) {
        addAttribute(root, DEP_PARENT_SOURCE_ARTIFACT_ID, genericArtifact.getDepParentSourceArtifactId());
        addAttribute(root, DEP_PARENT_SOURCE_REPOSITORY_ID, genericArtifact.getDepParentSourceRepositoryId());
        addAttribute(root, DEP_PARENT_SOURCE_REPOSITORY_KIND,
                genericArtifact.getDepParentSourceRepositoryKind());
        addAttribute(root, DEP_PARENT_TARGET_ARTIFACT_ID, genericArtifact.getDepParentTargetArtifactId());
        addAttribute(root, DEP_PARENT_TARGET_REPOSITORY_ID, genericArtifact.getDepParentTargetRepositoryId());
        addAttribute(root, DEP_PARENT_TARGET_REPOSITORY_KIND,
                genericArtifact.getDepParentTargetRepositoryKind());
    }

    // dependencies have even more optional attributes
    if (artifactType == ArtifactTypeValue.DEPENDENCY) {
        addAttribute(root, DEP_CHILD_SOURCE_ARTIFACT_ID, genericArtifact.getDepChildSourceArtifactId());
        addAttribute(root, DEP_CHILD_SOURCE_REPOSITORY_ID, genericArtifact.getDepChildSourceRepositoryId());
        addAttribute(root, DEP_CHILD_SOURCE_REPOSITORY_KIND, genericArtifact.getDepChildSourceRepositoryKind());
        addAttribute(root, DEP_CHILD_TARGET_ARTIFACT_ID, genericArtifact.getDepChildTargetArtifactId());
        addAttribute(root, DEP_CHILD_TARGET_REPOSITORY_ID, genericArtifact.getDepChildTargetRepositoryId());
        addAttribute(root, DEP_CHILD_TARGET_REPOSITORY_KIND, genericArtifact.getDepChildTargetRepositoryKind());
    }

    addAttribute(root, SOURCE_ARTIFACT_ID, genericArtifact.getSourceArtifactId());
    addAttribute(root, SOURCE_REPOSITORY_ID, genericArtifact.getSourceRepositoryId());
    addAttribute(root, SOURCE_REPOSITORY_KIND, genericArtifact.getSourceRepositoryKind());
    addAttribute(root, SOURCE_SYSTEM_ID, genericArtifact.getSourceSystemId());
    addAttribute(root, SOURCE_SYSTEM_KIND, genericArtifact.getSourceSystemKind());
    addAttribute(root, TARGET_ARTIFACT_ID, genericArtifact.getTargetArtifactId());
    addAttribute(root, TARGET_REPOSITORY_ID, genericArtifact.getTargetRepositoryId());
    addAttribute(root, TARGET_REPOSITORY_KIND, genericArtifact.getTargetRepositoryKind());
    addAttribute(root, TARGET_SYSTEM_ID, genericArtifact.getTargetSystemId());
    addAttribute(root, TARGET_SYSTEM_KIND, genericArtifact.getTargetSystemKind());
    addAttribute(root, SOURCE_SYSTEM_TIMEZONE, genericArtifact.getSourceSystemTimezone());
    addAttribute(root, TARGET_SYSTEM_TIMEZONE, genericArtifact.getTargetSystemTimezone());
    // addAttribute(root, SOURCE_SYSTEM_ENCODING, genericArtifact
    // .getSourceSystemEncoding());
    // addAttribute(root, TARGET_SYSTEM_ENCODING, genericArtifact
    // .getTargetSystemEncoding());
    addAttribute(root, TRANSACTION_ID, genericArtifact.getTransactionId());

    if (genericArtifact.getAllGenericArtifactFields() != null) {
        // now add fields
        for (GenericArtifactField genericArtifactField : genericArtifact.getAllGenericArtifactFields()) {
            Element field = addElement(root, ARTIFACT_FIELD_ELEMENT_NAME, CCF_ARTIFACT_NAMESPACE);
            switch (genericArtifactField.getFieldAction()) {
            case APPEND: {
                addAttribute(field, FIELD_ACTION, FIELD_ACTION_APPEND);
                break;
            }
            case DELETE: {
                addAttribute(field, FIELD_ACTION, FIELD_ACTION_DELETE);
                break;
            }
            case REPLACE: {
                addAttribute(field, FIELD_ACTION, FIELD_ACTION_REPLACE);
                break;
            }
            case UNKNOWN: {
                addAttribute(field, FIELD_ACTION, FIELD_ACTION_UNKNOWN);
                break;
            }
            default: {
                throw new GenericArtifactParsingException(
                        "Non valid value for field-attribute " + FIELD_ACTION + " specified.");
            }
            }

            addAttribute(field, FIELD_NAME, genericArtifactField.getFieldName());
            addAttribute(field, FIELD_TYPE, genericArtifactField.getFieldType());
            if (genericArtifactField.getFieldValueHasChanged()) {
                addAttribute(field, FIELD_VALUE_HAS_CHANGED, FIELD_VALUE_HAS_CHANGED_TRUE);
            } else {
                addAttribute(field, FIELD_VALUE_HAS_CHANGED, FIELD_VALUE_HAS_CHANGED_FALSE);
            }

            if (genericArtifact.getIncludesFieldMetaData()
                    .equals(GenericArtifact.IncludesFieldMetaDataValue.TRUE)) {
                addAttribute(field, MIN_OCCURS, genericArtifactField.getMinOccursValue());
                addAttribute(field, MAX_OCCURS, genericArtifactField.getMaxOccursValue());
                addAttribute(field, NULL_VALUE_SUPPORTED, genericArtifactField.getNullValueSupported());
                addAttribute(field, ALTERNATIVE_FIELD_NAME, genericArtifactField.getAlternativeFieldName());
            }

            setFieldValue(field, genericArtifactField.getFieldValue(),
                    genericArtifactField.getFieldValueType());
        }
    }
    root.addAttribute(
            new QName(SCHEMA_LOCATION_ATTRIBUTE, new Namespace(SCHEMA_NAMESPACE_PREFIX, SCHEMA_NAMESPACE)),
            CCF_SCHEMA_LOCATION);
    return document;
}