Example usage for org.apache.commons.configuration XMLConfiguration save

List of usage examples for org.apache.commons.configuration XMLConfiguration save

Introduction

In this page you can find the example usage for org.apache.commons.configuration XMLConfiguration save.

Prototype

public void save(Writer writer) throws ConfigurationException 

Source Link

Document

Saves the configuration to the specified writer.

Usage

From source file:org.onosproject.drivers.fujitsu.FujitsuVoltControllerConfig.java

/**
 * Forms XML string to change controller information.
 *
 * @param cfg a hierarchical configuration
 * @param target the type of configuration
 * @param netconfOperation operation type
 * @param controllers list of controllers
 * @return XML string/*  w w  w. jav  a 2s  .  com*/
 */
private String createVoltControllersConfig(HierarchicalConfiguration cfg, String target,
        String netconfOperation, List<ControllerInfo> controllers) {
    XMLConfiguration editcfg = null;

    cfg.setProperty(EDIT_CONFIG_TG, target);
    cfg.setProperty(EDIT_CONFIG_DO, netconfOperation);

    List<ConfigurationNode> newControllers = new ArrayList<>();
    for (ControllerInfo ci : controllers) {
        XMLConfiguration controller = new XMLConfiguration();
        controller.setRoot(new HierarchicalConfiguration.Node(OF_CONTROLLER));
        controller.setProperty(OFCONFIG_ID, ci.annotations().value(OFCONFIG_ID));
        controller.setProperty(CONTROLLER_INFO_ID, ci.annotations().value(OFCONFIG_ID));
        controller.setProperty(CONTROLLER_INFO_IP, ci.ip());
        controller.setProperty(CONTROLLER_INFO_PORT, ci.port());
        controller.setProperty(CONTROLLER_INFO_PROTOCOL, ci.type());
        newControllers.add(controller.getRootNode());
    }
    cfg.addNodes(VOLT_EDITCONFIG, newControllers);

    try {
        editcfg = (XMLConfiguration) cfg;
    } catch (ClassCastException e) {
        e.printStackTrace();
    }
    StringWriter stringWriter = new StringWriter();
    try {
        editcfg.save(stringWriter);
    } catch (ConfigurationException e) {
        e.printStackTrace();
    }
    String s = stringWriter.toString();
    String fromStr = buildStartTag(TARGET, false) + target + buildEndTag(TARGET, false);
    String toStr = buildStartTag(TARGET, false) + buildEmptyTag(target, false) + buildEndTag(TARGET, false);
    s = s.replace(fromStr, toStr);
    return s;
}

From source file:org.onosproject.drivers.juniper.tools.XmlParserJuniper.java

public static String getReplyXml(HierarchicalConfiguration cfg) {
    StringWriter stringWriter = new StringWriter();
    try {//from  w w  w  .  j a va  2  s  .c  o m
        XMLConfiguration xcfg = (XMLConfiguration) cfg;
        xcfg.save(stringWriter);
    } catch (ConfigurationException e) {
        System.out.println(e.getMessage());
    }
    String s = stringWriter.toString();
    return s;
}

From source file:org.onosproject.drivers.utilities.YangXmlUtils.java

/**
 * Return the string representation of the XMLConfig without header
 * and configuration element.//from w  ww.  ja va2  s .  co m
 *
 * @param cfg the XML to convert
 * @return the cfg string.
 */
public String getString(XMLConfiguration cfg) {
    StringWriter stringWriter = new StringWriter();
    try {
        cfg.save(stringWriter);
    } catch (ConfigurationException e) {
        log.error("Cannot convert configuration", e.getMessage());
    }
    String xml = stringWriter.toString();
    xml = xml.substring(xml.indexOf("\n"));
    xml = xml.substring(xml.indexOf(">") + 1);
    return xml;
}

From source file:org.pivot4j.state.StateSavingIT.java

@Test
public void testSaveModelSettings() throws ConfigurationException, IOException {
    PivotModel model = getPivotModel();/*from  w  w  w  .ja v  a 2s.  c o  m*/
    model.setMdx(getTestQuery());
    model.initialize();

    model.setSorting(true);
    model.setTopBottomCount(3);
    model.setSortCriteria(SortCriteria.BOTTOMCOUNT);

    CellSet cellSet = model.getCellSet();
    CellSetAxis axis = cellSet.getAxes().get(Axis.COLUMNS.axisOrdinal());

    model.sort(axis, axis.getPositions().get(0));

    String mdx = model.getCurrentMdx();

    XMLConfiguration configuration = new XMLConfiguration();
    configuration.setDelimiterParsingDisabled(true);

    model.saveSettings(configuration);

    Logger logger = LoggerFactory.getLogger(getClass());
    if (logger.isDebugEnabled()) {
        StringWriter writer = new StringWriter();
        configuration.save(writer);
        writer.flush();
        writer.close();

        logger.debug("Loading report content :" + System.getProperty("line.separator"));
        logger.debug(writer.getBuffer().toString());
    }

    PivotModel newModel = new PivotModelImpl(getDataSource());
    newModel.restoreSettings(configuration);

    newModel.getCellSet();

    String newMdx = newModel.getCurrentMdx();
    if (newMdx != null) {
        // Currently the parser treats every number as double value.
        // It's inevitable now and does not impact the result.
        newMdx = newMdx.replaceAll("3\\.0", "3");
    }

    assertThat("MDX has been changed after the state restoration", newMdx, is(equalTo(mdx)));
    assertThat("RenderProperty 'sorting' has been changed after the state restoration", newModel.isSorting(),
            is(true));
    assertThat("RenderProperty 'topBottomCount' has been changed after the state restoration",
            newModel.getTopBottomCount(), is(equalTo(3)));
    assertThat("RenderProperty 'sortMode' has been changed after the state restoration",
            newModel.getSortCriteria(), is(equalTo(SortCriteria.BOTTOMCOUNT)));
}

From source file:org.pivot4j.ui.condition.ExpressionConditionTest.java

@Test
public void testSettingsManagement() throws ConfigurationException {
    TableRenderContext context = createDummyRenderContext();
    context.setColIndex(2);/*w  w  w . j ava2 s . c o  m*/
    context.setRowIndex(1);
    context.setAxis(Axis.ROWS);

    String expression = "<#if columnIndex = 2 && rowIndex = 1>true</#if>";

    ExpressionCondition condition = new ExpressionCondition(conditionFactory);
    condition.setExpression(expression);

    XMLConfiguration configuration = new XMLConfiguration();
    configuration.setRootElementName("condition");

    condition.saveSettings(configuration);

    condition = new ExpressionCondition(conditionFactory);
    condition.restoreSettings(configuration);

    assertThat("Expression has been changed.", condition.getExpression(), is(equalTo(expression)));
    assertThat("Expression '" + expression + "' should be true.", condition.matches(context), is(true));

    System.out.println("Saved configuration : ");

    configuration.save(System.out);
}

From source file:org.pivot4j.ui.property.ConditionalPropertyTest.java

@Test
public void testSettingsManagement() throws ConfigurationException {
    XMLConfiguration configuration = new XMLConfiguration();
    configuration.setRootElementName("property");

    property.saveSettings(configuration);
    System.out.println("Saved configuration : ");
    configuration.save(System.out);
    ConditionalRenderProperty property2 = new ConditionalRenderProperty(new DefaultConditionFactory());
    property2.restoreSettings(configuration);

    assertThat("RenderProperty name has been changed.", property2.getName(), is(equalTo(property.getName())));
    assertThat("Default value has been changed.", property2.getDefaultValue(),
            is(equalTo(property.getDefaultValue())));

    TableRenderContext context = createDummyRenderContext();
    context.setColIndex(2);//from  ww w.j  a  va2  s . c  om
    context.setRowIndex(4);

    String result = property2.getValue(context);

    assertThat("Wrong property value.", result, is(equalTo("blue")));

    System.out.println("Saved configuration : ");
    configuration.save(System.out);
}

From source file:org.pivot4j.ui.property.SimplePropertyTest.java

@Test
public void testSettingsManagement() throws ConfigurationException {
    SimpleRenderProperty property = new SimpleRenderProperty("bgColor", "red");

    XMLConfiguration configuration = new XMLConfiguration();
    configuration.setRootElementName("property");

    property.saveSettings(configuration);

    SimpleRenderProperty property2 = new SimpleRenderProperty();
    property2.restoreSettings(configuration);

    assertThat("RenderProperty name has been changed.", property2.getName(), is(equalTo(property.getName())));
    assertThat("RenderProperty value has been changed.", property2.getValue(),
            is(equalTo(property.getValue())));

    System.out.println("Saved configuration : ");

    configuration.save(System.out);
}

From source file:org.sindice.analytics.servlet.ServletConfigurationContextListener.java

private void loadDefaultConfiguration(final XMLConfiguration config, File saveAs) {
    logger.info("loading default configuration");
    InputStream in = ServletConfigurationContextListener.class.getClassLoader()
            .getResourceAsStream("default-config.xml");
    if (in == null) {
        logger.error("application is missing default-config.xml from classpath");
    } else {//  www.  j a  va  2  s . c om
        try {
            config.load(in);
            if (saveAs != null) {
                try {
                    saveAs.getParentFile().mkdirs();
                    config.save(saveAs);
                    logger.info("wrote default configuration to {}", saveAs);
                } catch (ConfigurationException e) {
                    logger.warn("Could not write configuration to {}", saveAs, e);
                }
            }
        } catch (ConfigurationException e) {
            logger.error("could not load default-config.xml", e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                logger.warn("problem closing stream", e);
            }
        }
    }
}

From source file:org.talend.mdm.commmon.util.core.EncryptUtil.java

public static void encyptXML(String location) {
    try {/*from   w w  w  . j  ava 2s . c om*/
        File file = new File(location);
        if (file.exists()) {
            XMLConfiguration config = new XMLConfiguration();
            config.setDelimiterParsingDisabled(true);
            config.load(file);
            List<Object> dataSources = config.getList("datasource.[@name]"); //$NON-NLS-1$
            int index = -1;
            for (int i = 0; i < dataSources.size(); i++) {
                if (dataSources.get(i).equals(dataSourceName)) {
                    index = i;
                    break;
                }
            }
            updated = false;
            if (index >= 0) {
                HierarchicalConfiguration sub = config.configurationAt("datasource(" + index + ")"); //$NON-NLS-1$//$NON-NLS-2$
                encryptByXpath(sub, "master.rdbms-configuration.connection-password"); //$NON-NLS-1$
                encryptByXpath(sub, "master.rdbms-configuration.init.connection-password"); //$NON-NLS-1$
                encryptByXpath(sub, "staging.rdbms-configuration.connection-password"); //$NON-NLS-1$
                encryptByXpath(sub, "staging.rdbms-configuration.init.connection-password"); //$NON-NLS-1$
                encryptByXpath(sub, "system.rdbms-configuration.connection-password"); //$NON-NLS-1$
                encryptByXpath(sub, "system.rdbms-configuration.init.connection-password"); //$NON-NLS-1$
            }
            if (updated) {
                config.save(file);
            }
        }
    } catch (Exception e) {
        LOGGER.error("Encrypt password in '" + location + "' error."); //$NON-NLS-1$ //$NON-NLS-2$
    }
}

From source file:org.zaproxy.gradle.UpdateAddOnZapVersionsEntries.java

@TaskAction
public void update() throws Exception {
    if (checksumAlgorithm.get().isEmpty()) {
        throw new IllegalArgumentException("The checksum algorithm must not be empty.");
    }/*www. j a  v a2 s .  c  o m*/

    if (fromFile.isPresent()) {
        if (fromUrl.isPresent()) {
            throw new IllegalArgumentException(
                    "Only one of the properties, URL or file, can be set at the same time.");
        }

        if (!downloadUrl.isPresent()) {
            throw new IllegalArgumentException("The download URL must be provided when specifying the file.");
        }
    } else if (!fromUrl.isPresent()) {
        throw new IllegalArgumentException("Either one of the properties, URL or file, must be set.");
    }

    if (downloadUrl.get().isEmpty()) {
        throw new IllegalArgumentException("The download URL must not be empty.");
    }

    try {
        URL url = new URL(downloadUrl.get());
        if (!HTTPS_SCHEME.equalsIgnoreCase(url.getProtocol())) {
            throw new IllegalArgumentException(
                    "The provided download URL does not use HTTPS scheme: " + url.getProtocol());
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("Failed to parse the download URL: " + e.getMessage(), e);
    }

    Path addOn = getAddOn();
    String addOnId = extractAddOnId(addOn.getFileName().toString());
    AddOnEntry addOnEntry = new AddOnEntry(addOnId,
            new AddOnConfBuilder(addOn, downloadUrl.get(), checksumAlgorithm.get(), releaseDate.get()).build());

    for (File zapVersionsFile : into.getFiles()) {
        if (!Files.isRegularFile(zapVersionsFile.toPath())) {
            throw new IllegalArgumentException("The provided path is not a file: " + zapVersionsFile);
        }

        SortedSet<AddOnEntry> addOns = new TreeSet<>();
        XMLConfiguration zapVersionsXml = new CustomXmlConfiguration();
        zapVersionsXml.load(zapVersionsFile);
        Arrays.stream(zapVersionsXml.getStringArray(ADD_ON_ELEMENT)).filter(id -> !addOnId.equals(id))
                .forEach(id -> {
                    String key = ADD_ON_NODE_PREFIX + id;
                    addOns.add(new AddOnEntry(id, zapVersionsXml.configurationAt(key)));
                    zapVersionsXml.clearTree(key);
                });

        zapVersionsXml.clearTree(ADD_ON_ELEMENT);
        zapVersionsXml.clearTree(ADD_ON_NODE_PREFIX + addOnId);

        addOns.add(addOnEntry);

        addOns.forEach(e -> {
            zapVersionsXml.addProperty(ADD_ON_ELEMENT, e.getAddOnId());
            zapVersionsXml.addNodes(ADD_ON_NODE_PREFIX + e.getAddOnId(),
                    e.getData().getRootNode().getChildren());
        });
        zapVersionsXml.save(zapVersionsFile);
    }
}