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

com.undefinedlabs.scope.settings.credentials.CredentialsUtils Maven / Gradle / Ivy

package com.undefinedlabs.scope.settings.credentials;

import org.apache.commons.lang3.StringUtils;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

public enum CredentialsUtils {
  INSTANCE;

  public ScopeCredentials extractFromDsn(final String scopeDsn) {
    if (StringUtils.isEmpty(scopeDsn)) {
      throw new IllegalArgumentException("DSN must not be null or empty.");
    }

    try {
      final URL url = URI.create(scopeDsn).toURL();
      return new ScopeCredentials(
          url.getProtocol()
              + "://"
              + url.getHost()
              + (url.getPort() != -1 ? ":" + url.getPort() : "")
              + (StringUtils.isNotEmpty(url.getPath()) ? url.getPath() : ""),
          url.getUserInfo());

    } catch (final Exception e) {
      throw new IllegalArgumentException(
          "DSN '" + scopeDsn + "' must be correct: " + e.getMessage());
    }
  }

  public String createDsn(final String apiEndpoint, final String apiKey) {
    if (StringUtils.isEmpty(apiEndpoint) || StringUtils.isEmpty(apiKey)) {
      return null;
    }

    try {
      final URL url = new URL(apiEndpoint);
      return url.getProtocol()
          + "://"
          + apiKey
          + "@"
          + url.getHost()
          + ((url.getPort() != -1) ? ":" + url.getPort() : "")
          + (StringUtils.isNotEmpty(url.getPath()) ? url.getPath() : "");
    } catch (final MalformedURLException e) {
      return apiEndpoint;
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy