001/*
002 * Sonar, open source software quality management tool.
003 * Copyright (C) 2008-2012 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * Sonar is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * Sonar is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public
017 * License along with Sonar; if not, write to the Free Software
018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
019 */
020package org.sonar.core.persistence.dialect;
021
022import com.google.common.base.Predicate;
023import com.google.common.collect.Iterators;
024import org.apache.commons.lang.StringUtils;
025import org.sonar.api.utils.SonarException;
026
027import javax.annotation.Nullable;
028import java.util.NoSuchElementException;
029
030public final class DialectUtils {
031
032  private DialectUtils() {
033  }
034
035  private static final Dialect[] DIALECTS = new Dialect[]{new Derby(), new MySql(), new Oracle(), new PostgreSql(), new MsSql()};
036
037  public static Dialect find(final String dialectId, final String jdbcConnectionUrl) {
038    Dialect match = StringUtils.isNotBlank(dialectId) ? findById(dialectId) : findByJdbcUrl(jdbcConnectionUrl);
039    if (match == null) {
040      throw new SonarException("Unable to determine database dialect to use within sonar with dialect " + dialectId + " jdbc url " + jdbcConnectionUrl);
041    }
042    return match;
043  }
044
045  private static Dialect findByJdbcUrl(final String jdbcConnectionUrl) {
046    return findDialect(new Predicate<Dialect>() {
047      public boolean apply(@Nullable Dialect dialect) {
048        return dialect != null && dialect.matchesJdbcURL(StringUtils.trimToEmpty(jdbcConnectionUrl));
049      }
050    });
051  }
052
053  private static Dialect findById(final String dialectId) {
054    return findDialect(new Predicate<Dialect>() {
055      public boolean apply(@Nullable Dialect dialect) {
056        return dialect != null && dialect.getId().equals(dialectId);
057      }
058    });
059  }
060
061  private static Dialect findDialect(Predicate<Dialect> predicate) {
062    try {
063      return Iterators.find(Iterators.forArray(DIALECTS), predicate);
064    } catch (NoSuchElementException ex) {
065      return null;
066    }
067  }
068}