Example usage for org.dom4j Element addElement

List of usage examples for org.dom4j Element addElement

Introduction

In this page you can find the example usage for org.dom4j Element addElement.

Prototype

Element addElement(String name);

Source Link

Document

Adds a new Element node with the given name to this branch and returns a reference to the new node.

Usage

From source file:com.doculibre.constellio.utils.izpack.UsersXmlFileUtils.java

License:Open Source License

private static Element toXmlElement(ConstellioUser constellioUser) {
    BaseElement user = new BaseElement(USER);
    user.addAttribute(FIRST_NAME, constellioUser.getFirstName());
    user.addAttribute(LAST_NAME, constellioUser.getLastName());
    user.addAttribute(LOGIN, constellioUser.getUsername());
    user.addAttribute(PASSWORD_HASH, constellioUser.getPasswordHash());

    if (constellioUser.getLocale() != null) {
        user.addAttribute(LOCALE, constellioUser.getLocaleCode());
    }/*ww w .j  ava 2 s.c o m*/

    Set<String> constellioRoles = constellioUser.getRoles();
    if (!constellioRoles.isEmpty()) {
        Element roles = user.addElement(ROLES);
        for (String constellioRole : constellioRoles) {
            Element role = roles.addElement(ROLE);
            role.addAttribute(VALUE, constellioRole);
        }
    }

    return user;
}

From source file:com.dreikraft.axbo.sound.SoundPackageUtil.java

/**
 * creates a package-info.xml from the SoundPackage Bean
 *
 * @param soundPackage a SoundPackage Bean containing all the meta information
 * @return a dom4j document/*  w  ww .  ja  v a 2 s.  co  m*/
 */
public static Document createPackageInfoXml(final SoundPackage soundPackage) {

    Document document = DocumentHelper.createDocument();
    document.setXMLEncoding(ENCODING);

    Element rootNode = document.addElement(SoundPackageNodes.axboSounds.toString());
    rootNode.addElement(SoundPackageNodes.packageName.toString()).addText(soundPackage.getName());
    rootNode.addElement(SoundPackageNodes.creator.toString()).addText(soundPackage.getCreator());
    rootNode.addElement(SoundPackageNodes.creationDate.toString())
            .addText(new SimpleDateFormat(pattern).format(soundPackage.getCreationDate()));

    Element securityNode = rootNode.addElement(SoundPackageNodes.security.toString());
    securityNode.addElement(SoundPackageNodes.serialNumber.toString()).addText(soundPackage.getSerialNumber());
    securityNode.addElement(SoundPackageNodes.enforced.toString())
            .addText("" + soundPackage.isSecurityEnforced());

    Element soundsNode = rootNode.addElement(SoundPackageNodes.sounds.toString());
    int id = 1;
    for (Sound sound : soundPackage.getSounds()) {
        Element soundNode = soundsNode.addElement(SoundPackageNodes.sound.toString());
        soundNode.addAttribute(SoundPackageAttributes.id.toString(), String.valueOf(id));
        soundNode.addElement(SoundPackageNodes.displayName.toString()).addText(sound.getName());

        Element axboFileNode = soundNode.addElement(SoundPackageNodes.axboFile.toString());
        axboFileNode.addElement(SoundPackageNodes.path.toString()).setText(sound.getAxboFile().extractName());
        axboFileNode.addElement(SoundPackageNodes.type.toString())
                .setText(sound.getAxboFile().getType().toString());

        id++;
    }
    return document;
}

From source file:com.dtolabs.client.services.JobDefinitionSerializer.java

License:Apache License

private static Element addJobBasic(final Element root, final String jobName, final String loglevel) {
    final Element job = root.addElement("job");
    job.addElement("name").addText(jobName);
    job.addElement("description").addText(jobName);
    job.addElement("additional");
    job.addElement("loglevel").addText(loglevel);
    return job;//from w ww  . ja v a  2  s .  co  m
}

From source file:com.dtolabs.client.services.JobDefinitionSerializer.java

License:Apache License

/**
 * Add script dispatch content to the job element
 *
 * @param dispatchdef dispatch definition
 * @param job         job element/*from  w ww. ja  va  2s  .  com*/
 * @throws java.io.IOException if the input IDispatchedScript throws it when accessing script stream input.
 */
private static void addScriptDispatch(final IDispatchedScript dispatchdef, final Element job)
        throws IOException {
    if (null == dispatchdef.getFrameworkProject()) {
        throw new IllegalArgumentException("No project is specified");
    }
    final Element ctx = job.addElement("context");
    ctx.addElement("project").addText(dispatchdef.getFrameworkProject());
    final InputStream stream = dispatchdef.getScriptAsStream();
    final Element seq = job.addElement("sequence");
    final Element cmd = seq.addElement("command");
    if (null != dispatchdef.getScript() || null != stream) {

        //full script
        final Element script = cmd.addElement("script");
        if (null != dispatchdef.getScript()) {
            script.addCDATA(dispatchdef.getScript());
        } else {
            //serialize script inputstream and add string to dom
            final StringWriter sw = new StringWriter();
            copyReader(new InputStreamReader(stream), sw, 10240);
            sw.flush();
            script.addCDATA(sw.toString());
        }
        if (null != dispatchdef.getArgs() && dispatchdef.getArgs().length > 0) {
            final Element argstring = cmd.addElement("scriptargs");
            argstring.addText(OptsUtil.join(dispatchdef.getArgs()));
        }
    } else if (null != dispatchdef.getServerScriptFilePath()) {
        //server-local script filepath
        final Element filepath = cmd.addElement("scriptfile");
        filepath.addText(dispatchdef.getServerScriptFilePath());
        if (null != dispatchdef.getArgs() && dispatchdef.getArgs().length > 0) {
            final Element argstring = cmd.addElement("scriptargs");
            argstring.addText(OptsUtil.join(dispatchdef.getArgs()));
        }
    } else if (null != dispatchdef.getArgs() && dispatchdef.getArgs().length > 0) {
        //shell command
        final Element exec = cmd.addElement("exec");
        exec.addText(OptsUtil.join(dispatchdef.getArgs()));
    } else {
        throw new IllegalArgumentException("Dispatched script did not specify a command, script or filepath");
    }

}

From source file:com.dtolabs.client.services.JobDefinitionSerializer.java

License:Apache License

/**
 * Add nodefilter and dispatch element to job element for the nodeset, if not null
 *
 * @param job     job element/*from   w  w  w. j a  va2 s  . c  om*/
 * @param threadCount thread count
 * @param excludePrecedence exclude precedence set
 * @param nodeFilter node filter string
 */
private static void addNodefilters(final Element job, int threadCount, boolean keepgoing,
        boolean excludePrecedence, String nodeFilter) {
    final int threadcount = (threadCount > 1) ? threadCount : 1;
    if (null != nodeFilter) {
        final Element filters = job.addElement("nodefilters");
        ;
        filters.addElement("filter").addText(nodeFilter);
        filters.addAttribute("excludeprecedence", Boolean.toString(excludePrecedence));
    }
    final Element dispatch = job.addElement("dispatch");
    dispatch.addElement("threadcount").addText(Integer.toString(threadcount));
    dispatch.addElement("keepgoing").addText(Boolean.toString(keepgoing));

}

From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java

License:Apache License

@Override
public void createProject(final String project, final Properties projectProperties)
        throws CentralDispatcherException {
    final HashMap<String, String> params = new HashMap<String, String>();

    Document document = DocumentFactory.getInstance().createDocument();
    Element project1 = DocumentFactory.getInstance().createElement("project");
    document.setRootElement(project1);/*  w  ww . ja v a  2 s  . c  om*/
    project1.addElement("name").addText(project);
    Element config = project1.addElement("config");

    for (Object o : projectProperties.keySet()) {
        config.addElement("property").addAttribute("key", o.toString()).addAttribute("value",
                projectProperties.getProperty(o.toString()));
    }
    //serialize to temp file
    File temp = null;
    try {
        temp = File.createTempFile("rundeck-api", ".xml");
        temp.deleteOnExit();
        try (FileOutputStream fos = new FileOutputStream(temp)) {
            serialize(document, fos);
        } catch (IOException e) {
            throw new CentralDispatcherServerRequestException("Failed to serialize request document", e);
        }
    } catch (IOException e) {
        throw new CentralDispatcherServerRequestException("Failed to serialize request document", e);
    }

    /*
     * Send the request bean and the file as a multipart request.
     */

    //2. send request via ServerService
    final WebserviceResponse response;
    try {
        response = getServerService().makeRundeckRequest(RUNDECK_API_PROJECTS, params, temp, "POST", "text/xml",
                "text/xml");
    } catch (MalformedURLException e) {
        throw new CentralDispatcherServerRequestException("Failed to make request", e);
    } finally {
        temp.delete();
    }
    if (response.getResultCode() != 201) {
        throw new CentralDispatcherServerRequestException("Failed to create the project, result code: "
                + response.getResultCode() + " " + response.getResponseMessage());
    }

    validateResponse(response);
}

From source file:com.dtolabs.rundeck.core.cli.util.MvnPomInfoTool.java

License:Apache License

Document generateData() {
    Document doc = DocumentHelper.createDocument();
    Element el = doc.addElement("packages");
    String basepath = basedir.getAbsolutePath();
    if (basepath.endsWith("/")) {
        basepath = basepath.substring(0, basepath.length() - 1);
    }/*from w  w  w.ja va2  s.  c  o  m*/
    el.addAttribute("basedir", basepath);
    for (Iterator iterator = data.keySet().iterator(); iterator.hasNext();) {
        String file = (String) iterator.next();
        Map data = (Map) this.data.get(file);
        logger.info(file + ": " + data);
        Element pkgelem = el.addElement("package");
        pkgelem.addAttribute("name",
                data.get("artifactId") + "-" + data.get("version") + "." + data.get("packaging"));
        File f = new File(file);

        String relpom = file.substring(basepath.length() + 1);
        pkgelem.addAttribute("pom-path", relpom);

        String groupId = (String) data.get("groupId");
        String relpath = groupId.replaceAll("\\.", "/");
        pkgelem.addAttribute("repo-path", relpath);

    }
    return doc;
}

From source file:com.dtolabs.shared.resources.ResourceXMLGenerator.java

License:Apache License

/**
 * Generate resources section and resource references
 *
 * @param ent element/*from ww w . j a  v  a2  s.  co m*/
 * @param entity entity
 */
private void genAttributes(final Element ent, final ResourceXMLParser.Entity entity) {
    if (null == entity.getProperties()) {
        return;
    }
    for (final String key : entity.getProperties().stringPropertyNames()) {
        if (!ResourceXMLConstants.allPropSet.contains(key)) {
            //test attribute name is a valid XML attribute name
            if (XMLChar.isValidName(key) && !key.contains(":") && !key.contains(".")) {
                ent.addAttribute(key, entity.getProperties().getProperty(key));
            } else {
                //add sub element
                final Element atelm = ent.addElement(ATTRIBUTE_TAG);
                atelm.addAttribute(ATTRIBUTE_NAME_ATTR, key);
                atelm.addAttribute(ATTRIBUTE_VALUE_ATTR, entity.getProperties().getProperty(key));
            }
        }
    }

}

From source file:com.dtolabs.shared.resources.ResourceXMLGenerator.java

License:Apache License

/**
 * Create entity tag based on resourceType of entity, and add common attributes
 *
 * @param root element//from  w ww  .  j a va2s.c o m
 * @param entity entity
 *
 * @return element
 */
private Element genEntityCommon(final Element root, final ResourceXMLParser.Entity entity) {
    final Element tag = root.addElement(entity.getResourceType());
    tag.addAttribute(COMMON_NAME, entity.getName());
    tag.addAttribute(COMMON_DESCRIPTION, notNull(entity.getProperty(COMMON_DESCRIPTION)));
    tag.addAttribute(COMMON_TAGS, notNull(entity.getProperty(COMMON_TAGS)));
    return tag;
}

From source file:com.ethercis.compositionservice.CompositionService.java

License:Apache License

@QuerySetting(dialect = {
        @QuerySyntax(mode = I_ServiceRunMode.DialectSpace.STANDARD, httpMethod = "GET", method = "create", path = "vehr/composition", responseType = ResponseType.Json),
        @QuerySyntax(mode = I_ServiceRunMode.DialectSpace.EHRSCAPE, httpMethod = "POST", method = "post", path = "rest/v1/composition", responseType = ResponseType.Json) })
public Object create(I_SessionClientProperties props) throws Exception {

    auditSetter.handleProperties(getDataAccess(), props);
    String sessionId = auditSetter.getSessionId();
    String templateId = props.getClientProperty(I_CompositionService.TEMPLATE_ID, (String) null);
    UUID ehrId = retrieveEhrId(sessionId, props);

    UUID committerUuid = auditSetter.getCommitterUuid();
    UUID systemUuid = auditSetter.getSystemUuid();

    I_CompositionService.CompositionFormat format = I_CompositionService.CompositionFormat
            .valueOf(props.getClientProperty(I_CompositionService.FORMAT, "XML"));

    if ((format == CompositionFormat.FLAT || format == CompositionFormat.ECISFLAT)
            && (templateId == null || templateId.length() == 0))
        throw new ServiceManagerException(getGlobal(), SysErrorCode.USER_ILLEGALARGUMENT, ME,
                "Template Id must be specified");

    //get body stuff
    String content = props.getClientProperty(Constants.REQUEST_CONTENT, (String) null);

    if (content == null)
        throw new ServiceManagerException(getGlobal(), SysErrorCode.USER_ILLEGALARGUMENT, ME,
                "Content cannot be empty for a new composition");

    Integer contentLength = (Integer) props.getClientProperty(Constants.REQUEST_CONTENT_LENGTH, (Integer) 0);

    if (content.length() != contentLength)
        throw new ServiceManagerException(getGlobal(), SysErrorCode.USER_ILLEGALARGUMENT, ME,
                "Content may be altered found length =" + content.length() + " expected:" + contentLength);

    //        String contentType = props.getClientProperty(Constants.REQUEST_CONTENT_TYPE, "");

    UUID compositionId;/*from  www .  j av  a 2  s . co m*/

    switch (format) {
    case XML:
        CanonicalHandler canonicalHandler = new CanonicalHandler(knowledgeCache.getKnowledgeCache(), templateId,
                null);
        Composition composition = canonicalHandler.build(getGlobal(), content);
        templateId = composition.getArchetypeDetails().getTemplateId().getValue();
        I_CompositionAccess compositionAccess = I_CompositionAccess.getNewInstance(getDataAccess(), composition,
                DateTime.now(), ehrId);
        I_EntryAccess entryAccess = I_EntryAccess.getNewInstance(getDataAccess(), templateId, 0,
                compositionAccess.getId(), composition);
        compositionAccess.addContent(entryAccess);
        compositionId = compositionAccess.commit(committerUuid, systemUuid, auditSetter.getDescription());

        //create an XML response
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("compositionCreateRestResponseData");
        root.addElement("action").addText("CREATE");
        root.addElement("compositionUid").addText(encodeUuid(compositionId, 1));
        root.addElement("meta").addElement("href")
                .addText(Constants.URI_TAG + "?" + encodeURI(null, compositionId, 1, null));
        global.getProperty().set(MethodName.RETURN_TYPE_PROPERTY, "" + MethodName.RETURN_XML);
        return document;

    case ECISFLAT:
        PvCompoHandler pvCompoHandler = new PvCompoHandler(this.getDataAccess(), templateId, null);
        Map<String, String> kvPairs = FlatJsonUtil
                .inputStream2Map(new StringReader(new String(content.getBytes())));
        compositionId = pvCompoHandler.storeComposition(ehrId, kvPairs, auditSetter.getCommitterUuid(),
                auditSetter.getSystemUuid(), auditSetter.getDescription());

        //create json response
        global.getProperty().set(MethodName.RETURN_TYPE_PROPERTY, "" + MethodName.RETURN_JSON);
        Map<String, Object> retmap = new HashMap<>();
        retmap.put("action", "CREATE");
        retmap.put(COMPOSITION_UID, encodeUuid(compositionId, 1));
        Map<String, Map<String, String>> metaref = MetaBuilder.add2MetaMap(null, "href",
                Constants.URI_TAG + "?" + encodeURI(null, compositionId, 1, null));
        retmap.putAll(metaref);
        return retmap;

    case FLAT:
        I_FlatJsonCompositionConverter flatJsonCompositionConverter = FlatJsonCompositionConverter
                .getInstance(getDataAccess().getKnowledgeManager());
        Map flatMap = FlatJsonUtil.inputStream2Map(new StringReader(new String(content.getBytes())));
        Composition newComposition = flatJsonCompositionConverter.toComposition(templateId, flatMap);
        I_CompositionAccess access = I_CompositionAccess.getNewInstance(getDataAccess(), newComposition,
                DateTime.now(), ehrId);
        I_EntryAccess entry = I_EntryAccess.getNewInstance(getDataAccess(), templateId, 0, access.getId(),
                newComposition);
        access.addContent(entry);
        compositionId = access.commit(committerUuid, systemUuid, auditSetter.getDescription());
        //create json response
        global.getProperty().set(MethodName.RETURN_TYPE_PROPERTY, "" + MethodName.RETURN_JSON);
        retmap = new HashMap<>();
        retmap.put("action", "CREATE");
        retmap.put(COMPOSITION_UID, encodeUuid(compositionId, 1));
        metaref = MetaBuilder.add2MetaMap(null, "href",
                Constants.URI_TAG + "?" + encodeURI(null, compositionId, 1, null));
        retmap.putAll(metaref);
        return retmap;

    default:
        throw new ServiceManagerException(getGlobal(), SysErrorCode.USER_ILLEGALARGUMENT, ME,
                "This format is not supported:" + format);
    }
}