PluginConfigUtil.java

/*
 * #%L
 * wcm.io
 * %%
 * Copyright (C) 2018 wcm.io
 * %%
 * 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.
 * #L%
 */
package io.wcm.devops.conga.tooling.maven.plugin.util;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.sling.commons.osgi.ManifestHeader;
import org.apache.sling.commons.osgi.ManifestHeader.NameValuePair;

import io.wcm.devops.conga.generator.util.ValueUtil;

/**
 * Helper methos for managing plugin configuration.
 */
public final class PluginConfigUtil {

  private PluginConfigUtil() {
    // static methods only
  }

  /**
   * Convert configuration string in OSGI manifest header style to nested configuration map.
   * @param pluginConfig OSGi manifest header-style config
   * @return Nested configuration map
   */
  public static Map<String, Map<String, Object>> getConfigMap(String pluginConfig) {
    if (StringUtils.isEmpty(pluginConfig)) {
      return Collections.emptyMap();
    }
    Map<String, Map<String, Object>> valueProviderConfig = new HashMap<>();
    ManifestHeader header = ManifestHeader.parse(pluginConfig);
    for (ManifestHeader.Entry entry : header.getEntries()) {
      Map<String, Object> config = new HashMap<>();
      for (NameValuePair nameValue : entry.getAttributes()) {
        config.put(nameValue.getName(), ValueUtil.stringToValue(nameValue.getValue()));
      }
      valueProviderConfig.put(entry.getValue(), Collections.unmodifiableMap(config));
    }
    return Collections.unmodifiableMap(valueProviderConfig);
  }

}