org.dom4j.dom.DOMElement Java Examples

The following examples show how to use org.dom4j.dom.DOMElement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServiceResource.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
private Element marshal(IServiceSettings settings) throws Exception {
 BeanMap beanMap = new BeanMap(settings);
 
 DOMElement rootElement = new DOMElement(new QName("settings"));
 
 for (Object key : beanMap.keySet()) {
         Object value = beanMap.get(key);
         if (value != null) {
             DOMElement domElement = new DOMElement(new QName(key.toString()));
             domElement.setText(value.toString());
             rootElement.add(domElement);
         }
    }
 
 return rootElement;
}
 
Example #2
Source File: Param.java    From mts with GNU General Public License v3.0 6 votes vote down vote up
public Element toXmlElement(){
    if (getParam() == null) {
        param = new DOMElement("parameter");
        if(getName() != null){
            param.addAttribute("name", getName());
        }
        if(getOperation() != null){
            param.addAttribute("operation", getOperation());
        }
        if(getValue() != null){
            param.addAttribute("value", getValue());
        }
        if(getValue2() != null){
            param.addAttribute("value2", getValue2());
        }
        if(getValue3() != null){
            param.addAttribute("value3", getValue3());
        }
        if(getEditable() != null){
            param.addAttribute("editable", getEditable());
        }
    }
    
    return getParam();
}
 
Example #3
Source File: ScmMaterialXmlRepresenterTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@FileSource(files = "/feeds/materials/git-material.xml")
void shouldGenerateXmlFromMaterialRevision(String expectedXML) {
    GitMaterial gitMaterial = gitMaterial("https://material/example.git");
    gitMaterial.setId(100);
    MaterialRevision materialRevision = new MaterialRevision(gitMaterial, modifications());
    DOMElement root = new DOMElement("materials");
    ElementBuilder builder = new ElementBuilder(root);
    XmlWriterContext context = new XmlWriterContext("https://test.host/go", null, null, null, new SystemEnvironment());

    new ScmMaterialXmlRepresenter("up42", 1,materialRevision).populate(builder, context);

    assertThat(root.asXML()).and(expectedXML)
            .ignoreWhitespace()
            .areIdentical();
}
 
Example #4
Source File: DependencyMaterialXmlRepresenterTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@FileSource(files = "/feeds/materials/dependency-material.xml")
void shouldRepresentDependencyMaterial(String expectedXML) {
    Date date = DateUtils.parseISO8601("2019-12-31T15:31:49+05:30");
    DependencyMaterial material = MaterialsMother.dependencyMaterial();
    material.setId(60);
    MaterialRevision revision = new MaterialRevision(material, new Modification(date, "acceptance/63/twist-plugins/2", null, null));
    DOMElement root = new DOMElement("materials");
    ElementBuilder builder = new ElementBuilder(root);
    StageFinder stageFinder = getStageFinder(100L);
    XmlWriterContext context = new XmlWriterContext("https://test.host/go", null, null, stageFinder, new SystemEnvironment());

    new DependencyMaterialXmlRepresenter("up42", 1, revision).populate(builder, context);

    assertThat(root.asXML()).and(expectedXML)
        .ignoreWhitespace()
        .areIdentical();
}
 
Example #5
Source File: PackageMaterialXmlRepresenterTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@FileSource(files = "/feeds/materials/package-material.xml")
void shouldRepresentDependencyMaterial(String expectedXML) {
    Date date = DateUtils.parseISO8601("2019-12-31T15:31:49+05:30");
    PackageMaterial material = MaterialsMother.packageMaterial();
    material.setId(60);
    Modification modification = new Modification("Bob", "Release new package", null, date, "1");
    MaterialRevision revision = new MaterialRevision(material, modification);
    DOMElement root = new DOMElement("materials");
    ElementBuilder builder = new ElementBuilder(root);
    XmlWriterContext context = new XmlWriterContext("https://test.host/go", null, null, null, new SystemEnvironment());

    new PackageMaterialXmlRepresenter("up42", 1, revision).populate(builder, context);

    assertThat(root.asXML()).and(expectedXML)
        .ignoreWhitespace()
        .areIdentical();
}
 
Example #6
Source File: DisabledServiceSettings.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private void convertMapToElementList(Map<String, String> settings) {
    for(Entry<String, String> entry : settings.entrySet()) {
        DOMElement domElement = new DOMElement(new QName(entry.getKey()));
        domElement.setText(entry.getValue());
        entries.add(domElement);
    }
}
 
Example #7
Source File: DocumentBuilder.java    From gocd with Apache License 2.0 5 votes vote down vote up
public static DocumentBuilder withRoot(String name, String xmlns) {
    DOMElement rootElement = new DOMElement(name);
    if (StringUtils.isNotBlank(xmlns)) {
        rootElement.setNamespace(new Namespace("", xmlns));
    }
    return new DocumentBuilder(new DOMDocument(rootElement));
}
 
Example #8
Source File: JobPlanXmlViewModel.java    From gocd with Apache License 2.0 5 votes vote down vote up
private DOMElement getXmlForJobPlan(XmlWriterContext writerContext, WaitingJobPlan waitingJobPlan) {
    JobPlan jobPlan = waitingJobPlan.jobPlan();
    DOMElement root = new DOMElement("job");
    root.addAttribute("name", jobPlan.getName()).addAttribute("id", String.valueOf(jobPlan.getJobId()));
    root.addElement("link").addAttribute("rel", "self").addAttribute("href", httpUrlFor(writerContext.getBaseUrl(), jobPlan.getIdentifier()));
    root.addElement("buildLocator").addText(jobPlan.getIdentifier().buildLocator());
    if (!StringUtils.isBlank(waitingJobPlan.envName())) {
        root.addElement("environment").addText(waitingJobPlan.envName());
    }

    if (!jobPlan.getResources().isEmpty()) {
        DOMElement resources = new DOMElement("resources");

        for (Resource resource : jobPlan.getResources()) {
            resources.addElement("resource").addCDATA(resource.getName());
        }
        root.add(resources);
    }

    if (!jobPlan.getVariables().isEmpty()) {
        DOMElement envVars = new DOMElement("environmentVariables");
        for (EnvironmentVariable environmentVariable : jobPlan.getVariables()) {
            envVars.addElement("variable").addAttribute("name", environmentVariable.getName()).addText(environmentVariable.getDisplayValue());
        }
        root.add(envVars);
    }

    return root;
}
 
Example #9
Source File: JobPlanXmlViewModel.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public Document toXml(XmlWriterContext writerContext) {
    DOMElement root = new DOMElement("scheduledJobs");
    for (WaitingJobPlan jobPlan : jobPlans) {
        DOMElement jobElement = getXmlForJobPlan(writerContext, jobPlan);
        root.add(jobElement);
    }
    DOMDocument domDocument = new DOMDocument(root);
    return domDocument;
}
 
Example #10
Source File: PipelineXmlViewModel.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public Document toXml(XmlWriterContext writerContext) {
    DOMElement root = new DOMElement("pipeline");
    root.addAttribute("name", pipeline.getName()).addAttribute("counter", String.valueOf(pipeline.getCounter())).addAttribute("label", pipeline.getLabel());
    Document document = new DOMDocument(root);
    String baseUrl = writerContext.getBaseUrl();
    root.addElement("link").addAttribute("rel", "self").addAttribute("href", httpUrl(baseUrl));

    root.addElement("id").addCDATA(pipeline.getPipelineIdentifier().asURN());
    PipelineTimelineEntry pipelineAfter = pipeline.getPipelineAfter();
    if (pipelineAfter != null) {
        addTimelineLink(root, baseUrl, "insertedBefore", pipelineAfter);
    }
    PipelineTimelineEntry pipelineBefore = pipeline.getPipelineBefore();
    if (pipelineBefore != null) {
        addTimelineLink(root, baseUrl, "insertedAfter", pipelineBefore);
    }

    root.addElement("scheduleTime").addText(DateUtils.formatISO8601(pipeline.getScheduledDate()));

    Element materials = root.addElement("materials");

    for (MaterialRevision materialRevision : pipeline.getCurrentRevisions()) {
        populateXml(materials, materialRevision, writerContext);

    }

    Element stages = root.addElement("stages");
    for (StageInstanceModel stage : pipeline.getStageHistory()) {
        if (! (stage instanceof NullStageHistoryItem)) {
            stages.addElement("stage").addAttribute("href", StageXmlViewModel.httpUrlFor(writerContext.getBaseUrl(), stage.getId()));
        }
    }

    root.addElement("approvedBy").addCDATA(pipeline.getApprovedBy());
    return document;
}
 
Example #11
Source File: StageXmlViewModel.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public Document toXml(XmlWriterContext writerContext) {
    DOMElement root = new DOMElement("stage");
    root.addAttribute("name", stage.getName()).addAttribute("counter", String.valueOf(stage.getCounter()));
    Document document = new DOMDocument(root);
    root.addElement("link").addAttribute("rel", "self").addAttribute("href", httpUrl(writerContext.getBaseUrl()));

    StageIdentifier stageId = stage.getIdentifier();
    root.addElement("id").addCDATA(stageId.asURN());
    String pipelineName = stageId.getPipelineName();
    root.addElement("pipeline").addAttribute("name", pipelineName)
            .addAttribute("counter", String.valueOf(stageId.getPipelineCounter()))
            .addAttribute("label", stageId.getPipelineLabel())
    .addAttribute("href", writerContext.getBaseUrl() + "/api/pipelines/" + pipelineName + "/" + stage.getPipelineId() + ".xml");

    root.addElement("updated").addText(DateUtils.formatISO8601(stage.latestTransitionDate()));

    root.addElement("result").addText(stage.getResult().toString());

    root.addElement("state").addText(stage.status());

    root.addElement("approvedBy").addCDATA(stage.getApprovedBy());

    Element jobs = root.addElement("jobs");
    for (JobInstance jobInstance : stage.getJobInstances()) {
        jobs.addElement("job").addAttribute("href", writerContext.getBaseUrl() + "/api/jobs/" + jobInstance.getId() + ".xml");
    }

    return document;
}
 
Example #12
Source File: MaterialXmlRepresenter.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public Document toXml(XmlWriterContext ctx) {
    DOMElement rootElement = new DOMElement("material");
    ElementBuilder builder = new ElementBuilder(rootElement);
    populateMaterial(ctx, materialRevision.getMaterial(), builder);
    return new DOMDocument(rootElement);
}
 
Example #13
Source File: VersionUpdater.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @author 
 * @param folderPath
 * @param plug_id
 * @param lastDate
 * @param dayInpast
 */
private void genVersionLog(	File folderPath , 
							String plug_id , 
							String lastDate , 
							int dayInpast ){
	// gen the dest file path
	String parentPath = folderPath.getAbsolutePath();
	String fileName = plug_id + "_DayInPast" + ".xml";
	String fullName = parentPath + "/" + fileName;
	File dest = new File(fullName);
	System.out.println("dest file full path:\t"+fullName);
	try{
		//genarate document factory
		DocumentFactory factory = new DocumentFactory();
		//create root element
		DOMElement rootElement = new DOMElement("plugin");
		rootElement.setAttribute("id",plug_id);
		//add child:lastdate
		DOMElement dateElement = new DOMElement("LastDate");
		dateElement.setText(lastDate);
		rootElement.add(dateElement);
		//add child:dayinpast
		DOMElement dayElement = new DOMElement("DayInPast");
		dayElement.setText( Integer.toString(dayInpast));
		rootElement.add(dayElement);
		//gen the doc
		Document doc = factory.createDocument(rootElement);
	
		//PrettyFormat
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter( new FileWriter(dest) , format );
		writer.write( doc );
		writer.close();

	}catch(Exception ex){
		ex.printStackTrace();
	}

}
 
Example #14
Source File: DOM4JFuncTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testMisc2 ()
{
  final DOMDocument aXML = new DOMDocument ();
  final Node aChild = aXML.appendChild (new DOMElement ("rootElement",
                                                        new DOMNamespace ("xyz", "http://www.example.org")));
  aChild.appendChild (new DOMText ("anyText"));
  aChild.appendChild (new DOMEntityReference ("abc"));

  assertNotNull (XMLWriter.getNodeAsString (aXML));
}
 
Example #15
Source File: Test.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public Element toXmlElement(){        
    test = getTest();

    Element newTest = new DOMElement("test");
    if(getName() != null){
        newTest.addAttribute("name", getName());
    }
    if(getDescription() != null){
        newTest.addAttribute("description", getDescription());
    }
    
    // Pour chaque testcase
    for(TestCase tc : listTestCase){
       // On g�n�re l'�l�ment xml
       tc.toXmlElement();
    }
            
    // Ajout des param�tres du test
    List<Element> params = ParamGenerator.getInstance().paramTestToXml();
    for(Element p : params){            
        newTest.add(p);
    }
    
    
    for(Iterator i = test.elements("testcase").iterator(); i.hasNext();){
        Element elem = (Element)i.next();
        newTest.add(elem.createCopy());
    }      
    
    return newTest;
}
 
Example #16
Source File: Scenario.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public Element toXmlElement(){
    if(getScenario() == null){            
        scenario = new DOMElement("scenario");
    
        if(getName() != null){
            scenario.addAttribute("name", getName());
        }
        if(getPath() != null){
            scenario.setText(getPath());
        }
    }        
    return getScenario();
}
 
Example #17
Source File: StreamManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Attempts to enable Stream Management for the entity identified by the provided JID.
 *
 * @param namespace The namespace that defines what version of SM is to be enabled.
 * @param resume Whether the client is requesting a resumable session.
 */
private void enable( String namespace, boolean resume )
{


    boolean offerResume = allowResume();
    // Ensure that resource binding has occurred.
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        this.namespace = namespace;
        sendUnexpectedError();
        return;
    }

    String smId = null;

    synchronized ( this )
    {
        // Do nothing if already enabled
        if ( isEnabled() )
        {
            sendUnexpectedError();
            return;
        }
        this.namespace = namespace;

        this.resume = resume && offerResume;
        if ( this.resume ) {
            // Create SM-ID.
            smId = StringUtils.encodeBase64( session.getAddress().getResource() + "\0" + session.getStreamID().getID());
        }
    }

    // Send confirmation to the requestee.
    Element enabled = new DOMElement(QName.get("enabled", namespace));
    if (this.resume) {
        enabled.addAttribute("resume", "true");
        enabled.addAttribute("id", smId);
        if ( !namespace.equals(NAMESPACE_V2) && LOCATION_ENABLED.getValue() ) {
            // OF-1925: Hint clients to do resumes at the same cluster node.
            enabled.addAttribute("location", XMPPServer.getInstance().getServerInfo().getHostname());
        }

        // OF-1926: Tell clients how long they can be detached.
        if ( MAX_SERVER_ENABLED.getValue() ) {
            final int sessionDetachTime = XMPPServer.getInstance().getSessionManager().getSessionDetachTime();
            if ( sessionDetachTime > 0 ) {
                enabled.addAttribute("max", String.valueOf(sessionDetachTime/1000));
            }
        }
    }
    session.deliverRawText(enabled.asXML());
}
 
Example #18
Source File: PipelineXmlViewModel.java    From gocd with Apache License 2.0 4 votes vote down vote up
private void addTimelineLink(DOMElement root, String baseUrl, final String rel, final PipelineTimelineEntry entry) {
    root.addElement("link").addAttribute("rel", rel).addAttribute("href", httpUrlForPipeline(baseUrl, entry.getId(), pipeline.getName()));
}
 
Example #19
Source File: JobXmlViewModel.java    From gocd with Apache License 2.0 4 votes vote down vote up
@Override
public Document toXml(XmlWriterContext writerContext) {
    DOMElement root = new DOMElement("job");
    root.addAttribute("name", jobInstance.getName());
    Document document = new DOMDocument(root);
    root.addElement("link").addAttribute("rel", "self").addAttribute("href", httpUrl(writerContext.getBaseUrl()));

    JobIdentifier identifier = jobInstance.getIdentifier();
    root.addElement("id").addCDATA(identifier.asURN());
    String pipelineName = identifier.getPipelineName();
    StageIdentifier stageId = identifier.getStageIdentifier();

    root.addElement("pipeline").addAttribute("name", pipelineName)
            .addAttribute("counter", String.valueOf(stageId.getPipelineCounter()))
            .addAttribute("label", stageId.getPipelineLabel());

    root.addElement("stage").addAttribute("name", stageId.getStageName()).addAttribute("counter", stageId.getStageCounter()).addAttribute("href", StageXmlViewModel.httpUrlFor(
            writerContext.getBaseUrl(),
            jobInstance.getStageId()));

    root.addElement("result").addText(jobInstance.getResult().toString());

    root.addElement("state").addText(jobInstance.getState().toString());

    Element properties = root.addElement("properties");

    root.addElement("agent").addAttribute("uuid", jobInstance.getAgentUuid());

    root.addComment("artifacts of type `file` will not be shown. See https://github.com/gocd/gocd/pull/2875");
    Element artifacts = root.addElement("artifacts");
    artifacts.addAttribute("baseUri", writerContext.artifactBaseUrl(identifier)).addAttribute("pathFromArtifactRoot", writerContext.artifactRootPath(identifier));

    JobPlan jobPlan = writerContext.planFor(identifier);
    for (ArtifactPlan artifactPlan : jobPlan.getArtifactPlansOfType(ArtifactPlanType.unit)) {
        artifacts.addElement("artifact").addAttribute("src", artifactPlan.getSrc()).addAttribute("dest", artifactPlan.getDest()).addAttribute("type", artifactPlan.getArtifactPlanType().toString());
    }

    // Retain the top level elements for backward-compatibility
    root.addComment("resources are now intentionally left blank. See https://github.com/gocd/gocd/pull/2875");
    root.addElement("resources");
    root.addComment("environmentvariables are now intentionally left blank. See https://github.com/gocd/gocd/pull/2875");
    root.addElement("environmentvariables");

    return document;
}
 
Example #20
Source File: XMLVisitor.java    From compiler with Apache License 2.0 4 votes vote down vote up
private void visit(DOMElement node) {
	Element.Builder b = Element.newBuilder();
	b.setKind(ElementKind.XML_ELEMENT);
	b.setTag(node.getQualifiedName());
	Namespace ns = node.getNamespace();
	if (!ns.getURI().equals("")){
		Ast.Attribute.Builder ab = Ast.Attribute.newBuilder();
		ab.setKey(ns.getPrefix() + " URI");
		ab.setValue(ns.getURI());
		b.addAttributes(ab.build());
	}
	DOMAttributeNodeMap attr = (DOMAttributeNodeMap) node.getAttributes();
	for (int i = 0; i < attr.getLength(); i++) {
		DOMAttribute a = (DOMAttribute) attr.item(i);
		visit(a);
		b.addAttributes(Attributes.pop());
	}
	elements.push(new ArrayList<boa.types.Ast.Element>());
	NodeList children = node.getChildNodes();
	for (int i = 0; i < children.getLength(); i++){
		Node n = (Node) children.item(i);
		switch (n.getNodeType()){
			case(org.dom4j.Node.ELEMENT_NODE):
				visit((org.dom4j.dom.DOMElement)n);
				break;
			case(org.dom4j.Node.TEXT_NODE):
				String t = ((DOMText) n).getText();
				String check = t.replaceAll(" ", "");
				if (!check.equals("") && !check.equals("\n") && !check.equals("\n\n") && !check.equals("\n  ") && !check.equals("\n    ") )
					b.addText(t);
				break;
		}
	}
	
	for (ProcessingInstruction pi : node.processingInstructions()){
		visit((DOMProcessingInstruction)pi);
		b.addProcessingInstruction(Attributes.pop());
	}
	
	
	for (Ast.Element e : elements.pop())
		b.addElements(e);
	elements.peek().add(b.build());
	
}
 
Example #21
Source File: ElementBuilder.java    From gocd with Apache License 2.0 4 votes vote down vote up
public ElementBuilder(DOMElement parent) {
    super(ElementBuilder.class, parent);
}
 
Example #22
Source File: AbstractBuilder.java    From gocd with Apache License 2.0 4 votes vote down vote up
public SELF node(String name, Consumer<ElementBuilder> consumer) {
    DOMElement element = withNamespace(name);
    current().add(element);
    consumer.accept(new ElementBuilder(element));
    return mySelf;
}
 
Example #23
Source File: AbstractBuilder.java    From gocd with Apache License 2.0 4 votes vote down vote up
public SELF emptyNode(String name) {
    DOMElement element = withNamespace(name);
    current().add(element);
    return mySelf;
}
 
Example #24
Source File: AbstractBuilder.java    From gocd with Apache License 2.0 4 votes vote down vote up
private DOMElement withNamespace(String name) {
    DOMElement element = new DOMElement(name);
    getDefaultNameSpace().ifPresent(element::setNamespace);
    return element;
}
 
Example #25
Source File: Help.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
public static void save(Furnace furnace) throws IOException
{
    Document doc = new DOMDocument(new DOMElement(HELP));
    Iterable<ConfigurationOption> windupOptions = WindupConfiguration.getWindupConfigurationOptions(furnace);
    for (ConfigurationOption option : windupOptions)
    {
        Element optionElement = new DOMElement(OPTION);
        optionElement.addAttribute(NAME, option.getName());

        Element descriptionElement = new DOMElement(DESCRIPTION);
        descriptionElement.setText(option.getDescription());
        optionElement.add(descriptionElement);

        // Type
        Element typeElement = new DOMElement(TYPE);
        typeElement.setText(option.getType().getSimpleName());
        optionElement.add(typeElement);

        // UI Type
        Element uiTypeElement = new DOMElement(UI_TYPE);
        uiTypeElement.setText(option.getUIType().name());
        optionElement.add(uiTypeElement);

        // Available Options
        Element availableOptionsElement = new DOMElement(AVAILABLE_OPTIONS);
        for (Object availableValueObject : option.getAvailableValues())
        {
            if (availableValueObject == null)
                continue;

            Element availableOption = new DOMElement(AVAILABLE_OPTION);
            availableOption.setText(String.valueOf(availableValueObject));
            availableOptionsElement.add(availableOption);
        }
        if (!availableOptionsElement.elements().isEmpty())
            optionElement.add(availableOptionsElement);

        // Is it required?
        Element required = new DOMElement(REQUIRED);
        required.setText(Boolean.toString(option.isRequired()));
        optionElement.add(required);

        doc.getRootElement().add(optionElement);
    }

    try (FileWriter writer = new FileWriter(getDefaultFile()))
    {
        doc.write(writer);
    }
}