Example usage for org.jdom2 Attribute setValue

List of usage examples for org.jdom2 Attribute setValue

Introduction

In this page you can find the example usage for org.jdom2 Attribute setValue.

Prototype

public Attribute setValue(final String value) 

Source Link

Document

This will set the value of the Attribute.

Usage

From source file:com.archimatetool.editor.model.compatibility.Archimate2To3Converter.java

License:Open Source License

/**
 * Convert concept name types//from   w  ww .  j  a  va 2 s. c  o m
 */
private void convertConceptTypeName(Element element) {
    Attribute attType = element.getAttribute("type", JDOMUtils.XSI_Namespace);

    if (attType != null) {
        String oldValue = attType.getValue();
        String newValue = ConceptNameMapping.get(oldValue);

        if (newValue != null) {
            attType.setValue(newValue);
        }

        // Or Junction has type set
        if ("archimate:OrJunction".equals(oldValue)) {
            element.setAttribute("type", "or");
        }
    }
}

From source file:com.archimatetool.editor.model.compatibility.Archimate2To3Converter.java

License:Open Source License

private void setAttributeValue(Element element, String attributeName, String newValue) {
    if (element != null) {
        Attribute attribute = element.getAttribute(attributeName);
        if (attribute != null) {
            attribute.setValue(newValue);
        }//w w  w. j a  va2  s.  com
    }
}

From source file:com.thoughtworks.go.config.ConfigCipherUpdater.java

License:Apache License

public void migrate() {
    File cipherFile = systemEnvironment.getDESCipherFile();
    String timestamp = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(timeProvider.currentTime());

    File backupCipherFile = new File(systemEnvironment.getConfigDir(), "cipher.original." + timestamp);
    File configFile = new File(systemEnvironment.getCruiseConfigFile());
    File backupConfigFile = new File(configFile.getParentFile(),
            configFile.getName() + ".original." + timestamp);
    try {//from  w  ww  .  j a  va2  s.co m
        if (!cipherFile.exists() || !FileUtils.readFileToString(cipherFile, UTF_8).equals(FLAWED_VALUE)) {
            return;
        }
        LOGGER.info("Found unsafe cipher {} on server, Go will make an attempt to rekey", FLAWED_VALUE);
        FileUtils.copyFile(cipherFile, backupCipherFile);
        LOGGER.info("Old cipher was successfully backed up to {}", backupCipherFile.getAbsoluteFile());
        FileUtils.copyFile(configFile, backupConfigFile);
        LOGGER.info("Old config was successfully backed up to {}", backupConfigFile.getAbsoluteFile());

        String oldCipher = FileUtils.readFileToString(backupCipherFile, UTF_8);
        new DESCipherProvider(systemEnvironment).resetCipher();

        String newCipher = FileUtils.readFileToString(cipherFile, UTF_8);

        if (newCipher.equals(oldCipher)) {
            LOGGER.warn("Unable to generate a new safe cipher. Your cipher is unsafe.");
            FileUtils.deleteQuietly(backupCipherFile);
            FileUtils.deleteQuietly(backupConfigFile);
            return;
        }
        Document document = new SAXBuilder().build(configFile);
        List<String> encryptedAttributes = Arrays.asList("encryptedPassword", "encryptedManagerPassword");
        List<String> encryptedNodes = Arrays.asList("encryptedValue");
        XPathFactory xPathFactory = XPathFactory.instance();
        for (String attributeName : encryptedAttributes) {
            XPathExpression<Element> xpathExpression = xPathFactory
                    .compile(String.format("//*[@%s]", attributeName), Filters.element());
            List<Element> encryptedPasswordElements = xpathExpression.evaluate(document);
            for (Element element : encryptedPasswordElements) {
                Attribute encryptedPassword = element.getAttribute(attributeName);
                encryptedPassword.setValue(reEncryptUsingNewKey(decodeHex(oldCipher), decodeHex(newCipher),
                        encryptedPassword.getValue()));
                LOGGER.debug("Replaced encrypted value at {}", element.toString());
            }
        }
        for (String nodeName : encryptedNodes) {
            XPathExpression<Element> xpathExpression = xPathFactory.compile(String.format("//%s", nodeName),
                    Filters.element());
            List<Element> encryptedNode = xpathExpression.evaluate(document);
            for (Element element : encryptedNode) {
                element.setText(
                        reEncryptUsingNewKey(decodeHex(oldCipher), decodeHex(newCipher), element.getValue()));
                LOGGER.debug("Replaced encrypted value at {}", element.toString());
            }
        }
        try (FileOutputStream fileOutputStream = new FileOutputStream(configFile)) {
            XmlUtils.writeXml(document, fileOutputStream);
        }
        LOGGER.info("Successfully re-encrypted config");
    } catch (Exception e) {
        LOGGER.error("Re-keying of cipher failed with error: [{}]", e.getMessage(), e);
        if (backupCipherFile.exists()) {
            try {
                FileUtils.copyFile(backupCipherFile, cipherFile);
            } catch (IOException e1) {
                LOGGER.error(
                        "Could not replace the cipher file [{}] with original one [{}], please do so manually. Error: [{}]",
                        cipherFile.getAbsolutePath(), backupCipherFile.getAbsolutePath(), e.getMessage(), e);
                bomb(e1);
            }
        }
    }
}

From source file:com.xebialabs.overcast.support.libvirt.jdom.DiskXml.java

License:Apache License

/**
 * update the disks in the domain XML. It is assumed that the the size of the volumes is the same as the number of
 * disk elements and that the order is the same.
 *//* w  w w.  java  2s .co  m*/
public static void updateDisks(Document domainXml, List<StorageVol> volumes) throws LibvirtException {
    XPathFactory xpf = XPathFactory.instance();
    XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element());
    XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute());
    List<Element> disks = diskExpr.evaluate(domainXml);
    Iterator<StorageVol> cloneDiskIter = volumes.iterator();
    for (Element disk : disks) {
        Attribute file = fileExpr.evaluateFirst(disk);
        StorageVol cloneDisk = cloneDiskIter.next();
        file.setValue(cloneDisk.getPath());
    }
}

From source file:edu.wisc.ssec.adapter.NetCDFFile.java

License:Open Source License

public static NetCDFFile makeUnion(String filename, String other) throws Exception {
    Object obj = new Object();
    URL url = obj.getClass().getResource("/edu/wisc/ssec/mcidasv/data/hydra/resources/union.ncml");
    SAXBuilder builder = new SAXBuilder(false);
    Document doc = null;/*from  w  ww  . j  av a  2s  .  c  o  m*/

    try {
        doc = builder.build(url);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Element root = doc.getRootElement();

    List list = root.getChildren();

    list = ((Element) list.get(1)).getChildren();

    org.jdom2.Attribute attr1 = (org.jdom2.Attribute) (((Element) list.get(0)).getAttributes()).get(0);
    attr1.setValue(filename);

    org.jdom2.Attribute attr2 = (org.jdom2.Attribute) (((Element) list.get(1)).getAttributes()).get(0);
    attr2.setValue(other);

    XMLOutputter xmlOut = new XMLOutputter();
    String newStr = xmlOut.outputString(doc);
    ByteArrayInputStream is = new ByteArrayInputStream(newStr.getBytes());
    return new NetCDFFile(is);
}

From source file:edu.wisc.ssec.mcidasv.data.hydra.NetCDFFile.java

License:Open Source License

public static NetCDFFile makeUnion(String filename, String other) throws Exception {
    Object obj = new Object();
    URL url = obj.getClass().getResource("/edu/wisc/ssec/mcidasv/data/hydra/resources/union.ncml");
    SAXBuilder builder = new SAXBuilder(false);
    Document doc = null;/*from w  w  w.j a va2  s  .  c o m*/

    try {
        doc = builder.build(url);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Element root = doc.getRootElement();

    List list = root.getChildren();

    list = ((Element) list.get(1)).getChildren();

    org.jdom2.Attribute attr1 = (((Element) list.get(0)).getAttributes()).get(0);
    attr1.setValue(filename);

    org.jdom2.Attribute attr2 = (((Element) list.get(1)).getAttributes()).get(0);
    attr2.setValue(other);

    XMLOutputter xmlOut = new XMLOutputter();
    String newStr = xmlOut.outputString(doc);
    logger.trace("union string:\n{}", newStr);
    ByteArrayInputStream is = new ByteArrayInputStream(newStr.getBytes());
    return new NetCDFFile(is);
}

From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java

License:Apache License

/**
 * Method that generates a complexType tag, wherever it has to be generated and in the correct way
 * @param configuration the inference configuration
 * @param complexType the complex type to which the tag will be generated
 * @param anonymous whether this complex type must be anonymous (i.e. it must not have a 'name' attribute)
 * @param targetNamespace the target namespace which is currently being generated
 * @param namespaceURIToPrefixMappings solved mappings between namespace URIs and prefixes
 * @param mainNamespace main namespace/*from  w  w w  .  j a  v a 2  s  .  com*/
 * @param xsdNamespace namespace of the XML Schema
 * @return a JDOM2 {@link Element} which describes the complex type
 */
private Element generateComplexType(XSDInferenceConfiguration configuration, ComplexType complexType,
        boolean anonymous, String targetNamespace, Map<String, String> namespaceURIToPrefixMappings,
        String mainNamespace, Namespace xsdNamespace) {
    Element complexTypeElement = new Element("complexType", xsdNamespace);
    for (String commentOnComplexType : ImmutableSortedSet.copyOf(complexType.getComments())) {
        complexTypeElement.addContent(new Comment(commentOnComplexType));
    }
    if (!anonymous) {
        Attribute complexTypeNameAttr = new Attribute("name", "");
        complexTypeNameAttr.setValue(complexType.getName());
        complexTypeElement.setAttribute(complexTypeNameAttr);
    }
    SimpleType simpleType = complexType.getTextSimpleType();
    boolean hasChildren = !complexType.getRegularExpression().equals(new EmptyRegularExpression());
    boolean hasNonWhitespaceSimpleContent = !simpleType.isEmpty()
            && !simpleType.consistOnlyOfWhitespaceCharacters();
    if (hasChildren) {
        //Mixed complex type. As far as I know, XSD does not allow to constraint simple content on mixed types
        if (hasNonWhitespaceSimpleContent) {
            Attribute mixedAttr = new Attribute("mixed", "");
            mixedAttr.setValue("true");
            complexTypeElement.setAttribute(mixedAttr);
        }
        Element childrenContent = generateRegexpRepresentation(complexType.getRegularExpression(),
                configuration, targetNamespace, mainNamespace, complexType, namespaceURIToPrefixMappings,
                xsdNamespace);
        if (childrenContent.getName().equals("element")) {
            Element unwrappedChildrenContent = childrenContent;
            childrenContent = new Element("sequence", xsdNamespace);
            childrenContent.addContent(unwrappedChildrenContent);
        }
        complexTypeElement.addContent(childrenContent);
        List<Element> attributesInfo = generateAttributeList(complexType, targetNamespace, mainNamespace,
                configuration, namespaceURIToPrefixMappings, xsdNamespace);
        complexTypeElement.addContent(attributesInfo);
    } else if (complexType.getAttributeList().size() > 0 && !simpleType.isEmpty()) {
        Element simpleContentElement = new Element("simpleContent", xsdNamespace);
        Element extensionElement = new Element("extension", xsdNamespace);
        Attribute extensionBaseAttr = new Attribute("base", "");
        String simpleTypeRepresentationName = complexType.getTextSimpleType()
                .getRepresentationName(configuration.getTypeNamesAncestorsSeparator());
        if (!simpleTypeRepresentationName.contains(XSD_NAMESPACE_PREFIX)
                && !namespaceURIToPrefixMappings.get(mainNamespace).equals("")) {
            simpleTypeRepresentationName = namespaceURIToPrefixMappings.get(mainNamespace) + ":"
                    + simpleTypeRepresentationName;
        }
        extensionBaseAttr.setValue(simpleTypeRepresentationName);
        extensionElement.setAttribute(extensionBaseAttr);
        List<Element> attributesInfo = generateAttributeList(complexType, targetNamespace, mainNamespace,
                configuration, namespaceURIToPrefixMappings, xsdNamespace);
        extensionElement.addContent(attributesInfo);
        simpleContentElement.addContent(extensionElement);
        complexTypeElement.addContent(simpleContentElement);
    } else if (complexType.getAttributeList().size() > 0) {
        List<Element> attributesInfo = generateAttributeList(complexType, targetNamespace, mainNamespace,
                configuration, namespaceURIToPrefixMappings, xsdNamespace);
        complexTypeElement.addContent(attributesInfo);
    }
    //If the complex type consists of a non empty simple type without either children or attributes, no complexType tag would be generated, so it is not handled here
    return complexTypeElement;

}

From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java

License:Apache License

/**
 * Generates an element that describes an attribute (including name, type and optionality)
 * @param schemaAttribute the attribute to describe
 * @param isGlobal whether it will be declared globally or not
 * @param configuration the inference configuration
 * @param namespaceURIToPrefixMappings the solved mappings between namespace URIs and prefixes
 * @param targetNamespace the target namespace of the XSD that is being currently generated
 * @param mainNamespace the main namespace
 * @param schemaAttributeKey the key used at the {@link Schema} attributes structures, which will be 
 * also used to name attribute groups used at inter-namespace importing and exporting when the 
 * workaround is enabled./*from www  .  j  a  v  a 2s  .c  o m*/
 * @param xsdNamespace the XSD namespace
 * @return a JDOM2 {@link Element} describing the attribute
 */
private Element generateAttribute(SchemaAttribute schemaAttribute, boolean isGlobal,
        XSDInferenceConfiguration configuration, Map<String, String> namespaceURIToPrefixMappings,
        String targetNamespace, String mainNamespace, String schemaAttributeKey, Namespace xsdNamespace) {

    Element attributeElement = new Element("attribute", xsdNamespace);
    boolean workaround = configuration.getStrictValidRootDefinitionWorkaround();
    boolean belongsToSkippedNamespace = configuration.getSkipNamespaces().contains(
            schemaAttribute.getNamespace()) || schemaAttribute.getNamespace().equals(xsdNamespace.getURI());
    if ((schemaAttribute.getNamespace().equals(mainNamespace) || schemaAttribute.getNamespace().equals(""))
            || (isGlobal && (!workaround))) {
        fillNormalAttributeElement(schemaAttribute, attributeElement, configuration,
                namespaceURIToPrefixMappings, targetNamespace, mainNamespace, isGlobal, xsdNamespace);

        return attributeElement;
    } else if (!isGlobal && (!workaround || belongsToSkippedNamespace)) {
        Attribute attributeRefAttr = new Attribute("ref", "");
        String namespacePrefix = namespaceURIToPrefixMappings.get(schemaAttribute.getNamespace());
        String attributeRefValue = schemaAttribute.getName();
        if (!namespacePrefix.equals(""))
            attributeRefValue = namespacePrefix + ":" + attributeRefValue;
        attributeRefAttr.setValue(attributeRefValue);
        attributeElement.setAttribute(attributeRefAttr);
        return attributeElement;
    } else {
        Element attributeGroupElement = new Element("attributeGroup", xsdNamespace);
        if (isGlobal) {
            Attribute attributeGroupNameAttr = new Attribute("name", "");
            attributeGroupNameAttr.setValue(schemaAttributeKey);
            attributeGroupElement.setAttribute(attributeGroupNameAttr);
            fillNormalAttributeElement(schemaAttribute, attributeElement, configuration,
                    namespaceURIToPrefixMappings, targetNamespace, mainNamespace, isGlobal, xsdNamespace);
            attributeGroupElement.addContent(attributeElement);
            return attributeGroupElement;
        } else {
            Attribute attributeGroupRefAttr = new Attribute("ref", "");
            String namespacePrefix = namespaceURIToPrefixMappings.get(schemaAttribute.getNamespace());
            String refValue = "";
            if (!namespacePrefix.equals(""))
                refValue = namespacePrefix + ":";
            refValue += schemaAttributeKey;
            attributeGroupRefAttr.setValue(refValue);
            attributeGroupElement.setAttribute(attributeGroupRefAttr);
            Attribute attributeUseAttr = new Attribute("use", "");
            String attributeUseValue = schemaAttribute.isOptional() ? "optional" : "required";
            attributeUseAttr.setValue(attributeUseValue);
            attributeElement.setAttribute(attributeUseAttr);
            return attributeGroupElement;
        }
    }

}

From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java

License:Apache License

/**
 * Fills an already created 'attribute' element (a future element called 'attribute' on the schema document) in a situation 
 * such that it should have a name and a type, via 'type' attribute or a nested simpleType tag (depending on the configuration).
 * @param schemaAttribute the source SchemaAttribute
 * @param attributeElement the 'attribute' element
 * @param configuration the inference configuration
 * @param namespaceURIToPrefixMappings the resolved namespaceURIToPrefixMappings
 * @param targetNamespace the target namespace of the current schema
 * @param mainNamespace the default namespace of the inference
 * @param isGlobal whether the attribute is being declared at the top of the schema (global) or not (because it is local, it means, declared into its enclosing complex type).
 * @param xsdNamespace namespace URI for XML Schema Documents
 *///from  www .  ja v a2  s  . c o m
private void fillNormalAttributeElement(SchemaAttribute schemaAttribute, Element attributeElement,
        XSDInferenceConfiguration configuration, Map<String, String> namespaceURIToPrefixMappings,
        String targetNamespace, String mainNamespace, boolean isGlobal, Namespace xsdNamespace) {
    Attribute attributeNameAttr = new Attribute("name", "");
    attributeNameAttr.setValue(schemaAttribute.getName());
    attributeElement.setAttribute(attributeNameAttr);
    if (configuration.getSimpleTypesGlobal() || !schemaAttribute.getSimpleType().isEnum()) {
        Attribute attributeTypeAttr = new Attribute("type", "");
        String simpleTypeRepresentationName = schemaAttribute.getSimpleType()
                .getRepresentationName(configuration.getTypeNamesAncestorsSeparator());
        if (!simpleTypeRepresentationName.startsWith(XSD_NAMESPACE_PREFIX)
                && !namespaceURIToPrefixMappings.get(mainNamespace).equals("")) {
            simpleTypeRepresentationName = namespaceURIToPrefixMappings.get(mainNamespace) + ":"
                    + simpleTypeRepresentationName;
        }
        attributeTypeAttr.setValue(simpleTypeRepresentationName);
        if (!schemaAttribute.getSimpleType().isEmpty())
            attributeElement.setAttribute(attributeTypeAttr);
    }

    else {
        Element simpleType = generateSimpleType(schemaAttribute.getSimpleType(), true, configuration,
                xsdNamespace);
        attributeElement.addContent(simpleType);
    }
    if (!(isGlobal && !configuration.getStrictValidRootDefinitionWorkaround())) {
        Attribute attributeUseAttr = new Attribute("use", "");
        String attributeUseValue = schemaAttribute.isOptional() ? "optional" : "required";
        attributeUseAttr.setValue(attributeUseValue);
        attributeElement.setAttribute(attributeUseAttr);
    }
    //If the namespace of the attribute (which should be equals to the target namespace in this method)
    //is prefixed, this attribute should be marked as qualified.
    //Globally declared attributes (which may only happen if they belong to an auxiliary namespace and the workaround is disabled) 
    //are always qualified and it is prohibited to include the attribute 'form' (even with the value 'qualified'), so we omit it.
    if ((schemaAttribute.getNamespace() != null) && (!schemaAttribute.getNamespace().equals(""))
            && (!namespaceURIToPrefixMappings.get(schemaAttribute.getNamespace()).equals(""))
            && !(isGlobal && !configuration.getStrictValidRootDefinitionWorkaround())) {
        Attribute attribtueFormAttr = new Attribute("form", "qualified");
        attributeElement.setAttribute(attribtueFormAttr);

    }

}

From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java

License:Apache License

/**
 * Generates an element that describes a {@link SimpleType}, whenever it is necessary.
 * @param simpleType the simple type to describe
 * @param anonymous whether it must be anonymous (lack of a 'name' attribute) or not
 * @param configuration the inference configuration
 * @param xsdNamespace the XSD namespace
 * @return a JDOM2 {@link Element} that describes the {@link SimpleType}
 *///from   w w  w . jav a2s  .  c  om
private Element generateSimpleType(SimpleType simpleType, boolean anonymous,
        XSDInferenceConfiguration configuration, Namespace xsdNamespace) {
    checkArgument(simpleType.isEnum());
    checkArgument(!simpleType.isEmpty());
    Element simpleTypeElement = new Element("simpleType", xsdNamespace);
    if (!anonymous) {
        Attribute simpleTypeNameAttr = new Attribute("name", "");
        simpleTypeNameAttr
                .setValue(simpleType.getRepresentationName(configuration.getTypeNamesAncestorsSeparator()));
        simpleTypeElement.setAttribute(simpleTypeNameAttr);
        //System.err.println(simpleType.getRepresentationName("-"));
    }
    Element restrictionElement = new Element("restriction", xsdNamespace);
    Attribute restrictionBaseAttr = new Attribute("base", "");
    restrictionBaseAttr.setValue(simpleType.getBuiltinType());
    restrictionElement.setAttribute(restrictionBaseAttr);
    SortedSet<String> values = new TreeSet<>();
    for (String value : simpleType) {
        values.add(value);
    }
    for (String value : values) {
        Element enumerationElement = new Element("enumeration", xsdNamespace);
        Attribute enumerationValueAttr = new Attribute("value", "");
        enumerationValueAttr.setValue(value);
        enumerationElement.setAttribute(enumerationValueAttr);
        restrictionElement.addContent(enumerationElement);
    }
    simpleTypeElement.addContent(restrictionElement);
    return simpleTypeElement;

}