/**
   * This is to workaround the issue that {@link AbstractConfiguration} by default automatically
   * convert comma delimited string to array
   */
  protected static String getStringValue(Configuration config, String key) {
    try {
      String values[] = config.getStringArray(key);
      if (values == null) {
        return null;
      }
      if (values.length == 0) {
        return config.getString(key);
      } else if (values.length == 1) {
        return values[0];
      }

      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < values.length; i++) {
        sb.append(values[i]);
        if (i != values.length - 1) {
          sb.append(",");
        }
      }
      return sb.toString();
    } catch (Exception e) {
      Object v = config.getProperty(key);
      if (v != null) {
        return String.valueOf(v);
      } else {
        return null;
      }
    }
  }
  private static List<String> asYamlLines(Configuration config, int depth) {
    List<String> lines = Lists.newArrayList();
    Set<String> prefixes = Sets.newHashSet();

    Iterator<String> keys = config.getKeys();
    while (keys.hasNext()) {
      String key = keys.next();

      String[] parts = key.split("\\.");
      String prefix = parts[0];

      if (prefixes.contains(prefix)) {
        continue; // skip parsed set of keys
      }

      if (parts.length == 1) {
        lines.add(spaces(depth * 2) + key + ": " + config.getProperty(key));

      } else if (parts.length > 1) {
        lines.add(spaces(depth * 2) + prefix + ":");
        lines.addAll(asYamlLines(config.subset(prefix), depth + 1));
      }

      prefixes.add(prefix);
    }

    return lines;
  }
 public static void create(final Configuration configuration) {
   final SparkConf sparkConf = new SparkConf();
   configuration
       .getKeys()
       .forEachRemaining(key -> sparkConf.set(key, configuration.getProperty(key).toString()));
   sparkConf.setAppName("Apache TinkerPop's Spark-Gremlin");
   CONTEXT = SparkContext.getOrCreate(sparkConf);
 }
  @Required
  public void setConfiguration(Configuration configuration) {
    this.configuration = configuration;

    Object val = configuration.getProperty(ConfigurationStore.ADVANCED_USAGE_LOGGING);
    if (val != null && val.equals("true")) {
      advancedLogging = true;
    }
  }
  public static synchronized SenseiPluginRegistry build(Configuration conf) {
    if (cachedRegistries.containsKey(conf)) {
      return cachedRegistries.get(conf);
    }

    SenseiPluginRegistry ret = new SenseiPluginRegistry();
    ret.configuration = conf;
    Iterator<?> keysIterator = conf.getKeys();
    while (keysIterator.hasNext()) {
      String key = (String) keysIterator.next();
      if (key.endsWith(".class")) {
        String prefix = key.substring(0, key.indexOf(".class"));
        String pluginName = getNameByPrefix(prefix);
        String pluginClass = conf.getString(key);
        ret.plugins.add(new PluginHolder(ret, pluginClass, pluginName, prefix));
      }
      if (key.endsWith(".instance")) {
        String prefix = key.substring(0, key.indexOf(".instance"));
        String pluginName = getNameByPrefix(prefix);
        Object pluginInstance = conf.getProperty(key);
        ret.plugins.add(new PluginHolder(ret, pluginInstance, pluginName, prefix));
      }
    }
    for (PluginHolder pluginHolder : ret.plugins) {
      ret.pluginsByPrefix.put(pluginHolder.fullPrefix, pluginHolder);
      ret.pluginsByNames.put(pluginHolder.pluginName, pluginHolder);

      Iterator<?> propertyIterator = conf.getKeys(pluginHolder.fullPrefix);
      while (propertyIterator.hasNext()) {
        String propertyName = (String) propertyIterator.next();
        if (propertyName.endsWith(".class")) {
          continue;
        }
        String property = propertyName;
        if (propertyName.contains(pluginHolder.fullPrefix)) {
          property = propertyName.substring(pluginHolder.fullPrefix.length() + 1);
        }
        pluginHolder.properties.put(property, conf.getProperty(propertyName).toString());
      }
    }
    cachedRegistries.put(conf, ret);
    return ret;
  }
 private static void logConfiguration(Configuration configuration) {
   if (LOG.isDebugEnabled()) {
     Iterator<String> keys = configuration.getKeys();
     LOG.debug("Configuration loaded:");
     while (keys.hasNext()) {
       String key = keys.next();
       LOG.debug("{} = {}", key, configuration.getProperty(key));
     }
   }
 }
 private void append(Map<String, Object> map, Configuration config) {
   if (config instanceof ConfigurableEnvironmentConfiguration) {
     return;
   }
   if (config instanceof SystemConfiguration) {
     return;
   }
   if (config instanceof EnvironmentConfiguration) {
     return;
   }
   for (Iterator<String> iter = config.getKeys(); iter.hasNext(); ) {
     String key = iter.next();
     map.put(key, config.getProperty(key));
   }
 }
 private Options getAsciiDocOptionsAndAttributes(ParserContext context) {
   Configuration config = context.getConfig();
   final AttributesBuilder attributes =
       attributes(config.getStringArray(Keys.ASCIIDOCTOR_ATTRIBUTES));
   if (config.getBoolean(Keys.ASCIIDOCTOR_ATTRIBUTES_EXPORT, false)) {
     final String prefix = config.getString(Keys.ASCIIDOCTOR_ATTRIBUTES_EXPORT_PREFIX, "");
     for (final Iterator<String> it = config.getKeys(); it.hasNext(); ) {
       final String key = it.next();
       if (!key.startsWith("asciidoctor")) {
         attributes.attribute(prefix + key.replace(".", "_"), config.getProperty(key));
       }
     }
   }
   final Configuration optionsSubset = config.subset(Keys.ASCIIDOCTOR_OPTION);
   final Options options = options().attributes(attributes.get()).get();
   for (final Iterator<String> iterator = optionsSubset.getKeys(); iterator.hasNext(); ) {
     final String name = iterator.next();
     options.setOption(name, guessTypeByContent(optionsSubset.getString(name)));
   }
   options.setBaseDir(context.getFile().getParentFile().getAbsolutePath());
   options.setSafe(UNSAFE);
   return options;
 }
  @Transactional
  public boolean changeCustomerPassword(Customer customer, String oldPassword, String newPassword)
      throws Exception {
    String key = EncryptionUtil.generatekey(String.valueOf(SecurityConstants.idConstant));
    String encrypted = EncryptionUtil.encrypt(key, newPassword);

    String old = EncryptionUtil.encrypt(key, oldPassword);

    if (!customer.getCustomerPassword().equals(old)) {
      return false;
    }

    customer.setCustomerPassword(encrypted);

    MerchantService mservice =
        (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);

    // MerchantUserInformation minfo = mservice.getMerchantUserInfo(customer
    //		.getMerchantId());

    MerchantStore store = mservice.getMerchantStore(customer.getMerchantId());

    customerDao.saveOrUptade(customer);

    // send email
    String l = config.getString("core.system.defaultlanguage", "en");
    if (!StringUtils.isBlank(customer.getCustomerLang())) {
      l = customer.getCustomerLang();
    }

    LabelUtil lhelper = LabelUtil.getInstance();
    String subject = lhelper.getText(l, "label.profile.information");
    String info = lhelper.getText(l, "label.email.customer.portalinfo");
    String pass = lhelper.getText(l, "label.email.customer.passwordreset.text") + " " + newPassword;

    // @TODO replace suffix
    String url =
        "<a href=\""
            + config.getString("core.accountmanagement.portal.url")
            + "\">"
            + config.getProperty("core.accountmanagement.portal.url")
            + "</a>";
    String portalurl = lhelper.getText(l, "label.email.customer.portalurl") + " " + url;

    Map emailctx = new HashMap();
    emailctx.put("EMAIL_STORE_NAME", store.getStorename());
    emailctx.put("EMAIL_CUSTOMER_PASSWORD", pass);
    emailctx.put("EMAIL_CUSTOMER_PORTAL_INFO", info);
    emailctx.put("EMAIL_CUSTOMER_PORTAL_ENTRY", portalurl);
    emailctx.put("EMAIL_CONTACT_OWNER", store.getStoreemailaddress());

    CommonService cservice = new CommonService();

    cservice.sendHtmlEmail(
        customer.getCustomerEmailAddress(),
        subject,
        store,
        emailctx,
        "email_template_password_reset_customer.ftl",
        customer.getCustomerLang());

    return true;
  }
  @Transactional(rollbackFor = {Exception.class})
  public void saveOrUpdateCustomer(Customer customer, SystemUrlEntryType entryType, Locale locale)
      throws Exception {

    MerchantService mservice =
        (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);

    MerchantStore store = mservice.getMerchantStore(customer.getMerchantId());
    // MerchantUserInformation minfo = mservice.getMerchantUserInfo(customer
    //		.getMerchantId());

    if (entryType == null) {
      entryType = SystemUrlEntryType.WEB;
    }

    // check if email aleady exist

    boolean isNew = false;
    if (customer.getCustomerId() == 0) {
      isNew = true;
    }

    if (isNew && !customer.isCustomerAnonymous()) {

      // generate password
      PasswordGeneratorModule passwordGenerator =
          (PasswordGeneratorModule) SpringUtil.getBean("passwordgenerator");

      // encrypt
      String key = EncryptionUtil.generatekey(String.valueOf(SecurityConstants.idConstant));
      boolean found = true;

      String password = null;
      String encrypted = null;
      // validate if already exist
      while (found) {

        password = passwordGenerator.generatePassword();
        encrypted = EncryptionUtil.encrypt(key, password);
        Customer cfound =
            customerDao.findByUserNameAndPassword(customer.getCustomerNick(), encrypted);
        if (cfound == null) {
          found = false;
        }
      }

      // store in customer
      customer.setCustomerNick(customer.getCustomerEmailAddress());
      customer.setCustomerPassword(encrypted);

      // send email
      String l = config.getString("core.system.defaultlanguage", "en");
      if (!StringUtils.isBlank(customer.getCustomerLang())) {
        l = customer.getCustomerLang();
      }

      LabelUtil lhelper = LabelUtil.getInstance();
      String subject = lhelper.getText(l, "label.profile.information");
      List params = new ArrayList();
      params.add(store.getStorename());
      String greeting = lhelper.getText(locale, "label.email.customer.greeting", params);

      String username =
          lhelper.getText(l, "label.generic.customer.username") + " " + customer.getCustomerNick();
      String pass = lhelper.getText(l, "label.generic.customer.password") + " " + password;

      String info = "";
      String portalurl = "";

      if (entryType == SystemUrlEntryType.PORTAL) {
        info = lhelper.getText(l, "label.email.customer.portalinfo");
        String url =
            "<a href=\""
                + config.getProperty("core.accountmanagement.portal.url")
                + "/"
                + customer.getMerchantId()
                + "\">"
                + config.getProperty("core.accountmanagement.portal.url")
                + "/"
                + customer.getMerchantId()
                + "</a>";
        portalurl = lhelper.getText(l, "label.email.customer.portalurl") + " " + url;
      } else {
        info = lhelper.getText(l, "label.email.customer.webinfo");
        String url =
            "<a href=\""
                + ReferenceUtil.buildCatalogUri(store)
                + "/\">"
                + ReferenceUtil.buildCatalogUri(store)
                + "/landing.action?merchantId="
                + store.getMerchantId()
                + "</a>";
        portalurl = lhelper.getText(l, "label.email.customer.weburl") + " " + url;
      }

      Map emailctx = new HashMap();
      emailctx.put("EMAIL_STORE_NAME", store.getStorename());
      emailctx.put("EMAIL_CUSTOMER_FIRSTNAME", customer.getCustomerFirstname());
      emailctx.put("EMAIL_CUSTOMER_LAST", customer.getCustomerLastname());
      emailctx.put("EMAIL_CUSTOMER_USERNAME", username);
      emailctx.put("EMAIL_CUSTOMER_PASSWORD", pass);
      emailctx.put("EMAIL_GREETING", greeting);
      emailctx.put("EMAIL_CUSTOMER_PORTAL_INFO", info);
      emailctx.put("EMAIL_CUSTOMER_PORTAL_ENTRY", portalurl);
      emailctx.put("EMAIL_CONTACT_OWNER", store.getStoreemailaddress());

      CommonService cservice = new CommonService();
      cservice.sendHtmlEmail(
          customer.getCustomerEmailAddress(),
          subject,
          store,
          emailctx,
          "email_template_customer.ftl",
          customer.getCustomerLang());
    }

    customerDao.saveOrUptade(customer);

    // set CustomerInfo

    CustomerInfo customerInfo = new CustomerInfo();
    customerInfo.setCustomerInfoId(customer.getCustomerId());

    int login = customerInfo.getCustomerInfoNumberOfLogon();
    customerInfo.setCustomerInfoNumberOfLogon(login++);
    customerInfo.setCustomerInfoDateOfLastLogon(new Date());
    customerInfoDao.saveOrUpdate(customerInfo);
  }
 @Override
 public Object propertyFor(BoundProperty key) {
   return config.getProperty(key.value());
 }