Example usage for java.sql Connection setAutoCommit

List of usage examples for java.sql Connection setAutoCommit

Introduction

In this page you can find the example usage for java.sql Connection setAutoCommit.

Prototype

void setAutoCommit(boolean autoCommit) throws SQLException;

Source Link

Document

Sets this connection's auto-commit mode to the given state.

Usage

From source file:com.autentia.tnt.bill.migration.support.MigratedInformationRecoverer.java

/**
 * Recupera la suma total de todos los conceptos de cada una de las facturas cuyo tipo se envia por parametro
 * @param billType tipo de factura/*from  w  w w .  j a v  a2 s  .c o m*/
 */
public static double[] getImporteFacturaMigrated(String billType) throws Exception {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    LineNumberReader file = null;
    double[] result = new double[0];

    try {
        log.info("RECOVERING IMPORTE FACTURAS " + billType + " MIGRADAS");

        // connect to database
        Class.forName(BillToBillPaymentMigration.DATABASE_DRIVER);
        con = DriverManager.getConnection(BillToBillPaymentMigration.DATABASE_CONNECTION,
                BillToBillPaymentMigration.DATABASE_USER, BillToBillPaymentMigration.DATABASE_PASS); // NOSONAR
        con.setAutoCommit(false); // DATABASE_PASS vacio         

        String sql = "SELECT bp.amount FROM BillPayment bp, Bill b where bp.billId = b.id and b.billType = ? order by amount";

        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, billType);
        rs = pstmt.executeQuery();

        rs.last();
        result = new double[rs.getRow()];
        rs.beforeFirst();
        int counter = 0;

        while (rs.next()) {
            result[counter] = rs.getDouble(1);
            log.info("\t" + result[counter]);
            counter++;
        }

    } catch (Exception e) {
        log.error("FAILED: WILL BE ROLLED BACK: ", e);
        if (con != null) {
            con.rollback();
        }

    } finally {
        cierraFichero(file);
        liberaConexion(con, pstmt, rs);
    }
    return result;
}

From source file:com.autentia.tnt.bill.migration.support.OriginalInformationRecoverer.java

/**
 * Recupera la suma total de todos los conceptos de cada una de las facturas cuyo tipo se envia por parametro
 * @param billType tipo de factura/*from   w w w  .ja va2s .  c  o m*/
 */
public static double[] getImporteFacturaOriginal(String billType) throws Exception {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    LineNumberReader file = null;
    double[] result = new double[0];

    try {
        log.info("RECOVERING IMPORTE FACTURAS " + billType + " ORIGINALES");

        // connect to database
        Class.forName(BillToBillPaymentMigration.DATABASE_DRIVER);
        con = DriverManager.getConnection(BillToBillPaymentMigration.DATABASE_CONNECTION,
                BillToBillPaymentMigration.DATABASE_USER, BillToBillPaymentMigration.DATABASE_PASS); //NOSONAR
        con.setAutoCommit(false); //DATABASE_PASS vacio.            

        String sql = "SELECT sum((bb.units*bb.amount)*(1+(bb.iva/100))) as total from Bill b left join BillBreakDown bb on b.id=bb.billId, Organization o, Project p where b.projectId = p.id and p.organizationId = o.id and b.billType= ? group by b.id order by total";

        pstmt = con.prepareStatement(sql);

        rs = pstmt.executeQuery();
        pstmt.setString(1, billType);

        rs.last();
        result = new double[rs.getRow()];
        rs.beforeFirst();
        int counter = 0;

        while (rs.next()) {
            result[counter] = rs.getDouble(1);
            log.info("\t" + result[counter]);
            counter++;
        }
        con.commit();
    } catch (Exception e) {
        log.error("FAILED: WILL BE ROLLED BACK: ", e);
        if (con != null) {
            con.rollback();
        }
    } finally {
        cierraFichero(file);
        liberaConexion(con, pstmt, rs);
    }
    return result;
}

From source file:com.aurel.track.admin.customize.category.filter.PredefinedQueryBL.java

/**
 * We forgot to add also the watcher at Migrate400To410.
 * This will be added at Migrate410To412
 * Although it will not appear implicitly in the menu items for users we should define it
 * because otherwise the watcher part of MyItems dashboard does not work
 *///from w  w w  .ja  va  2s.co  m
public static void addWatcherFilter() {
    LOGGER.info("Add watcher filters");
    FilterFacade filterFacade = FilterFacadeFactory.getInstance()
            .getFilterFacade(TQueryRepositoryBean.QUERY_PURPOSE.TREE_FILTER, true);
    // Get not closed stateIDs
    List<TStateBean> notClosedStateBeans = StatusBL.loadNotClosedStates();
    List<Integer> notClosedStateIDs = GeneralUtils.createIntegerListFromBeanList(notClosedStateBeans);
    Integer[] notClosedStatesArr = GeneralUtils.createIntegerArrFromCollection(notClosedStateIDs);
    ILabelBean watcherBean = filterFacade.getByKey(PREDEFINED_QUERY.WATCHER_ITEMS);
    if (watcherBean == null) {
        Connection cono = null;
        try {
            cono = InitDatabase.getConnection();
            Statement ostmt = cono.createStatement();
            cono.setAutoCommit(false);
            ostmt.executeUpdate(addPredefinedQueryClob(PREDEFINED_QUERY.WATCHER_ITEMS,
                    PredefinedQueryBL.getWatcherItemsExpression(notClosedStatesArr)));
            ostmt.executeUpdate(addPredefinedQuery(PREDEFINED_QUERY.WATCHER_ITEMS, "I''m watcher"));
            cono.commit();
            cono.setAutoCommit(true);
        } catch (Exception e) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        } finally {
            try {
                if (cono != null) {
                    cono.close();
                }
            } catch (Exception e) {
                LOGGER.info("Closing the connection failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
}

From source file:com.aurel.track.admin.customize.localize.LocalizeBL.java

/**
 * Update the resources based on the properties
 * @param properties/*from  www  .  ja va2s  . c o m*/
 * @param strLocale
 * @param overwrite whether to overwrite the edited resources
 * @param withPrimaryKey whether the used to be BoxResources are imported or the ApplicationResources 
 */
static synchronized void uploadResources(Properties properties, String strLocale, boolean overwrite,
        boolean withPrimaryKey, boolean initBoxResources) {
    List<TLocalizedResourcesBean> resourceBeans = getResourcesForLocale(strLocale, withPrimaryKey);
    SortedMap<String, List<TLocalizedResourcesBean>> existingLabels = new TreeMap<String, List<TLocalizedResourcesBean>>();
    for (TLocalizedResourcesBean localizedResourcesBean : resourceBeans) {
        String key = localizedResourcesBean.getFieldName();
        if (withPrimaryKey) {
            if (key.startsWith(LocalizationKeyPrefixes.FIELD_LABEL_KEY_PREFIX)
                    || key.startsWith(LocalizationKeyPrefixes.FIELD_TOOLTIP_KEY_PREFIX)) {
                key += ".";
            }
            key = key + localizedResourcesBean.getPrimaryKeyValue();
        }
        List<TLocalizedResourcesBean> localizedResources = existingLabels.get(key);
        if (localizedResources == null) {
            localizedResources = new LinkedList<TLocalizedResourcesBean>();
            existingLabels.put(key, localizedResources);
        }
        localizedResources.add(localizedResourcesBean);
    }
    Enumeration propertyNames = properties.keys();
    Connection connection = null;
    try {
        connection = Transaction.begin();
        connection.setAutoCommit(false);
        while (propertyNames.hasMoreElements()) {
            String key = (String) propertyNames.nextElement();
            String localizedText = LocalizeBL.correctString(properties.getProperty(key));
            Integer primaryKey = null;
            String fieldName = null;
            if (withPrimaryKey) {
                int primaryKeyIndex = key.lastIndexOf(".");
                if (primaryKeyIndex != -1) {
                    try {
                        primaryKey = Integer.valueOf(key.substring(primaryKeyIndex + 1));
                    } catch (Exception e) {
                        LOGGER.warn("The last part after . can't be converted to integer " + e.getMessage());
                        LOGGER.debug(ExceptionUtils.getStackTrace(e));
                    }
                    fieldName = key.substring(0, primaryKeyIndex + 1);
                    if (fieldName.startsWith(LocalizationKeyPrefixes.FIELD_LABEL_KEY_PREFIX)
                            || fieldName.startsWith(LocalizationKeyPrefixes.FIELD_TOOLTIP_KEY_PREFIX)) {
                        //do not have . at the end (legacy)
                        fieldName = fieldName.substring(0, fieldName.length() - 1);
                    }
                }
            } else {
                fieldName = key;
            }
            List<TLocalizedResourcesBean> localizedResources = existingLabels.get(key);
            if (localizedResources != null && localizedResources.size() > 1) {
                //remove all duplicates (as a consequence of previous erroneous imports)
                localizedResourcesDAO.deleteLocalizedResourcesForFieldNameAndKeyAndLocale(fieldName, primaryKey,
                        strLocale);
                localizedResources = null;
            }
            if (localizedResources == null || localizedResources.isEmpty()) {
                //new resource
                TLocalizedResourcesBean localizedResourcesBean = new TLocalizedResourcesBean();
                localizedResourcesBean.setFieldName(fieldName);
                localizedResourcesBean.setPrimaryKeyValue(primaryKey);
                localizedResourcesBean.setLocalizedText(localizedText);
                localizedResourcesBean.setLocale(strLocale);
                localizedResourcesDAO.insert(localizedResourcesBean);
            } else {
                //existing resource
                if (localizedResources.size() == 1) {
                    TLocalizedResourcesBean localizedResourcesBean = localizedResources.get(0);
                    if (EqualUtils.notEqual(localizedText, localizedResourcesBean
                            .getLocalizedText()) /*&& locale.equals(localizedResourcesBean.getLocale())*/) {
                        //text changed locally by the customer
                        boolean textChanged = localizedResourcesBean.getTextChangedBool();
                        if ((textChanged == false && !initBoxResources) || (textChanged && overwrite)) {
                            localizedResourcesBean.setLocalizedText(localizedText);
                            localizedResourcesDAO.save(localizedResourcesBean);
                        }
                    } else {
                    }
                }
            }
        }
        Transaction.commit(connection);
        if (!connection.isClosed()) {
            connection.close();
        }
    } catch (Exception e) {
        LOGGER.error("Problem filling locales: " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        if (connection != null) {
            Transaction.safeRollback(connection);
        }
    }
    //delete the existing ones not found in the properties
    Locale locale;
    if (strLocale != null) {
        locale = LocaleHandler.getLocaleFromString(strLocale);
    } else {
        locale = Locale.getDefault();
    }
    if (withPrimaryKey) {
        //not sure that all is needed but to be sure we do not miss imported localizations
        LookupContainer.resetLocalizedLookupMap(SystemFields.INTEGER_ISSUETYPE, locale);
        LookupContainer.resetLocalizedLookupMap(SystemFields.INTEGER_STATE, locale);
        LookupContainer.resetLocalizedLookupMap(SystemFields.INTEGER_PRIORITY, locale);
        LookupContainer.resetLocalizedLookupMap(SystemFields.INTEGER_SEVERITY, locale);
    }
    ResourceBundle.clearCache();
}

From source file:com.mirth.connect.server.controllers.tests.TestUtils.java

public static Connection getConnection() throws Exception {
    Properties configuration = Donkey.getInstance().getConfiguration().getDonkeyProperties();
    String driver = configuration.getProperty("database.driver");

    if (driver != null) {
        Class.forName(driver);//from   ww  w  . ja  v a2s  . co m
    }

    Connection connection = DriverManager.getConnection(configuration.getProperty("database.url"),
            configuration.getProperty("database.username"), configuration.getProperty("database.password"));
    connection.setAutoCommit(false);
    return connection;
}

From source file:net.bull.javamelody.internal.model.JavaInformations.java

private static String buildDataBaseVersion() {
    if (Parameters.isNoDatabase()) {
        return null;
    }//from  w  w w  .  j  av  a  2s . c  om
    final StringBuilder result = new StringBuilder();
    try {
        // on commence par voir si le driver jdbc a t utilis
        // car s'il n'y a pas de datasource une exception est dclenche
        if (Parameters.getLastConnectUrl() != null) {
            final Connection connection = DriverManager.getConnection(Parameters.getLastConnectUrl(),
                    Parameters.getLastConnectInfo());
            connection.setAutoCommit(false);
            try {
                appendDataBaseVersion(result, connection);
            } finally {
                // rollback inutile ici car on ne fait que lire les meta-data (+ cf issue 38)
                connection.close();
            }
        }

        // on cherche une datasource avec InitialContext pour afficher nom et version bdd + nom et version driver jdbc
        // (le nom de la dataSource recherche dans JNDI est du genre jdbc/Xxx qui est le nom standard d'une DataSource)
        final Map<String, DataSource> dataSources = JdbcWrapper.getJndiAndSpringDataSources();
        for (final Map.Entry<String, DataSource> entry : dataSources.entrySet()) {
            final String name = entry.getKey();
            final DataSource dataSource = entry.getValue();
            final Connection connection = dataSource.getConnection();
            // on ne doit pas changer autoCommit pour la connection d'une DataSource
            // (ou alors il faudrait remettre l'autoCommit aprs, issue 233)
            // connection.setAutoCommit(false);
            try {
                if (result.length() > 0) {
                    result.append("\n\n");
                }
                result.append(name).append(":\n");
                appendDataBaseVersion(result, connection);
            } finally {
                // rollback inutile ici car on ne fait que lire les meta-data (+ cf issue 38)
                connection.close();
            }
        }
    } catch (final Exception e) {
        result.append(e.toString());
    }
    if (result.length() > 0) {
        return result.toString();
    }
    return null;
}

From source file:de.sqlcoach.db.jdbc.DBConnection.java

/**
 * Gets the pool connection./*from   www .j  a v  a 2s  .c om*/
 * 
 * @return the pool connection
 * 
 * @throws NamingException
 *           the naming exception
 * @throws SQLException
 *           the SQL exception
 */
protected static DBConnection getPoolConnection(String dataSourceName) throws NamingException, SQLException {
    final Context initCtx = new InitialContext();
    final Context envCtx = (Context) initCtx.lookup("java:comp/env");

    final String name = "jdbc/" + dataSourceName;

    DBConnection dbconn = null;

    Integer connectionCnt = DBConnection.connectionCounter.get(dataSourceName);
    if (connectionCnt == null)
        connectionCnt = 0;

    if (log.isInfoEnabled()) {
        log.info("getPoolConnection ENTER [dataSource=" + dataSourceName + " connectionCnt=" + connectionCnt
                + "]");
    }

    // final DataSource ds = (DataSource)envCtx.lookup(name);
    // if (ds == null) {
    // log.error ("getPoolConnection : No DataSource for "+ name+ " !");
    // return null;
    // } else {
    // if (log.isDebugEnabled())
    // log.debug("getPoolConnection : DataSource: "+ds.toString());
    // }

    // final Connection cn = ds.getConnection();
    final Connection cn = getSimpleConnection(dataSourceName);
    if (cn == null) { // Failed !
        log.error("getPoolConnection : No Connection for " + name + " ! (connectionCnt:" + connectionCnt + ")");
        return null;
    } else { // Success
        DBConnection.connectionCounter.put(dataSourceName, connectionCnt++);
        dbconn = new DBConnection(cn, connectionCnt, dataSourceName);
        if (log.isDebugEnabled())
            log.debug("getPoolConnection : Connection: " + cn.toString());
    }

    cn.setAutoCommit(false);

    // Set Oracle date format to YYYY-MM-DD
    // final java.sql.DatabaseMetaData dm = cn.getMetaData();
    // final String prodname = dm.getDatabaseProductName();
    // if (prodname.equalsIgnoreCase("Oracle")) { // Only for Oracle !!
    // try (Statement s = cn.createStatement()) {
    // s.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
    // if (log.isDebugEnabled())
    // log.debug("getPoolConnection : ProductName=" + prodname + "\nALTER
    // SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
    // } catch (SQLException e) {
    // log.warn("getPoolConnection : ProductName="+prodname+"\nALTER SESSION SET
    // NLS_DATE_FORMAT = 'YYYY-MM-DD': ", e);
    // }
    // } else {
    // if (log.isDebugEnabled())
    // log.debug("getPoolConnection : Kein Oracle cn= "+cn+ "
    // ProductName="+prodname);
    // }

    if (log.isInfoEnabled())
        log.info("getPoolConnection LEAVE dbconn=" + dbconn);

    return dbconn;
}

From source file:com.concursive.connect.web.modules.login.utils.UserUtils.java

/**
 * Creates a user's profile and sets the id on the user object
 *
 * @param db/*from   w  w w.j  a va  2s .c  o m*/
 * @param user
 * @param prefs
 * @throws SQLException
 */
public static void addUserProfile(Connection db, User user, ApplicationPrefs prefs) throws SQLException {
    boolean autoCommit = db.getAutoCommit();
    try {
        if (autoCommit) {
            db.setAutoCommit(false);
        }
        // Determine the project features
        ProjectFeatures features = new ProjectFeatures();
        ArrayList<String> modules = new ArrayList<String>();
        modules.add("Profile");
        String enabledModules = prefs.get(ApplicationPrefs.DEFAULT_USER_PROFILE_TABS);
        //      if (enabledModules == null || enabledModules.contains("Reviews")) {
        //       modules.add("Reviews");
        //      }
        if (enabledModules == null || enabledModules.contains("Blog")) {
            modules.add("News=My Blog");
        }
        if (enabledModules == null || enabledModules.contains("Wiki")) {
            modules.add("Wiki=About Me");
        }
        if (enabledModules == null || enabledModules.contains("Classifieds")) {
            modules.add("My Classifieds");
        }
        if (enabledModules == null || enabledModules.contains("Documents")) {
            modules.add("Documents=My Documents");
        }
        if (enabledModules == null || enabledModules.contains("Lists")) {
            modules.add("My Lists");
        }
        if (enabledModules == null || enabledModules.contains("Badges")) {
            modules.add("My Badges");
        }
        if (enabledModules == null || enabledModules.contains("Friends")) {
            modules.add("Team=Friends");
        }
        if (enabledModules == null || enabledModules.contains("Messages")) {
            modules.add("Messages");
        }
        int count = 0;
        for (String modulePreference : modules) {
            String moduleName = null;
            String moduleLabel = null;
            if (modulePreference.indexOf("=") != -1) {
                moduleName = modulePreference.split("=")[0];
                moduleLabel = modulePreference.split("=")[1];
            } else {
                moduleName = modulePreference;
                moduleLabel = modulePreference;
            }
            ObjectUtils.setParam(features, "order" + moduleName, count + 1);
            ObjectUtils.setParam(features, "label" + moduleName, moduleLabel);
            ObjectUtils.setParam(features, "show" + moduleName, true);
        }
        // Determine the category id
        ProjectCategoryList projectCategoryList = new ProjectCategoryList();
        projectCategoryList.setCategoryDescription("People");
        projectCategoryList.buildList(db);
        ProjectCategory people = projectCategoryList.getFromValue("People");
        // Create a user project profile
        Project project = new Project();
        project.setInstanceId(user.getInstanceId());
        project.setGroupId(1);
        project.setApproved(user.getEnabled());
        project.setProfile(true);
        project.setCategoryId(people.getId());
        project.setOwner(user.getId());
        project.setEnteredBy(user.getId());
        project.setModifiedBy(user.getId());
        // Determine how to record the user's name in the profile
        if ("true".equals(prefs.get(ApplicationPrefs.USERS_ARE_ANONYMOUS))) {
            project.setTitle(user.getNameFirstLastInitial());
        } else {
            project.setTitle(user.getNameFirstLast());
        }
        project.setKeywords(user.getNameFirstLast());
        project.setShortDescription("My Profile");
        project.setCity(user.getCity());
        project.setState(user.getState());
        project.setCountry(user.getCountry());
        project.setPostalCode(user.getPostalCode());
        project.setFeatures(features);
        // Access rules will allow this profile to be searched and seen
        project.getFeatures().setUpdateAllowGuests(true);
        project.getFeatures().setAllowGuests(true);
        if ("true".equals(prefs.get(ApplicationPrefs.INFORMATION_IS_SENSITIVE))) {
            project.getFeatures().setAllowGuests(false);
        }
        // A join request can be made which requires approval by the profile owner
        project.getFeatures().setUpdateAllowParticipants(true);
        project.getFeatures().setAllowParticipants(true);
        // Anyone can see the profile page
        project.getFeatures().setUpdateMembershipRequired(true);
        project.getFeatures().setMembershipRequired(true);
        project.insert(db);
        project.getFeatures().setId(project.getId());
        project.getFeatures().update(db);
        updateProfileProjectId(db, user, project);
        // Determine which role level the user is for their own profile
        LookupList roleList = CacheUtils.getLookupList("lookup_project_role");
        int defaultUserLevel = roleList.getIdFromLevel(TeamMember.MANAGER);
        if (!user.getAccessAdmin() && prefs.has(ApplicationPrefs.DEFAULT_USER_PROFILE_ROLE)) {
            int userLevelPreference = roleList
                    .getIdFromValue(prefs.get(ApplicationPrefs.DEFAULT_USER_PROFILE_ROLE));
            if (userLevelPreference > -1) {
                defaultUserLevel = userLevelPreference;
            }
        }
        // Add the user as a member of the profile
        TeamMember member = new TeamMember();
        member.setUserId(user.getId());
        member.setProjectId(project.getId());
        member.setUserLevel(defaultUserLevel);
        member.setStatus(TeamMember.STATUS_ADDED);
        member.setNotification(true);
        member.setEnteredBy(user.getId());
        member.setModifiedBy(user.getId());
        member.insert(db);
        if (autoCommit) {
            db.commit();
        }
        // Success, now that the database is committed, invalidate the cache
        CacheUtils.invalidateValue(Constants.SYSTEM_USER_CACHE, user.getId());
        CacheUtils.invalidateValue(Constants.SYSTEM_PROJECT_CACHE, project.getId());
    } catch (Exception e) {
        LOG.error("addUserProfile", e);
        if (autoCommit) {
            db.rollback();
        }
        throw new SQLException(e.getMessage());
    } finally {
        if (autoCommit) {
            db.setAutoCommit(true);
        }
    }
}

From source file:HSqlPrimerDesign.java

public static void checker(Connection connection, int bps) throws ClassNotFoundException, SQLException,
        InstantiationException, IllegalAccessException, IOException {
    String base = new File("").getAbsolutePath();
    Connection db = connection;
    db.setAutoCommit(false);
    Statement stat = db.createStatement();
    PrintWriter log = new PrintWriter(new File("checkertest.log"));
    ImportPhagelist.getInstance().parseAllPhagePrimers(bps);
    stat.execute("SET FILES LOG FALSE;\n");
    ResultSet call = stat.executeQuery("Select * From Primerdb.Phages;");
    List<String[]> phages = new ArrayList<>();
    String strain = "";
    while (call.next()) {
        String[] r = new String[3];
        r[0] = call.getString("Strain");
        r[1] = call.getString("Cluster");
        r[2] = call.getString("Name");
        phages.add(r);// ww w  . ja  v a  2 s .co m
        if (r[2].equals("xkcd")) {
            strain = r[0];
        }
    }
    String x = strain;
    phages.stream().filter(y -> y[0].equals(x)).map(y -> y[1]).collect(Collectors.toSet()).forEach(z -> {
        System.out.println("Starting:" + z);
        try {
            List<String> primers = new ArrayList<String>();
            Set<String> clustphages = phages.stream().filter(a -> a[0].equals(x) && a[1].equals(z))
                    .map(a -> a[2]).collect(Collectors.toSet());

            ResultSet resultSet = stat.executeQuery("Select * from primerdb.primers" + " where Strain ='" + x
                    + "' and Cluster ='" + z + "' and UniqueP = true" + " and Bp = " + Integer.valueOf(bps)
                    + " and Hairpin = false");
            while (resultSet.next()) {
                primers.add(resultSet.getString("Sequence"));
            }
            if (primers.size() > 0) {
                for (int i = 0; i < 4; i++) {
                    String primer = primers.get(i);
                    for (String clustphage : clustphages) {
                        if (!CSV.readCSV(base + "/PhageData/" + Integer.toString(bps) + clustphage + ".csv")
                                .contains(primer))
                            log.println("Problem " + z);
                    }
                }
                Set<String> nonclustphages = phages.stream().filter(a -> a[0].equals(x) && !a[1].equals(z))
                        .map(a -> a[2]).collect(Collectors.toSet());
                log.println("Cluster phages done");
                for (int i = 0; i < 4; i++) {
                    String primer = primers.get(i);
                    for (String nonclustphage : nonclustphages) {
                        if (CSV.readCSV(base + "/PhageData/" + Integer.toString(bps) + nonclustphage + ".csv")
                                .contains(primer))
                            log.println("Problem " + z);
                    }
                }
                log.println("NonCluster phages done");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("Error occurred at " + x + " " + z);
        }
        log.println(z);
        log.flush();
        System.gc();
    });
    stat.execute("SET FILES LOG TRUE\n");
    stat.close();
    System.out.println("Primers Matched");
}

From source file:com.ibm.research.rdf.store.runtime.service.sql.StoreHelper.java

public static boolean setupAutoCommit(Connection conn) {
    try {/*from  w ww.  ja  v a 2 s  . c o m*/
        if (conn.getAutoCommit()) {
            conn.setAutoCommit(false);
            return true;
        }
    } catch (SQLException e) {
    }

    return false;
}