All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hazelcast.config.ConfigXmlGenerator Maven / Gradle / Ivy

There is a newer version: 5.0-BETA-1
Show newest version
/*
 * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hazelcast.config;

import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import static com.hazelcast.util.ValidationUtil.isNotNull;

/**
 * The ConfigXmlGenerator is responsible for transforming a {@link Config} to a Hazelcast XML string.
 */
public class ConfigXmlGenerator {

    private static final ILogger logger = Logger.getLogger(ConfigXmlGenerator.class);

    private final boolean formatted;

    /**
     * Creates a ConfigXmlGenerator that will format the code.
     */
    public ConfigXmlGenerator() {
        this(true);
    }

    /**
     * Creates a ConfigXmlGenerator.
     *
     * @param formatted true if the XML should be formatted, false otherwise.
     */
    public ConfigXmlGenerator(boolean formatted) {
        this.formatted = formatted;
    }

    /**
     * Generates the XML string based on some Config.
     *
     * @param config the configuration.
     * @return the XML string.
     */
    public String generate(Config config) {
        isNotNull(config,"Config");

        final StringBuilder xml = new StringBuilder();
        xml.append("");
        xml.append("");
        xml.append("").append(config.getGroupConfig().getName()).append("");
        xml.append("").append(config.getGroupConfig().getPassword()).append("");
        xml.append("");
        if (config.getLicenseKey() != null) {
            xml.append("").append(config.getLicenseKey()).append("");
        }
        if (config.getManagementCenterConfig() != null) {
            ManagementCenterConfig mcConfig = config.getManagementCenterConfig();
            xml.append("")
                    .append(mcConfig.getUrl()).append("");
        }
        appendProperties(xml, config.getProperties());
        final Collection wanRepConfigs = config.getWanReplicationConfigs().values();
        for (WanReplicationConfig wan : wanRepConfigs) {
            xml.append("");
            final List targets = wan.getTargetClusterConfigs();
            for (WanTargetClusterConfig t : targets) {
                xml.append("");
                xml.append("").append(t.getReplicationImpl()).append("");
                xml.append("");
                final List eps = t.getEndpoints();
                for (String ep : eps) {
                    xml.append("
").append(ep).append("
"); } xml.append("
").append("
"); } xml.append("
"); } final NetworkConfig netCfg = config.getNetworkConfig(); xml.append(""); if (netCfg.getPublicAddress() != null) { xml.append("").append(netCfg.getPublicAddress()).append(""); } xml.append("") .append(netCfg.getPort()).append(""); final JoinConfig join = netCfg.getJoin(); xml.append(""); final MulticastConfig mcast = join.getMulticastConfig(); xml.append(""); xml.append("").append(mcast.getMulticastGroup()).append(""); xml.append("").append(mcast.getMulticastPort()).append(""); xml.append("").append(mcast.getMulticastTimeoutSeconds()).append(""); xml.append("").append(mcast.getMulticastTimeToLive()).append(""); if (!mcast.getTrustedInterfaces().isEmpty()) { xml.append(""); for (String trustedInterface : mcast.getTrustedInterfaces()) { xml.append("").append(trustedInterface).append(""); } xml.append(""); } xml.append(""); final TcpIpConfig tcpCfg = join.getTcpIpConfig(); xml.append(""); final List members = tcpCfg.getMembers(); for (String m : members) { xml.append("").append(m).append(""); } if (tcpCfg.getRequiredMember() != null) { xml.append("").append(tcpCfg.getRequiredMember()).append(""); } xml.append(""); final AwsConfig awsConfig = join.getAwsConfig(); xml.append(""); xml.append("").append(awsConfig.getAccessKey()).append(""); xml.append("").append(awsConfig.getSecretKey()).append(""); xml.append("").append(awsConfig.getRegion()).append(""); xml.append("").append(awsConfig.getSecurityGroupName()).append(""); xml.append("").append(awsConfig.getTagKey()).append(""); xml.append("").append(awsConfig.getTagValue()).append(""); xml.append(""); xml.append(""); final InterfacesConfig interfaces = netCfg.getInterfaces(); xml.append(""); final Collection interfaceList = interfaces.getInterfaces(); for (String i : interfaceList) { xml.append("").append(i).append(""); } xml.append(""); final SSLConfig ssl = netCfg.getSSLConfig(); xml.append(""); if (ssl != null) { String className = ssl.getFactoryImplementation() != null ? ssl.getFactoryImplementation().getClass().getName() : ssl.getFactoryClassName(); xml.append("").append(className).append(""); appendProperties(xml, ssl.getProperties()); } xml.append(""); final SocketInterceptorConfig socket = netCfg.getSocketInterceptorConfig(); xml.append(""); if (socket != null) { String className = socket.getImplementation() != null ? socket.getImplementation().getClass().getName() : socket.getClassName(); xml.append("").append(className).append(""); appendProperties(xml, socket.getProperties()); } xml.append(""); final SymmetricEncryptionConfig sec = netCfg.getSymmetricEncryptionConfig(); xml.append(""); if (sec != null) { xml.append("").append(sec.getAlgorithm()).append(""); xml.append("").append(sec.getSalt()).append(""); xml.append("").append(sec.getPassword()).append(""); xml.append("").append(sec.getIterationCount()).append(""); } xml.append(""); xml.append(""); final PartitionGroupConfig pg = config.getPartitionGroupConfig(); if (pg != null) { xml.append(""); } final Collection exCfgs = config.getExecutorConfigs().values(); for (ExecutorConfig ex : exCfgs) { xml.append(""); xml.append("").append(ex.getPoolSize()).append(""); xml.append("").append(ex.getQueueCapacity()).append(""); xml.append(""); } final Collection qCfgs = config.getQueueConfigs().values(); for (QueueConfig q : qCfgs) { xml.append(""); xml.append("").append(q.getMaxSize()).append(""); xml.append("").append(q.getBackupCount()).append(""); xml.append("").append(q.getAsyncBackupCount()).append(""); if (!q.getItemListenerConfigs().isEmpty()) { xml.append(""); for (ItemListenerConfig lc : q.getItemListenerConfigs()) { xml.append(""); xml.append(lc.getClassName()); xml.append(""); } xml.append(""); } xml.append(""); } final Collection mCfgs = config.getMapConfigs().values(); for (MapConfig m : mCfgs) { xml.append(""); xml.append("").append(m.getInMemoryFormat()).append(""); xml.append("").append(m.getBackupCount()).append(""); xml.append("").append(m.getAsyncBackupCount()).append(""); xml.append("").append(m.getTimeToLiveSeconds()).append(""); xml.append("").append(m.getMaxIdleSeconds()).append(""); xml.append("").append(m.getEvictionPolicy()).append(""); xml.append("").append(m.getMaxSizeConfig().getSize()).append(""); xml.append("").append(m.getEvictionPercentage()).append(""); xml.append("").append(m.getMergePolicy()).append(""); xml.append("").append(m.isReadBackupData()).append(""); xml.append("").append(m.isStatisticsEnabled()).append(""); if (m.getMapStoreConfig() != null) { final MapStoreConfig s = m.getMapStoreConfig(); xml.append(""); final String clazz = s.getImplementation() != null ? s.getImplementation().getClass().getName() : s.getClassName(); xml.append("").append(clazz).append(""); final String factoryClass = s.getFactoryImplementation() != null ? s.getFactoryImplementation().getClass().getName() : s.getFactoryClassName(); if (factoryClass != null) { xml.append("").append(factoryClass).append(""); } xml.append("").append(s.getWriteDelaySeconds()).append(""); appendProperties(xml, s.getProperties()); xml.append(""); } if (m.getNearCacheConfig() != null) { final NearCacheConfig n = m.getNearCacheConfig(); xml.append(""); xml.append("").append(n.getMaxSize()).append(""); xml.append("").append(n.getTimeToLiveSeconds()).append(""); xml.append("").append(n.getMaxIdleSeconds()).append(""); xml.append("").append(n.getEvictionPolicy()).append(""); xml.append("").append(n.isInvalidateOnChange()).append(""); xml.append("").append(n.getInMemoryFormat()).append(""); xml.append(""); } if (m.getWanReplicationRef() != null) { final WanReplicationRef wan = m.getWanReplicationRef(); xml.append(""); xml.append("").append(wan.getMergePolicy()).append(""); xml.append(""); } if (!m.getMapIndexConfigs().isEmpty()) { xml.append(""); for (MapIndexConfig indexCfg : m.getMapIndexConfigs()) { xml.append(""); xml.append(indexCfg.getAttribute()); xml.append(""); } xml.append(""); } if (!m.getEntryListenerConfigs().isEmpty()) { xml.append(""); for (EntryListenerConfig lc : m.getEntryListenerConfigs()) { xml.append(""); final String clazz = lc.getImplementation() != null ? lc.getImplementation().getClass().getName() : lc.getClassName(); xml.append(clazz); xml.append(""); } xml.append(""); } if (m.getPartitioningStrategyConfig() != null) { xml.append(""); PartitioningStrategyConfig psc = m.getPartitioningStrategyConfig(); if (psc.getPartitioningStrategy() != null) { xml.append(psc.getPartitioningStrategy().getClass().getName()); } else { xml.append(psc.getPartitioningStrategyClass()); } xml.append(""); } xml.append(""); } final Collection mmCfgs = config.getMultiMapConfigs().values(); for (MultiMapConfig mm : mmCfgs) { xml.append(""); xml.append("").append(mm.getValueCollectionType()).append(""); if (!mm.getEntryListenerConfigs().isEmpty()) { xml.append(""); for (EntryListenerConfig lc : mm.getEntryListenerConfigs()) { xml.append(""); final String clazz = lc.getImplementation() != null ? lc.getImplementation().getClass().getName() : lc.getClassName(); xml.append(clazz); xml.append(""); } xml.append(""); } // if (mm.getPartitioningStrategyConfig() != null) { // xml.append(""); // PartitioningStrategyConfig psc = mm.getPartitioningStrategyConfig(); // if (psc.getPartitioningStrategy() != null) { // xml.append(psc.getPartitioningStrategy().getClass().getName()); // } else { // xml.append(psc.getPartitioningStrategyClass()); // } // xml.append(""); // } xml.append(""); } final Collection tCfgs = config.getTopicConfigs().values(); for (TopicConfig t : tCfgs) { xml.append(""); xml.append("").append(t.isGlobalOrderingEnabled()).append(""); if (!t.getMessageListenerConfigs().isEmpty()) { xml.append(""); for (ListenerConfig lc : t.getMessageListenerConfigs()) { xml.append(""); final String clazz = lc.getImplementation() != null ? lc.getImplementation().getClass().getName() : lc.getClassName(); xml.append(clazz); xml.append(""); } xml.append(""); } xml.append(""); } final Collection semaphoreCfgs = config.getSemaphoreConfigs(); for (SemaphoreConfig sc : semaphoreCfgs) { xml.append(""); xml.append("").append(sc.getInitialPermits()).append(""); xml.append("").append(sc.getBackupCount()).append(""); xml.append("").append(sc.getAsyncBackupCount()).append(""); xml.append(""); } if (!config.getListenerConfigs().isEmpty()) { xml.append(""); for (ListenerConfig lc : config.getListenerConfigs()) { xml.append(""); final String clazz = lc.getImplementation() != null ? lc.getImplementation().getClass().getName() : lc.getClassName(); xml.append(clazz); xml.append(""); } xml.append(""); } xml.append("
"); return format(xml.toString(), 5); } private String format(final String input, int indent) { if (!formatted) { return input; } try { final Source xmlInput = new StreamSource(new StringReader(input)); final StreamResult xmlOutput = new StreamResult(new StringWriter()); TransformerFactory transformerFactory = TransformerFactory.newInstance(); /* Older versions of Xalan still use this method of setting indent values. * Attempt to make this work but don't completely fail if it's a problem. */ try { transformerFactory.setAttribute("indent-number", indent); } catch (IllegalArgumentException e) { if(logger.isFinestEnabled()){ logger.finest( "Failed to set indent-number attribute; cause: " + e.getMessage()); } } Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); /* Newer versions of Xalan will look for a fully-qualified output property in order to specify amount of * indentation to use. Attempt to make this work as well but again don't completely fail if it's a problem. */ try { transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent)); } catch (IllegalArgumentException e) { if(logger.isFinestEnabled()){ logger.finest( "Failed to set indent-amount property; cause: " + e.getMessage()); } } transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (Exception e) { logger.warning(e); return input; } } private void appendProperties(StringBuilder xml, Properties props) { if (!props.isEmpty()) { xml.append(""); Set keys = props.keySet(); for (Object key : keys) { xml.append("") .append(props.getProperty(key.toString())) .append(""); } xml.append(""); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy