Example usage for org.w3c.dom Element setAttribute

List of usage examples for org.w3c.dom Element setAttribute

Introduction

In this page you can find the example usage for org.w3c.dom Element setAttribute.

Prototype

public void setAttribute(String name, String value) throws DOMException;

Source Link

Document

Adds a new attribute.

Usage

From source file:fi.csc.kapaVirtaAS.WSDLManipulator.java

public Element soapHeader(Element el, String message, String part, String use) {
    el.setAttribute("message", message);
    el.setAttribute("part", part);
    el.setAttribute("use", use);
    return el;//  w ww . java2 s . co  m
}

From source file:de.pixida.logtest.reporting.XUnitReportGenerator.java

@Override
public void finish() {
    try {// w  w  w .  j av a  2s .co m
        // Create document
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // Create root element
        final Document doc = docBuilder.newDocument();
        final Element rootElement = doc.createElement("testsuite");
        rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        rootElement.setAttribute("xsi:schemaLocation",
                "https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report.xsd");
        rootElement.setAttribute("name", "LogFileAnalysisTestsuite");
        final double msToSec = 1000.0;
        rootElement.setAttribute("time", String.valueOf(this.totalTimeMs / msToSec));
        final long numTests = this.results.size();
        final long numSuccesses = this.results.values().stream()
                .mapToLong(result -> result.stream().filter(r -> r.getMiddle().isSuccess()).count()).sum();
        final long numFailures = this.results.values().stream()
                .mapToLong(result -> result.stream().filter(r -> r.getMiddle().isFailure()).count()).sum();
        final long numSkipped = 0L;
        final long numErrors = numTests - numSuccesses - numFailures;
        rootElement.setAttribute("tests", String.valueOf(numTests));
        rootElement.setAttribute("errors", String.valueOf(numErrors));
        rootElement.setAttribute("skipped", String.valueOf(numSkipped));
        rootElement.setAttribute("failures", String.valueOf(numFailures));
        doc.appendChild(rootElement);

        // Create payload
        this.addProperties(doc, rootElement);
        this.addTestCases(doc, rootElement);

        // Dump results into file
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        final DOMSource source = new DOMSource(doc);
        final File parentFile = this.destFile.getParentFile();
        if (parentFile != null) {
            parentFile.mkdirs(); // If fails, will be caught by the following operations
        }
        final StreamResult result = new StreamResult(this.destFile);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, result);
    } catch (final DOMException | TransformerException | ParserConfigurationException e) {
        LOG.error("Failed to write results", e);
    }
}

From source file:com.twinsoft.convertigo.engine.admin.services.mobiles.GetBuildStatus.java

@Override
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    String project = Keys.project.value(request);

    MobileApplication mobileApplication = getMobileApplication(project);

    if (mobileApplication == null) {
        throw new ServiceException("no such mobile application");
    } else {//w w w. j  a  va2  s  .co  m
        boolean bAdminRole = Engine.authenticatedSessionManager.hasRole(request.getSession(), Role.WEB_ADMIN);
        if (!bAdminRole && mobileApplication.getAccessibility() == Accessibility.Private) {
            throw new AuthenticationException("Authentication failure: user has not sufficient rights!");
        }
    }

    String platformName = Keys.platform.value(request);

    String mobileBuilderPlatformURL = EnginePropertiesManager
            .getProperty(PropertyName.MOBILE_BUILDER_PLATFORM_URL);

    URL url = new URL(mobileBuilderPlatformURL + "/getstatus");

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(url.getHost());
    HttpState httpState = new HttpState();
    Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);

    PostMethod method = new PostMethod(url.toString());

    JSONObject jsonResult;
    try {
        HeaderName.ContentType.setRequestHeader(method, MimeType.WwwForm.value());
        method.setRequestBody(new NameValuePair[] {
                new NameValuePair("application", mobileApplication.getComputedApplicationName()),
                new NameValuePair("platformName", platformName),
                new NameValuePair("auth_token", mobileApplication.getComputedAuthenticationToken()),
                new NameValuePair("endpoint", mobileApplication.getComputedEndpoint(request)) });

        int methodStatusCode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState);

        InputStream methodBodyContentInputStream = method.getResponseBodyAsStream();
        byte[] httpBytes = IOUtils.toByteArray(methodBodyContentInputStream);
        String sResult = new String(httpBytes, "UTF-8");

        if (methodStatusCode != HttpStatus.SC_OK) {
            throw new ServiceException(
                    "Unable to get building status for application '" + project + "' (final app name: '"
                            + mobileApplication.getComputedApplicationName() + "').\n" + sResult);
        }

        jsonResult = new JSONObject(sResult);
    } finally {
        method.releaseConnection();
    }

    Element statusElement = document.createElement("build");
    statusElement.setAttribute(Keys.project.name(), project);
    statusElement.setAttribute(Keys.platform.name(), platformName);

    if (jsonResult.has(platformName + "_status")) {
        statusElement.setAttribute("status", jsonResult.getString(platformName + "_status"));
    } else {
        statusElement.setAttribute("status", "none");
    }

    if (jsonResult.has(platformName + "_error")) {
        statusElement.setAttribute("error", jsonResult.getString(platformName + "_error"));
    }

    statusElement.setAttribute("version", jsonResult.has("version") ? jsonResult.getString("version") : "n/a");
    statusElement.setAttribute("phonegap_version",
            jsonResult.has("phonegap_version") ? jsonResult.getString("phonegap_version") : "n/a");

    statusElement.setAttribute("revision",
            jsonResult.has("revision") ? jsonResult.getString("revision") : "n/a");
    statusElement.setAttribute("endpoint",
            jsonResult.has("endpoint") ? jsonResult.getString("endpoint") : "n/a");

    document.getDocumentElement().appendChild(statusElement);
}

From source file:ddf.security.samlp.SimpleSignTest.java

@Test(expected = SimpleSign.SignatureException.class)
public void testSignSamlObjectThenModify() throws Exception {

    Document responseDoc = StaxUtils.read(new ByteArrayInputStream(cannedResponse.getBytes()));
    XMLObject responseXmlObject = OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
    org.opensaml.saml.saml2.core.Response response = (org.opensaml.saml.saml2.core.Response) responseXmlObject;
    simpleSign.signSamlObject(response);

    Document doc = DOMUtils.createDocument();
    Element requestElement = OpenSAMLUtil.toDom(response, doc);
    requestElement.setAttribute("oops", "changedit");
    String responseMessage = DOM2Writer.nodeToString(requestElement);
    responseDoc = StaxUtils.read(new ByteArrayInputStream(responseMessage.getBytes()));
    responseXmlObject = OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
    response = (org.opensaml.saml.saml2.core.Response) responseXmlObject;
    simpleSign.validateSignature(response.getSignature(), response.getDOM().getOwnerDocument());
}

From source file:de.erdesignerng.model.serializer.xml30.XMLDomainSerializer.java

@Override
public void serialize(Domain aDomain, Document aDocument, Element aRootElement) {
    Element theDomainElement = addElement(aDocument, aRootElement, DOMAIN);

    // Basisdaten des Modelelementes speichern
    serializeProperties(aDocument, theDomainElement, aDomain);

    theDomainElement.setAttribute(DATATYPE, aDomain.getConcreteType().getName());

    // Bug Fixing 2876916 [ERDesignerNG] Reverse-Eng. PgSQL VARCHAR max-length wrong
    theDomainElement.setAttribute(SIZE, safeString(aDomain.getSize()));

    theDomainElement.setAttribute(FRACTION, safeString(aDomain.getFraction()));
    theDomainElement.setAttribute(SCALE, safeString(aDomain.getScale()));
    theDomainElement.setAttribute(NULLABLE, safeString(aDomain.isNullable()));
}

From source file:fr.aliasource.webmail.invitation.GetInvitationInfoAction.java

private void addListEvent(Element root, List<Event> eventsOfDay) {
    Element eventsElem = DOMUtils.createElement(root, "eventsOfDay");
    for (Event event : eventsOfDay) {
        Element eventElem = DOMUtils.createElement(eventsElem, "eventOfDay");
        eventElem.setAttribute("title", event.getTitle());
        eventElem.setAttribute("start", Long.toString(clearDate(event.getDate()).getTime()));
        eventElem.setAttribute("allDay", Boolean.toString(event.isAllday()));

    }//from w  w w .  j  av  a2 s  . c o m
}

From source file:com.microsoft.tfs.core.credentials.internal.CachedCredentialsSerializer.java

private void serializeCredentials(final CachedCredentials credentials, final Document document,
        final Element parentElement) {
    final Element credentialsElement = DOMUtils.appendChild(parentElement, CREDENTIALS_ELEMENT_NAME);
    credentialsElement.setAttribute(URI_ATTRIBUTE_NAME,
            URIUtils.removeTrailingSlash(credentials.getURI()).toString());

    if (credentials.getUsername() != null) {
        DOMUtils.appendChildWithText(credentialsElement, USERNAME_ELEMENT_NAME,
                encodeCredentialField(credentials.getUsername()));
    }/*w  ww.  j a  v a2s.  com*/

    if (credentials.getPassword() != null) {
        DOMUtils.appendChildWithText(credentialsElement, PASSWORD_ELEMENT_NAME,
                encodeCredentialField(credentials.getPassword()));
    }
}

From source file:com.aipo.container.gadgets.render.AipoRenderingGadgetRewriter.java

@Override
public void rewrite(Gadget gadget, MutableContent mutableContent) throws RewritingException {
    // Don't touch sanitized gadgets.
    if (gadget.sanitizeOutput()) {
        return;/*from w w  w. j  av  a2s . com*/
    }
    try {
        Document document = mutableContent.getDocument();

        Element head = (Element) DomUtil.getFirstNamedChildNode(document.getDocumentElement(), "head");

        // Insert new content before any of the existing children of the head
        // element
        Node firstHeadChild = head.getFirstChild();

        Element contentLanguage = document.createElement("meta");
        contentLanguage.setAttribute("http-equiv", "Content-Language");
        contentLanguage.setAttribute("content", "ja");
        head.insertBefore(contentLanguage, firstHeadChild);

        Element contentType = document.createElement("meta");
        contentType.setAttribute("http-equiv", "Content-Type");
        contentType.setAttribute("content", "text/html; charset=UTF-8");
        head.insertBefore(contentType, firstHeadChild);

        Element contentStyleType = document.createElement("meta");
        contentStyleType.setAttribute("http-equiv", "Content-Style-Type");
        contentStyleType.setAttribute("content", "text/css");
        head.insertBefore(contentStyleType, firstHeadChild);

        Element contentScriptType = document.createElement("meta");
        contentScriptType.setAttribute("http-equiv", "Content-Script-Type");
        contentScriptType.setAttribute("content", "text/javascript");
        head.insertBefore(contentScriptType, firstHeadChild);

        // Only inject default styles if no doctype was specified.
        // if (document.getDoctype() == null) {
        boolean isAipoStyle = gadget.getAllFeatures().contains("aipostyle")
                && gadget.getSpec().getModulePrefs().getFeatures().keySet().contains("aipostyle");
        Element defaultStyle = document.createElement("style");
        defaultStyle.setAttribute("type", "text/css");
        head.insertBefore(defaultStyle, firstHeadChild);
        defaultStyle.appendChild(
                defaultStyle.getOwnerDocument().createTextNode(isAipoStyle ? aipoStyleCss : DEFAULT_CSS));
        // }

        injectBaseTag(gadget, head);
        injectGadgetBeacon(gadget, head, firstHeadChild);
        injectFeatureLibraries(gadget, head, firstHeadChild);

        // This can be one script block.
        Element mainScriptTag = document.createElement("script");
        GadgetContext context = gadget.getContext();
        MessageBundle bundle = messageBundleFactory.getBundle(gadget.getSpec(), context.getLocale(),
                context.getIgnoreCache(), context.getContainer());
        injectMessageBundles(bundle, mainScriptTag);
        injectDefaultPrefs(gadget, mainScriptTag);
        injectPreloads(gadget, mainScriptTag);

        // We need to inject our script before any developer scripts.
        head.insertBefore(mainScriptTag, firstHeadChild);

        Element body = (Element) DomUtil.getFirstNamedChildNode(document.getDocumentElement(), "body");

        body.setAttribute("dir", bundle.getLanguageDirection());

        injectOnLoadHandlers(body);

        mutableContent.documentChanged();
    } catch (GadgetException e) {
        throw new RewritingException(e.getLocalizedMessage(), e, e.getHttpStatusCode());
    }
}

From source file:importer.handler.post.stages.Splitter.java

/**
 * Add a custom attribute signalling that this node's versions are "done"
 * @param elem the element to mark thus/*from  ww w  . j a  v  a2  s.  c  o m*/
 */
private void addDoneTag(Element elem) {
    elem.setAttribute(DONE, DONE);
}

From source file:com.msopentech.odatajclient.engine.data.impl.v3.AtomSerializer.java

private Element feed(final AtomFeed feed) throws ParserConfigurationException {
    final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
    final Document doc = builder.newDocument();

    final Element feedElem = doc.createElement(ODataConstants.ATOM_ELEM_FEED);
    feedElem.setAttribute(XMLConstants.XMLNS_ATTRIBUTE, ODataConstants.NS_ATOM);
    feedElem.setAttribute(ODataConstants.XMLNS_METADATA,
            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA));
    feedElem.setAttribute(ODataConstants.XMLNS_DATASERVICES,
            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES));
    feedElem.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
    feedElem.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
    if (feed.getBaseURI() != null) {
        feedElem.setAttribute(ODataConstants.ATTR_XMLBASE, feed.getBaseURI().toASCIIString());
    }/*from   ww  w .  j a v  a2  s  . c om*/
    doc.appendChild(feedElem);

    if (StringUtils.isNotBlank(feed.getTitle())) {
        final Element title = doc.createElement(ODataConstants.ATOM_ELEM_TITLE);
        title.appendChild(doc.createTextNode(feed.getTitle()));
        feedElem.appendChild(title);
    }

    if (StringUtils.isNotBlank(feed.getSummary())) {
        final Element summary = doc.createElement(ODataConstants.ATOM_ELEM_SUMMARY);
        summary.appendChild(doc.createTextNode(feed.getSummary()));
        feedElem.appendChild(summary);
    }

    for (AtomEntry entry : feed.getEntries()) {
        feedElem.appendChild(doc.importNode(entry(entry), true));
    }

    return feedElem;
}