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     */
020    package org.sonar.core.persistence.dialect;
021    
022    import com.google.common.base.Predicate;
023    import com.google.common.collect.Iterators;
024    import org.apache.commons.lang.StringUtils;
025    import org.sonar.api.utils.SonarException;
026    
027    import java.util.NoSuchElementException;
028    
029    public final class DialectUtils {
030    
031      private DialectUtils() {
032      }
033    
034      private static final Dialect[] DIALECTS = new Dialect[]{new Derby(), new MySql(), new Oracle(), new PostgreSql(), new MsSql()};
035    
036      public static Dialect find(final String dialectId, final String jdbcConnectionUrl) {
037        Dialect match = StringUtils.isNotBlank(dialectId) ? findById(dialectId) : findByJdbcUrl(jdbcConnectionUrl);
038        if (match == null) {
039          throw new SonarException("Unable to determine database dialect to use within sonar with dialect " + dialectId + " jdbc url " + jdbcConnectionUrl);
040        }
041        return match;
042      }
043    
044      private static Dialect findByJdbcUrl(final String jdbcConnectionUrl) {
045        Dialect match = findDialect(new Predicate<Dialect>() {
046          public boolean apply(Dialect dialect) {
047            return dialect.matchesJdbcURL(StringUtils.trimToEmpty(jdbcConnectionUrl));
048          }
049        });
050        return match;
051      }
052    
053      private static Dialect findById(final String dialectId) {
054        return findDialect(new Predicate<Dialect>() {
055          public boolean apply(Dialect dialect) {
056            return 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    }