Search in sources :

Example 16 with DalRuntimeException

use of com.ctrip.platform.dal.exceptions.DalRuntimeException in project dal by ctripcorp.

the class CompositeStrategyTransformer method visit.

@Override
public RouteStrategy visit(StrategyContext strategyContext) {
    try {
        if (strategyContext instanceof ZoneDividedStrategyContext) {
            ZoneDividedStrategyContext obStrategyContext = (ZoneDividedStrategyContext) strategyContext;
            CompositeRoundRobinStrategy localizedAccessStrategy = new CompositeRoundRobinStrategy();
            if (obStrategyContext.getZone() != null) {
                localizedAccessStrategy.setZone(obStrategyContext.getZone().toUpperCase());
            }
            for (Map.Entry<String, Set<HostSpec>> entry : obStrategyContext.entrySet()) {
                String zone = entry.getKey();
                Set<HostSpec> hostSpecSet = entry.getValue();
                RouteStrategy strategy = new ValidatorAwareRoundRobinStrategy();
                strategy.init(hostSpecSet, obStrategyContext.getStrategyProperties());
                if (strategy instanceof HostValidatorAware) {
                    ((HostValidatorAware) strategy).setHostValidator(obStrategyContext.getHostValidator());
                }
                localizedAccessStrategy.put(zone.toUpperCase(), strategy);
            }
            return localizedAccessStrategy;
        }
    } catch (Exception e) {
        throw new DalRuntimeException("generate error", e);
    }
    throw new DalRuntimeException("StrategyContext mismatch for " + strategyContext.getClass());
}
Also used : HostValidatorAware(com.ctrip.platform.dal.dao.datasource.cluster.strategy.multi.validator.HostValidatorAware) Set(java.util.Set) RouteStrategy(com.ctrip.platform.dal.dao.datasource.cluster.strategy.RouteStrategy) HostSpec(com.ctrip.framework.dal.cluster.client.base.HostSpec) DalRuntimeException(com.ctrip.platform.dal.exceptions.DalRuntimeException) DalRuntimeException(com.ctrip.platform.dal.exceptions.DalRuntimeException) Map(java.util.Map)

Example 17 with DalRuntimeException

use of com.ctrip.platform.dal.exceptions.DalRuntimeException in project dal by ctripcorp.

the class ForceSwitchableDataSource method getStatus.

public SwitchableDataSourceStatus getStatus() {
    synchronized (lock) {
        org.apache.tomcat.jdbc.pool.DataSource ds = (org.apache.tomcat.jdbc.pool.DataSource) getSingleDataSource().getDataSource();
        final String url = ds.getUrl();
        final String name = getSingleDataSource().getName();
        final String logName = String.format(GET_STATUS, name);
        try {
            LOGGER.logTransaction(DalLogTypes.DAL_CONFIGURE, logName, url, new Callback() {

                @Override
                public void execute() throws Exception {
                    if (!currentHostAndPort.isValid() || isUrlChanged(url)) {
                        currentHostAndPort.setValid(false);
                        LOGGER.logEvent(DalLogTypes.DAL_CONFIGURE, logName, "url changed, we will get url from connection");
                        try {
                            final CountDownLatch latch = new CountDownLatch(1);
                            executor.submit(new Runnable() {

                                public void run() {
                                    try (Connection conn = getConnection()) {
                                        HostAndPort hostAndPort = ConnectionStringParser.parseHostPortFromURL(conn.getMetaData().getURL());
                                        hostAndPort.setValid(true);
                                        setIpPortCache(hostAndPort);
                                        setPoolCreated(true);
                                    } catch (Exception e) {
                                        setIpPortCache(ConnectionStringParser.parseHostPortFromURL(url));
                                    } finally {
                                        latch.countDown();
                                    }
                                }
                            });
                            latch.await(1, TimeUnit.SECONDS);
                        } catch (Exception e) {
                            LOGGER.error("get connection error", e);
                        }
                    }
                }
            });
        } catch (Throwable t) {
            LOGGER.error("Get status error", t);
            throw new DalRuntimeException("Get status error", t);
        }
        boolean isForceSwitched;
        if (ForceSwitchedStatus.ForceSwitched.equals(forceSwitchedStatus)) {
            isForceSwitched = true;
        } else {
            isForceSwitched = false;
        }
        if (!currentHostAndPort.isValid()) {
            setIpPortCache(ConnectionStringParser.parseHostPortFromURL(url));
            return buildSwitchableDataSourceStatus(isForceSwitched, currentHostAndPort.getHost(), url, currentHostAndPort.getPort(), false);
        }
        return buildSwitchableDataSourceStatus(isForceSwitched, currentHostAndPort.getHost(), url, currentHostAndPort.getPort(), poolCreated);
    }
}
Also used : Connection(java.sql.Connection) DalRuntimeException(com.ctrip.platform.dal.exceptions.DalRuntimeException) SQLException(java.sql.SQLException) DalRuntimeException(com.ctrip.platform.dal.exceptions.DalRuntimeException) Callback(com.ctrip.platform.dal.dao.log.Callback)

Example 18 with DalRuntimeException

use of com.ctrip.platform.dal.exceptions.DalRuntimeException in project dal by ctripcorp.

the class ForceSwitchableDataSource method restore.

public SwitchableDataSourceStatus restore() {
    synchronized (lock) {
        final SwitchableDataSourceStatus oldStatus = getStatus();
        final String name = getSingleDataSource().getName();
        final String logName = String.format(RESTORE, name);
        try {
            LOGGER.logTransaction(DalLogTypes.DAL_CONFIGURE, logName, "restore", new Callback() {

                @Override
                public void execute() throws Exception {
                    DataSourceConfigure configure = getSingleDataSource().getDataSourceConfigure().clone();
                    LOGGER.logEvent(DalLogTypes.DAL_CONFIGURE, logName, String.format("old connection url: %s", configure.getConnectionUrl()));
                    LOGGER.logEvent(DalLogTypes.DAL_CONFIGURE, logName, String.format("old isForceSwitched before restore: %s, old poolCreated before restore: %s", oldStatus.isForceSwitched(), oldStatus.isPoolCreated()));
                    if (!ForceSwitchedStatus.ForceSwitched.equals(forceSwitchedStatus)) {
                        LOGGER.logEvent(DalLogTypes.DAL_CONFIGURE, logName, String.format("%s is not force switched, return", name));
                        return;
                    }
                    final DataSourceConfigure newConfigure = DataSourceConfigure.valueOf(provider.forceLoadDataSourceConfigure());
                    LOGGER.logEvent(DalLogTypes.DAL_CONFIGURE, logName, String.format("new connection url: %s", newConfigure.getConnectionUrl()));
                    asyncRefreshDataSource(name, newConfigure, new RestoreListener() {

                        public void onCreatePoolSuccess() {
                            LOGGER.logEvent(DalLogTypes.DAL_DATASOURCE, String.format("onCreatePoolSuccess: %s", name), newConfigure.getConnectionUrl());
                            poolCreated = true;
                            forceSwitchedStatus = ForceSwitchedStatus.UnForceSwitched;
                            oldForceSwitchedStatus = ForceSwitchedStatus.UnForceSwitched;
                            final SwitchableDataSourceStatus status = getStatus();
                            LOGGER.logEvent(DalLogTypes.DAL_DATASOURCE, String.format("onCreatePoolSuccess::notifyListeners: %s", name), "notify listeners' onRestoreSuccess");
                            for (final SwitchListener listener : listeners) executor.submit(new Runnable() {

                                @Override
                                public void run() {
                                    try {
                                        listener.onRestoreSuccess(status);
                                    } catch (Exception e1) {
                                        LOGGER.error("call listener.onRestoreSuccess() error ", e1);
                                    }
                                }
                            });
                        }

                        public void onCreatePoolFail(final Throwable e) {
                            LOGGER.logEvent(DalLogTypes.DAL_DATASOURCE, String.format("onCreatePoolFail: %s", name), e.getMessage());
                            final SwitchableDataSourceStatus status = getStatus();
                            LOGGER.logEvent(DalLogTypes.DAL_DATASOURCE, String.format("onCreatePoolFail::notifyListeners: %s", name), "notify listeners' onRestoreFail");
                            for (final SwitchListener listener : listeners) executor.submit(new Runnable() {

                                @Override
                                public void run() {
                                    try {
                                        listener.onRestoreFail(status, e);
                                    } catch (Exception e1) {
                                        LOGGER.error("call listener.onRestoreFail() error ", e1);
                                    }
                                }
                            });
                        }
                    });
                }
            });
        } catch (Throwable t) {
            LOGGER.error("Restore error", t);
            throw new DalRuntimeException("Restore error", t);
        }
        return oldStatus;
    }
}
Also used : DalRuntimeException(com.ctrip.platform.dal.exceptions.DalRuntimeException) Callback(com.ctrip.platform.dal.dao.log.Callback) DalRuntimeException(com.ctrip.platform.dal.exceptions.DalRuntimeException) SQLException(java.sql.SQLException)

Example 19 with DalRuntimeException

use of com.ctrip.platform.dal.exceptions.DalRuntimeException in project dal by ctripcorp.

the class DalStatementCreator method validateAndReorderParameter.

private void validateAndReorderParameter(ParametersType type, int index, StatementParameter parameter) {
    if (type == ParametersType.index) {
        if (index != parameter.getIndex())
            throw new DalRuntimeException(String.format("The index of parameter :%s doesn't match with the index in sql string", parameter.getName()));
    }
    parameter.setIndex(index);
    parameter.setTSQLParameter(true);
}
Also used : DalRuntimeException(com.ctrip.platform.dal.exceptions.DalRuntimeException)

Example 20 with DalRuntimeException

use of com.ctrip.platform.dal.exceptions.DalRuntimeException in project dal by ctripcorp.

the class DalTransactionalEnabler method replaceBeanDefinition.

private void replaceBeanDefinition() {
    for (String beanName : getBeanDefinitionNames()) {
        BeanDefinition beanDef = getBeanDefinition(beanName);
        String beanClassName = beanDef.getBeanClassName();
        if (beanClassName == null || beanClassName.equals(BEAN_FACTORY_NAME))
            continue;
        Class beanClass;
        try {
            beanClass = Class.forName(beanDef.getBeanClassName());
        } catch (ClassNotFoundException e) {
            throw new BeanDefinitionValidationException("Cannot validate bean: " + beanName, e);
        }
        boolean annotated = false;
        List<Method> methods = new ArrayList<>();
        ReflectUtils.addAllMethods(beanClass, methods);
        List<Method> unsupportedMethods = new ArrayList<>();
        for (int i = 0; i < methods.size(); i++) {
            Method currentMethod = methods.get(i);
            if (isTransactionAnnotated(currentMethod)) {
                if (Modifier.isFinal(currentMethod.getModifiers()) || Modifier.isStatic(currentMethod.getModifiers()) || Modifier.isPrivate(currentMethod.getModifiers()))
                    unsupportedMethods.add(currentMethod);
                annotated = true;
            }
        }
        if (!unsupportedMethods.isEmpty()) {
            StringBuilder errMsg = new StringBuilder();
            errMsg.append(String.format("The Methods below are not supported in dal transaction due to private, final or static modifier, please use public,protected or default modifier instead:"));
            errMsg.append("\n");
            int index = 1;
            for (Method method : unsupportedMethods) {
                errMsg.append(String.format("%d. %s", index, method.toString()));
                errMsg.append("\n");
                index++;
            }
            throw new DalRuntimeException(errMsg.toString());
        }
        if (!annotated)
            continue;
        beanDef.setBeanClassName(BEAN_FACTORY_NAME);
        beanDef.setFactoryMethodName(FACTORY_METHOD_NAME);
        ConstructorArgumentValues cav = beanDef.getConstructorArgumentValues();
        if (cav.getArgumentCount() != 0)
            throw new BeanDefinitionValidationException("The transactional bean can only be instantiated with default constructor.");
        cav.addGenericArgumentValue(beanClass.getName());
    }
}
Also used : BeanDefinitionValidationException(org.springframework.beans.factory.support.BeanDefinitionValidationException) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) ConstructorArgumentValues(org.springframework.beans.factory.config.ConstructorArgumentValues) DalRuntimeException(com.ctrip.platform.dal.exceptions.DalRuntimeException)

Aggregations

DalRuntimeException (com.ctrip.platform.dal.exceptions.DalRuntimeException)29 DalContextClient (com.ctrip.platform.dal.dao.DalContextClient)8 StatementParameters (com.ctrip.platform.dal.dao.StatementParameters)8 ConnectionString (com.ctrip.framework.dal.cluster.client.database.ConnectionString)4 SQLException (java.sql.SQLException)4 ArrayList (java.util.ArrayList)4 Callback (com.ctrip.platform.dal.dao.log.Callback)3 Map (java.util.Map)3 Cluster (com.ctrip.framework.dal.cluster.client.Cluster)2 UpdatableEntity (com.ctrip.platform.dal.dao.UpdatableEntity)2 RouteStrategy (com.ctrip.platform.dal.dao.datasource.cluster.strategy.RouteStrategy)2 Node (org.w3c.dom.Node)2 HostSpec (com.ctrip.framework.dal.cluster.client.base.HostSpec)1 Listener (com.ctrip.framework.dal.cluster.client.base.Listener)1 ClusterConfig (com.ctrip.framework.dal.cluster.client.config.ClusterConfig)1 DalConfigCustomizedOption (com.ctrip.framework.dal.cluster.client.config.DalConfigCustomizedOption)1 ClusterConfigException (com.ctrip.framework.dal.cluster.client.exception.ClusterConfigException)1 CustomDataSourceFactory (com.ctrip.framework.dal.cluster.client.extended.CustomDataSourceFactory)1 DatabaseShard (com.ctrip.framework.dal.cluster.client.shard.DatabaseShard)1 ClusterIdGeneratorConfig (com.ctrip.framework.dal.cluster.client.sharding.idgen.ClusterIdGeneratorConfig)1