Search in sources :

Example 1 with Database

use of org.wso2.carbon.humantask.core.db.Database in project jaggery by wso2.

the class ShellUtilityService method initializeUtilityServices.

/**
     * Initialize utility services for command line client
     * @throws SQLException 
     *
     */
protected static void initializeUtilityServices() throws SQLException {
    //H2 database
    final H2DatabaseManager databaseManager = H2DatabaseManager.getInstance();
    databaseManager.initialize();
}
Also used : H2DatabaseManager(org.wso2.carbon.h2.osgi.console.H2DatabaseManager)

Example 2 with Database

use of org.wso2.carbon.humantask.core.db.Database in project jaggery by wso2.

the class DatabaseHostObject method jsConstructor.

public static Scriptable jsConstructor(Context cx, Object[] args, Function ctorObj, boolean inNewExpr) throws ScriptException {
    int argsCount = args.length;
    DatabaseHostObject db = new DatabaseHostObject();
    //args count 1 for dataSource name
    if (argsCount != 1 && argsCount != 3 && argsCount != 4) {
        HostObjectUtil.invalidNumberOfArgs(hostObjectName, hostObjectName, argsCount, true);
    }
    if (!(args[0] instanceof String)) {
        HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "1", "string", args[0], true);
    }
    if (argsCount == 1) {
        String dataSourceName = (String) args[0];
        DataSourceManager dataSourceManager = new DataSourceManager();
        try {
            CarbonDataSource carbonDataSource = dataSourceManager.getInstance().getDataSourceRepository().getDataSource(dataSourceName);
            DataSource dataSource = (DataSource) carbonDataSource.getDSObject();
            db.conn = dataSource.getConnection();
            db.context = cx;
            return db;
        } catch (DataSourceException e) {
            log.error("Failed to access datasource " + dataSourceName, e);
        } catch (SQLException e) {
            log.error("Failed to get connection", e);
        }
    }
    if (!(args[1] instanceof String)) {
        HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "2", "string", args[1], true);
    }
    if (!(args[2] instanceof String) && !(args[2] instanceof Integer)) {
        HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "3", "string", args[2], true);
    }
    NativeObject configs = null;
    if (argsCount == 4) {
        if (!(args[3] instanceof NativeObject)) {
            HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "4", "object", args[3], true);
        }
        configs = (NativeObject) args[3];
    }
    String dbUrl = (String) args[0];
    RDBMSConfiguration rdbmsConfig = new RDBMSConfiguration();
    try {
        if (configs != null) {
            Gson gson = new Gson();
            rdbmsConfig = gson.fromJson(HostObjectUtil.serializeJSON(configs), RDBMSConfiguration.class);
        }
        if (rdbmsConfig.getDriverClassName() == null || rdbmsConfig.getDriverClassName().equals("")) {
            rdbmsConfig.setDriverClassName(getDriverClassName(dbUrl));
        }
        rdbmsConfig.setUsername((String) args[1]);
        rdbmsConfig.setPassword((String) args[2]);
        rdbmsConfig.setUrl(dbUrl);
        try {
            rdbmsDataSource = new RDBMSDataSource(rdbmsConfig);
        } catch (DataSourceException e) {
            throw new ScriptException(e);
        }
        db.conn = rdbmsDataSource.getDataSource().getConnection();
        db.context = cx;
        return db;
    } catch (SQLException e) {
        String msg = "Error connecting to the database : " + dbUrl;
        log.warn(msg, e);
        throw new ScriptException(msg, e);
    }
}
Also used : CarbonDataSource(org.wso2.carbon.ndatasource.core.CarbonDataSource) RDBMSDataSource(org.wso2.carbon.ndatasource.rdbms.RDBMSDataSource) Gson(com.google.gson.Gson) DataSourceManager(org.wso2.carbon.ndatasource.core.DataSourceManager) RDBMSConfiguration(org.wso2.carbon.ndatasource.rdbms.RDBMSConfiguration) DataSource(javax.sql.DataSource) CarbonDataSource(org.wso2.carbon.ndatasource.core.CarbonDataSource) RDBMSDataSource(org.wso2.carbon.ndatasource.rdbms.RDBMSDataSource) NativeObject(org.mozilla.javascript.NativeObject) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) DataSourceException(org.wso2.carbon.ndatasource.common.DataSourceException)

Example 3 with Database

use of org.wso2.carbon.humantask.core.db.Database in project carbon-apimgt by wso2.

the class ApiDAOImpl method getDedicatedGateway.

/**
 * @see ApiDAO#getDedicatedGateway(String)
 */
@Override
public DedicatedGateway getDedicatedGateway(String apiId) throws APIMgtDAOException {
    final String query = "SELECT HAS_OWN_GATEWAY FROM AM_API WHERE UUID = ?";
    DedicatedGateway dedicatedGateway;
    try (Connection connection = DAOUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(query)) {
        try {
            statement.setString(1, apiId);
            statement.execute();
            try (ResultSet rs = statement.getResultSet()) {
                if (rs.next()) {
                    dedicatedGateway = new DedicatedGateway();
                    dedicatedGateway.setEnabled(rs.getBoolean(ContainerBasedGatewayConstants.IS_DEDICATED_GATEWAY_ENABLED));
                    return dedicatedGateway;
                } else {
                    throw new APIMgtDAOException("Couldn't Find Dedicated Gateway details ", ExceptionCodes.DEDICATED_GATEWAY_DETAILS_NOT_FOUND);
                }
            }
        } catch (SQLException e) {
            String errorMessage = "Error while retrieving dedicated gateway details of API : " + apiId;
            throw new APIMgtDAOException(errorMessage, e);
        }
    } catch (SQLException e) {
        String message = "Error while creating database connection/prepared-statement";
        throw new APIMgtDAOException(message, e);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) DedicatedGateway(org.wso2.carbon.apimgt.core.models.DedicatedGateway)

Example 4 with Database

use of org.wso2.carbon.humantask.core.db.Database in project carbon-apimgt by wso2.

the class AnalyticsDAOImpl method getApplicationCount.

/**
 * @see AnalyticsDAO#getApplicationCount(Instant, Instant, String)
 */
@Override
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
public List<ApplicationCount> getApplicationCount(Instant fromTimestamp, Instant toTimestamp, String createdBy) throws APIMgtDAOException {
    final String query;
    if (StringUtils.isNotEmpty(createdBy)) {
        query = "SELECT COUNT(UUID) AS count, CREATED_TIME AS time " + "FROM AM_APPLICATION " + "WHERE (CREATED_TIME BETWEEN ? AND ?) " + "AND CREATED_BY = ?" + "GROUP BY CREATED_TIME " + "ORDER BY CREATED_TIME ASC";
    } else {
        query = "SELECT COUNT(UUID) AS count, CREATED_TIME AS time " + "FROM AM_APPLICATION " + "WHERE (CREATED_TIME BETWEEN ? AND ?) " + "GROUP BY CREATED_TIME " + "ORDER BY CREATED_TIME ASC";
    }
    List<ApplicationCount> applicationCountList = new ArrayList<>();
    try (Connection connection = DAOUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(query)) {
        statement.setTimestamp(1, Timestamp.from(fromTimestamp));
        statement.setTimestamp(2, Timestamp.from(toTimestamp));
        if (StringUtils.isNotEmpty(createdBy)) {
            statement.setString(3, createdBy);
        }
        log.debug("Executing query: {} ", query);
        statement.execute();
        try (ResultSet rs = statement.getResultSet()) {
            long count = 0;
            while (rs.next()) {
                ApplicationCount applicationCount = new ApplicationCount();
                count += rs.getLong("count");
                applicationCount.setTimestamp(rs.getTimestamp("time").getTime());
                applicationCount.setCount(count);
                applicationCountList.add(applicationCount);
            }
        }
    } catch (SQLException e) {
        String errorMsg = "Error while creating database connection/prepared-statement";
        throw new APIMgtDAOException(errorMsg, e);
    }
    return applicationCountList;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) ApplicationCount(org.wso2.carbon.apimgt.core.models.analytics.ApplicationCount) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 5 with Database

use of org.wso2.carbon.humantask.core.db.Database in project carbon-apimgt by wso2.

the class ApiDAOImpl method getAPIsByStatus.

/**
 * @see ApiDAO#getAPIsByStatus(Set, List, List)
 */
@Override
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
public List<API> getAPIsByStatus(Set<String> roles, List<String> statuses, List<String> labels) throws APIMgtDAOException {
    // check for null at the beginning before constructing the query to retrieve APIs from database
    if (roles == null || statuses == null) {
        String errorMessage = "Role list or API status list should not be null to retrieve APIs.";
        log.error(errorMessage);
        throw new APIMgtDAOException(errorMessage);
    }
    // the below query will be used to retrieve the union of,
    // published/prototyped APIs (statuses) with public visibility and
    // published/prototyped APIs with restricted visibility where APIs are restricted based on roles of the user
    String labelQuery = null;
    if (labels.isEmpty()) {
        labelQuery = "SELECT LABEL_ID FROM  AM_LABELS WHERE TYPE_NAME='STORE'";
    } else {
        labelQuery = "SELECT LABEL_ID FROM  AM_LABELS WHERE NAME IN ( " + DAOUtil.getParameterString(labels.size()) + ") AND TYPE_NAME='STORE'";
    }
    final String query = "Select UUID, PROVIDER, NAME, CONTEXT, VERSION, DESCRIPTION, CURRENT_LC_STATUS, " + "LIFECYCLE_INSTANCE_ID, LC_WORKFLOW_STATUS, SECURITY_SCHEME  FROM (" + API_SUMMARY_SELECT + " WHERE " + "VISIBILITY = '" + API.Visibility.PUBLIC + "' " + "AND " + "CURRENT_LC_STATUS  IN (" + DAOUtil.getParameterString(statuses.size()) + ") AND " + "API_TYPE_ID = (SELECT TYPE_ID FROM AM_API_TYPES WHERE TYPE_NAME = ?)" + "UNION " + API_SUMMARY_SELECT + " WHERE " + "VISIBILITY = '" + API.Visibility.RESTRICTED + "' " + "AND " + "UUID IN (SELECT API_ID FROM AM_API_VISIBLE_ROLES WHERE ROLE IN " + "(" + DAOUtil.getParameterString(roles.size()) + ")) " + " AND CURRENT_LC_STATUS  IN (" + DAOUtil.getParameterString(statuses.size()) + ") AND " + " API_TYPE_ID = (SELECT TYPE_ID FROM AM_API_TYPES WHERE TYPE_NAME = ?)) A" + " JOIN AM_API_LABEL_MAPPING LM ON A.UUID=LM.API_ID WHERE LM.LABEL_ID IN (" + labelQuery + ")";
    try (Connection connection = DAOUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(query)) {
        int i = 0;
        // put desired API status into the query (to get APIs with public visibility)
        for (String status : statuses) {
            statement.setString(++i, status);
        }
        statement.setString(++i, ApiType.STANDARD.toString());
        // put desired roles into the query
        for (String role : roles) {
            statement.setString(++i, role);
        }
        // put desired API status into the query (to get APIs with restricted visibility)
        for (String status : statuses) {
            statement.setString(++i, status);
        }
        statement.setString(++i, ApiType.STANDARD.toString());
        // Set the label names in the query
        for (String label : labels) {
            statement.setString(++i, label);
        }
        return constructAPISummaryList(connection, statement);
    } catch (SQLException e) {
        String errorMessage = "Error while retrieving API list in store.";
        throw new APIMgtDAOException(errorMessage, e);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Aggregations

SQLException (java.sql.SQLException)29 PreparedStatement (java.sql.PreparedStatement)28 Connection (java.sql.Connection)24 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)23 ResultSet (java.sql.ResultSet)16 ArrayList (java.util.ArrayList)13 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)12 Map (java.util.Map)6 DeviceMgtPluginException (org.wso2.iot.sampledevice.plugin.exception.DeviceMgtPluginException)6 HashMap (java.util.HashMap)5 BpelDatabase (org.apache.ode.bpel.engine.BpelDatabase)5 File (java.io.File)4 InstanceFilter (org.apache.ode.bpel.common.InstanceFilter)4 BpelDAOConnection (org.apache.ode.bpel.dao.BpelDAOConnection)4 InstanceManagementException (org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.InstanceManagementException)4 Device (org.wso2.carbon.device.mgt.common.Device)4 IOException (java.io.IOException)3 Collection (java.util.Collection)3 DataSource (javax.sql.DataSource)3 ProcessInstanceDAO (org.apache.ode.bpel.dao.ProcessInstanceDAO)3