001/*
002// This software is subject to the terms of the Eclipse Public License v1.0
003// Agreement, available at the following URL:
004// http://www.eclipse.org/legal/epl-v10.html.
005// You must accept the terms of that agreement to use this software.
006//
007// Copyright (C) 2012-2012 Pentaho and others
008// All Rights Reserved.
009*/
010package mondrian.rolap;
011
012import mondrian.olap.Util;
013import mondrian.util.*;
014
015import javax.sql.DataSource;
016
017/**
018 * Globally unique identifier for the definition of a JDBC database connection.
019 *
020 * <p>Two connections should have the same connection key if and only if their
021 * databases have the same content.</p>
022 *
023 * @see RolapConnectionProperties#JdbcConnectionUuid
024 *
025 * @author jhyde
026 */
027class ConnectionKey extends StringKey {
028    private ConnectionKey(String s) {
029        super(s);
030    }
031
032    static ConnectionKey create(
033        final String connectionUuidStr,
034        final DataSource dataSource,
035        final String catalogUrl,
036        final String connectionKey,
037        final String jdbcUser,
038        final String dataSourceStr)
039    {
040        String s;
041        if (connectionUuidStr != null
042            && connectionUuidStr.length() != 0)
043        {
044            s = connectionUuidStr;
045        } else {
046            final StringBuilder buf = new StringBuilder(100);
047            if (dataSource != null) {
048                attributeValue(buf, "jvm", Util.JVM_INSTANCE_UUID);
049                attributeValue(
050                    buf, "dataSource", System.identityHashCode(dataSource));
051            } else {
052                attributeValue(buf, "connectionKey", connectionKey);
053                attributeValue(buf, "catalogUrl", catalogUrl);
054                attributeValue(buf, "jdbcUser", jdbcUser);
055                attributeValue(buf, "dataSourceStr", dataSourceStr);
056            }
057            s = new ByteString(Util.digestMd5(buf.toString())).toString();
058        }
059        return new ConnectionKey(s);
060    }
061
062    static void attributeValue(
063        StringBuilder buf, String attribute, Object value)
064    {
065        if (value == null) {
066            return;
067        }
068        if (buf.length() > 0) {
069            buf.append(';');
070        }
071        buf.append(attribute)
072            .append('=');
073        Util.quoteForMdx(buf, value.toString());
074    }
075}
076
077// End ConnectionKey.java