Search in sources :

Example 21 with XPathExpression

use of org.jdom2.xpath.XPathExpression in project mycore by MyCoRe-Org.

the class MCRBinding method bind.

private void bind(String xPath, boolean buildIfNotExists, String initialValue) throws JaxenException {
    this.xPath = xPath;
    Map<String, Object> variables = buildXPathVariables();
    XPathExpression<Object> xPathExpr = XPathFactory.instance().compile(xPath, Filters.fpassthrough(), variables, MCRConstants.getStandardNamespaces());
    boundNodes.addAll(xPathExpr.evaluate(parent.getBoundNodes()));
    for (Object boundNode : boundNodes) if (!(boundNode instanceof Element || boundNode instanceof Attribute || boundNode instanceof Document))
        throw new RuntimeException("XPath MUST only bind either element, attribute or document nodes: " + xPath);
    LOGGER.debug("Bind to {} selected {} node(s)", xPath, boundNodes.size());
    if (boundNodes.isEmpty() && buildIfNotExists) {
        MCRNodeBuilder builder = new MCRNodeBuilder(variables);
        Object built = builder.buildNode(xPath, initialValue, (Parent) (parent.getBoundNode()));
        LOGGER.debug("Bind to {} generated node {}", xPath, MCRXPathBuilder.buildXPath(built));
        boundNodes.add(built);
        trackNodeCreated(builder.getFirstNodeBuilt());
    }
}
Also used : MCRNodeBuilder(org.mycore.common.xml.MCRNodeBuilder) MCRRemoveAttribute(org.mycore.frontend.xeditor.tracker.MCRRemoveAttribute) MCRAddedAttribute(org.mycore.frontend.xeditor.tracker.MCRAddedAttribute) Attribute(org.jdom2.Attribute) MCRAddedElement(org.mycore.frontend.xeditor.tracker.MCRAddedElement) MCRRemoveElement(org.mycore.frontend.xeditor.tracker.MCRRemoveElement) Element(org.jdom2.Element) Document(org.jdom2.Document)

Example 22 with XPathExpression

use of org.jdom2.xpath.XPathExpression in project gocd by gocd.

the class ConfigCipherUpdater method migrate.

public void migrate() {
    File cipherFile = systemEnvironment.getCipherFile();
    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 {
        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());
        byte[] oldCipher = FileUtils.readFileToByteArray(backupCipherFile);
        new CipherProvider(systemEnvironment).resetCipher();
        byte[] newCipher = FileUtils.readFileToByteArray(cipherFile);
        if (new String(newCipher).equals(new String(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(oldCipher, 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(oldCipher, 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);
            }
        }
    }
}
Also used : SAXBuilder(org.jdom2.input.SAXBuilder) Attribute(org.jdom2.Attribute) CipherProvider(com.thoughtworks.go.security.CipherProvider) Element(org.jdom2.Element) IOException(java.io.IOException) Document(org.jdom2.Document) InvalidCipherTextException(org.bouncycastle.crypto.InvalidCipherTextException) IOException(java.io.IOException) XPathFactory(org.jdom2.xpath.XPathFactory) FileOutputStream(java.io.FileOutputStream) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 23 with XPathExpression

use of org.jdom2.xpath.XPathExpression in project jspwiki by apache.

the class XmlUtil method parse.

/**
 * Parses the given XML file and returns the requested nodes. If there's an error accessing or parsing the file, an
 * empty list is returned.
 *
 * @param xml file to parse; matches all resources from classpath, filters repeated items.
 * @param requestedNodes requestd nodes on the xml file
 * @return the requested nodes of the XML file.
 */
public static List<Element> parse(String xml, String requestedNodes) {
    if (StringUtils.isNotEmpty(xml) && StringUtils.isNotEmpty(requestedNodes)) {
        Set<Element> readed = new HashSet<Element>();
        SAXBuilder builder = new SAXBuilder();
        try {
            Enumeration<URL> resources = XmlUtil.class.getClassLoader().getResources(xml);
            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();
                log.debug("reading " + resource.toString());
                Document doc = builder.build(resource);
                XPathFactory xpfac = XPathFactory.instance();
                XPathExpression<Element> xp = xpfac.compile(requestedNodes, Filters.element());
                // filter out repeated items
                readed.addAll(xp.evaluate(doc));
            }
            return new ArrayList<Element>(readed);
        } catch (IOException ioe) {
            log.error("Couldn't load all " + xml + " resources", ioe);
        } catch (JDOMException jdome) {
            log.error("error parsing " + xml + " resources", jdome);
        }
    }
    return Collections.<Element>emptyList();
}
Also used : SAXBuilder(org.jdom2.input.SAXBuilder) Element(org.jdom2.Element) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.jdom2.Document) JDOMException(org.jdom2.JDOMException) URL(java.net.URL) XPathFactory(org.jdom2.xpath.XPathFactory) HashSet(java.util.HashSet)

Example 24 with XPathExpression

use of org.jdom2.xpath.XPathExpression in project pwm by pwm-project.

the class StoredConfigurationImpl method readSettingMetadata.

public ValueMetaData readSettingMetadata(final PwmSetting setting, final String profileID) {
    final XPathExpression xp = XPathBuilder.xpathForSetting(setting, profileID);
    final Element settingElement = (Element) xp.evaluateFirst(document);
    if (settingElement == null) {
        return null;
    }
    Instant modifyDate = null;
    try {
        if (settingElement.getAttributeValue(XML_ATTRIBUTE_MODIFY_TIME) != null) {
            modifyDate = JavaHelper.parseIsoToInstant(settingElement.getAttributeValue(XML_ATTRIBUTE_MODIFY_TIME));
        }
    } catch (Exception e) {
        LOGGER.error("can't read modifyDate for setting " + setting.getKey() + ", profile " + profileID + ", error: " + e.getMessage());
    }
    UserIdentity userIdentity = null;
    try {
        if (settingElement.getAttributeValue(XML_ATTRIBUTE_MODIFY_USER) != null) {
            userIdentity = UserIdentity.fromDelimitedKey(settingElement.getAttributeValue(XML_ATTRIBUTE_MODIFY_USER));
        }
    } catch (Exception e) {
        LOGGER.error("can't read userIdentity for setting " + setting.getKey() + ", profile " + profileID + ", error: " + e.getMessage());
    }
    return new ValueMetaData(modifyDate, userIdentity);
}
Also used : XPathExpression(org.jdom2.xpath.XPathExpression) Element(org.jdom2.Element) Instant(java.time.Instant) UserIdentity(password.pwm.bean.UserIdentity) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmOperationalException(password.pwm.error.PwmOperationalException) PwmException(password.pwm.error.PwmException) IOException(java.io.IOException)

Example 25 with XPathExpression

use of org.jdom2.xpath.XPathExpression in project pwm by pwm-project.

the class StoredConfigurationImpl method resetAllPasswordValues.

public void resetAllPasswordValues(final String comment) {
    for (final Iterator<SettingValueRecord> settingValueRecordIterator = new StoredValueIterator(false); settingValueRecordIterator.hasNext(); ) {
        final SettingValueRecord settingValueRecord = settingValueRecordIterator.next();
        if (settingValueRecord.getSetting().getSyntax() == PwmSettingSyntax.PASSWORD) {
            this.resetSetting(settingValueRecord.getSetting(), settingValueRecord.getProfile(), null);
            if (comment != null && !comment.isEmpty()) {
                final XPathExpression xp = XPathBuilder.xpathForSetting(settingValueRecord.getSetting(), settingValueRecord.getProfile());
                final Element settingElement = (Element) xp.evaluateFirst(document);
                if (settingElement != null) {
                    settingElement.addContent(new Comment(comment));
                }
            }
        }
    }
    final String pwdHash = this.readConfigProperty(ConfigurationProperty.PASSWORD_HASH);
    if (pwdHash != null && !pwdHash.isEmpty()) {
        this.writeConfigProperty(ConfigurationProperty.PASSWORD_HASH, comment);
    }
}
Also used : XPathExpression(org.jdom2.xpath.XPathExpression) Comment(org.jdom2.Comment) Element(org.jdom2.Element)

Aggregations

Element (org.jdom2.Element)43 Document (org.jdom2.Document)23 XPathExpression (org.jdom2.xpath.XPathExpression)13 IOException (java.io.IOException)9 XPathFactory (org.jdom2.xpath.XPathFactory)9 SAXBuilder (org.jdom2.input.SAXBuilder)7 Attribute (org.jdom2.Attribute)6 JDOMException (org.jdom2.JDOMException)5 Test (org.junit.Test)5 Text (org.jdom2.Text)4 XMLOutputter (org.jdom2.output.XMLOutputter)4 MCRObject (org.mycore.datamodel.metadata.MCRObject)4 MCRPath (org.mycore.datamodel.niofs.MCRPath)4 URISyntaxException (java.net.URISyntaxException)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 SimpleDateFormat (java.text.SimpleDateFormat)2 HashMap (java.util.HashMap)2 MCRPersistenceException (org.mycore.common.MCRPersistenceException)2 MCRNodeBuilder (org.mycore.common.xml.MCRNodeBuilder)2 MCRCategory (org.mycore.datamodel.classifications2.MCRCategory)2