web-dev-qa-db-fra.com

Comment analyser une URL JDBC pour obtenir le nom d'hôte, le port, etc.?

Comment analyser une URL JDBC (Oracle ou sqlserver) pour obtenir le nom d'hôte, le port et le nom de la base de données. Les formats de l'URL sont différents.

26
Mickel Lee

Commencez avec quelque chose comme ceci:

 String url = "jdbc: derby: // localhost: 1527/netld; collation = TERRITORY_BASED: PRIMARY"; 
 Chaîne cleanURI = url.substring (5); 
 
 URI uri = URI.create (cleanURI); 
 System.out.println (uri.getScheme ()); 
 System.out.println (uri.getHost ()); 
 System.out.println (uri.getPort ()); 
 System.out.println (uri.getPath ()); 

Sortie de ce qui précède:

 derby 
 localhost 
 1527 
/netld; collation = TERRITORY_BASED: PRIMARY 
44
brettw

Cela n'a pas fonctionné pour moi. Je suis venu avec ces méthodes, en partant du principe que le nom d’hôte et le port sont toujours reliés par deux points. Cette hypothèse est valable pour toutes les bases de données sur lesquelles je dois travailler (Oracle, Vertica, MySQL, etc.). Mais cela ne fonctionne probablement pas pour quelque chose qui n'atteint pas un port réseau.

String url = null; // set elsewhere in the class
final public String regexForHostAndPort = "[.\\w]+:\\d+";
final public Pattern hostAndPortPattern = Pattern.compile(regexForHostAndPort);
public String getHostFromUrl() {
    Matcher matcher = hostAndPortPattern.matcher(url); 
    matcher.find();
    int start = matcher.start();
    int end = matcher.end();
    if(start >= 0 && end >= 0) {
        String hostAndPort = url.substring(start, end);
        String [] array = hostAndPort.split(":");
        if(array.length >= 2)
            return array[0];
    }
    throw new IllegalArgumentException("couldn't find pattern '" + regexForHostAndPort + "' in '" + url + "'");
}

public int getPortFromUrl() {
    Matcher matcher = hostAndPortPattern.matcher(url); 
    matcher.find();
    int start = matcher.start();
    int end = matcher.end();
    if(start >= 0 && end >= 0) {
        String hostAndPort = url.substring(start, end);
        String [] array = hostAndPort.split(":");
        if(array.length >= 2)
            return Integer.parseInt(array[1]);
    }
    throw new IllegalArgumentException("couldn't find pattern '" + regexForHostAndPort + "' in '" + url + "'");
}
6
timbaileyjones

Sachez que la réponse de @ brettw peut échouer pour certaines URL jdbc valides. Si le nom de l'hôte contient un trait de soulignement, uri getHost () renvoie null (voir ici ) et getPost () renvoie -1.

Pour contourner cela, j'ai ajouté un chèque pour l'hôte nul:

  String jdbcUrl = "jdbc:jtds:sqlserver://ABC_XYZ:1433/Database";
  String cleanURI = jdbcUrl.substring("jdbc:jtds:".length());

  URI uri = URI.create(cleanURI);
  String Host = uri.getHost();
  int port = uri.getPort();

  if(Host == null){
    String regex = ".*://(\\w*):(\\d++)/.*";
    Pattern p = Pattern.compile(regex);

    Matcher matcher = p.matcher(jdbcUrl);
    if(matcher.find()){
      Host =  matcher.group(1);
      port =  Integer.valueOf(matcher.group(2));
    } else {
      // handle fail
    }
  }

  System.out.println("Host = " + Host);
  System.out.println("port = " + port);
1
JPC

J'utilise cette classe dans mes projets. L'utilisation est vraiment simple.

/**
 * Split di una url JDBC nei componenti.
 * Estrae i componenti di una uri JDBC del tipo: <br>
 * String url = "jdbc:derby://localhost:1527/netld;collation=TERRITORY_BASED:PRIMARY"; <br>
 * nelle rispettive variabili pubbliche.
 * @author Nicola De Nisco
 */
public class JdbcUrlSplitter
{
  public String driverName, Host, port, database, params;

  public JdbcUrlSplitter(String jdbcUrl)
  {
    int pos, pos1, pos2;
    String connUri;

    if(jdbcUrl == null || !jdbcUrl.startsWith("jdbc:")
       || (pos1 = jdbcUrl.indexOf(':', 5)) == -1)
      throw new IllegalArgumentException("Invalid JDBC url.");

    driverName = jdbcUrl.substring(5, pos1);
    if((pos2 = jdbcUrl.indexOf(';', pos1)) == -1)
    {
      connUri = jdbcUrl.substring(pos1 + 1);
    }
    else
    {
      connUri = jdbcUrl.substring(pos1 + 1, pos2);
      params = jdbcUrl.substring(pos2 + 1);
    }

    if(connUri.startsWith("//"))
    {
      if((pos = connUri.indexOf('/', 2)) != -1)
      {
        Host = connUri.substring(2, pos);
        database = connUri.substring(pos + 1);

        if((pos = Host.indexOf(':')) != -1)
        {
          port = Host.substring(pos + 1);
          Host = Host.substring(0, pos);
        }
      }
    }
    else
    {
      database = connUri;
    }
  }
}
1
Nicola De Nisco