Example usage for java.sql SQLException getLocalizedMessage

List of usage examples for java.sql SQLException getLocalizedMessage

Introduction

In this page you can find the example usage for java.sql SQLException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java

/**
 * Method for all tables of a database schema 
 * @param schema/*from  w ww . j a v  a 2 s.c o m*/
 * @return list of tables
 * @return list tables
 * @throws Exception 
 */
public List<Table> tablesByShema(Schema schema) throws Exception {
    Exception error = null;

    List<Table> tablesBySchema = new LinkedList<Table>();

    Connection connection = null;
    PreparedStatement preparedStmnt = null;
    try {
        DataSource dataSource = poolDataSources.get(schemaId);
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        //Se actualiza la vista geometry_columns para hacer la consulta con datos actualizados
        /* try {
        PreparedStatement preparedStmntActualizeGC = null;
            preparedStmntActualizeGC = connection.prepareStatement("SELECT Populate_Geometry_Columns(true)");
            preparedStmntActualizeGC.execute();
         } catch (Exception oops) {
            log.info("No se a podido actualizar la tabla geometry_columns");
         }*/

        //Se seleccionan todas las tablas de la base de datos distinguiendo de las vistas y las tablas propias del sistema.
        preparedStmnt = connection
                .prepareStatement("SELECT * FROM geometry_columns WHERE f_table_name IN (SELECT table_name"
                        + " FROM information_schema.columns"
                        + " WHERE udt_name = 'geometry'  AND table_name IN (SELECT table_name FROM information_schema.tables )) AND f_geometry_column <> 'extent';");//AND srid > 0

        ResultSet rs = preparedStmnt.executeQuery();
        while (rs.next()) {
            Table table = new Table();
            table.setName(rs.getString("f_table_name"));
            table.setCreationDate(new Date());
            table.setGeomField(rs.getString("f_geometry_column"));
            table.setEpsg("EPSG:".concat(rs.getString("srid")));
            table.setModificationDate(null);
            table.setTableXservices(null);
            table.setTasks(null);
            table.setSchema(schema);
            tablesBySchema.add(table);
        }
    } catch (SQLException e) {
        error = e;
    } finally {
        if (preparedStmnt != null) {
            try {
                preparedStmnt.close();
            } catch (SQLException se2) {
                log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage()));
            }
        }
        if (connection != null) {
            try {
                if (error != null) {
                    connection.rollback();
                }
            } catch (SQLException se) {
                log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage()));
            }
            try {
                connection.close();
            } catch (SQLException se) {
                log.warn("Se produjo un error al intentar cerrar la conexin: "
                        .concat(se.getLocalizedMessage()));
            }
        }
    }
    if (error != null) {
        throw error;
    }
    return tablesBySchema;
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java

public int executeFeatureInsertLowLevel(String sql, SimpleFeature feature, List<ColumnVO> columns)
        throws Exception {
    Exception error = null;/*from ww w  .  ja  va 2 s  .co m*/

    int numRowsAffected = 0;

    if (columns.size() > 0) {
        Connection connection = null;
        PreparedStatement preparedStmnt = null;

        try {
            DataSource dataSource = poolDataSources.get(schemaId);
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);
            preparedStmnt = connection.prepareStatement(sql);

            int paramPosition = 1;
            for (ColumnVO column : columns) {
                String dataValue = null;
                Object attribute = feature.getAttribute(column.getFilePosition());
                if (attribute != null) {
                    dataValue = attribute.toString();
                }
                Integer dataType = column.getSqlType();
                if (dataType == Types.OTHER) { // it is a geometry
                    // ((org.postgresql.PGConnection)connection).addDataType(column.getName(),
                    // column.getTypeClass());
                    preparedStmnt.setObject(paramPosition, dataValue);
                } else {
                    if (StringUtils.isEmpty(dataValue)) {
                        preparedStmnt.setNull(paramPosition, dataType);
                    } else {
                        preparedStmnt.setObject(paramPosition, dataValue, dataType);
                    }
                }
                paramPosition++;
            }

            numRowsAffected = preparedStmnt.executeUpdate();

            connection.commit();
        } catch (SQLException e) {
            error = e;
        } finally {
            if (preparedStmnt != null) {
                try {
                    preparedStmnt.close();
                } catch (SQLException se2) {
                    log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage()));
                }
            }
            if (connection != null) {
                try {
                    if (error != null) {
                        connection.rollback();
                    }
                } catch (SQLException se) {
                    log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage()));
                }
                try {
                    connection.close();
                } catch (SQLException se) {
                    log.warn("Se produjo un error al intentar cerrar la conexin: "
                            .concat(se.getLocalizedMessage()));
                }
            }
        }
        if (error != null) {
            throw error;
        }
    }
    return numRowsAffected;
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java

/**
 * This method executes a low level insert with the data values
 * and data types (java.sql.Types) specified in a Map.
 * This is a way to improve the performance of data insertion.
 *
 * @param sql escaped SQL to avoid SQL-I
 * @param line the line to inser/*from  w  w w  .  j  a  v a2 s  . com*/
 * @param columns of the table
 * @return number of affected rows
 * @throws Exception exception thrown
 */
public int executeLineInsertLowLevel(String sql, String[] line, List<ColumnVO> columns) throws Exception {
    Exception error = null;

    int numRowsAffected = 0;

    if (columns.size() > 0) {
        Connection connection = null;
        PreparedStatement preparedStmnt = null;

        try {
            DataSource dataSource = poolDataSources.get(schemaId);
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);
            preparedStmnt = connection.prepareStatement(sql);

            String coordinateX = null;
            String coordinateY = null;
            int paramPosition = 1;
            for (ColumnVO column : columns) {
                Integer filePosition = column.getFilePosition();

                String dataValue;
                Integer dataType = column.getSqlType();

                if (column.isCoordinateX()) {
                    dataValue = line[filePosition];
                    coordinateX = dataValue;
                    preparedStmnt.setObject(paramPosition, dataValue, dataType);
                } else if (column.isCoordinateY()) {
                    dataValue = line[filePosition];
                    coordinateY = dataValue;
                    preparedStmnt.setObject(paramPosition, dataValue, dataType);
                } else if (column.isFromCoordinates()) {
                    int coordXIndex = column.getFileCoordinateXPosition();
                    int coordYIndex = column.getFileCoordinateYPosition();
                    coordinateX = line[coordXIndex];
                    coordinateY = line[coordYIndex];
                    continue;
                } else if (dataType == Types.OTHER) { // it is a geometry
                    // ((org.postgresql.PGConnection)connection).addDataType(column.getName(),
                    // column.getTypeClass());
                    dataValue = line[filePosition];
                    preparedStmnt.setObject(paramPosition, dataValue);
                } else {
                    dataValue = line[filePosition];
                    if (StringUtils.isEmpty(dataValue)) {
                        preparedStmnt.setNull(paramPosition, dataType);
                    } else {
                        preparedStmnt.setObject(paramPosition, dataValue, dataType);
                    }
                }
                paramPosition++;
            }
            if ((coordinateX != null) && (coordinateY != null)) {
                String pointWKT = Utils.getPointWKTFromCoordinates(coordinateX, coordinateY);
                preparedStmnt.setObject(paramPosition, pointWKT);
            }
            numRowsAffected = preparedStmnt.executeUpdate();

            connection.commit();
        } catch (SQLException e) {
            error = e;
        } finally {
            if (preparedStmnt != null) {
                try {
                    preparedStmnt.close();
                } catch (SQLException se2) {
                    log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage()));
                }
            }
            if (connection != null) {
                try {
                    if (error != null) {
                        connection.rollback();
                    }
                } catch (SQLException se) {
                    log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage()));
                }
                try {
                    connection.close();
                } catch (SQLException se) {
                    log.warn("Se produjo un error al intentar cerrar la conexin: "
                            .concat(se.getLocalizedMessage()));
                }
            }
        }
        if (error != null) {
            throw error;
        }
    }
    return numRowsAffected;
}

From source file:net.refractions.udig.catalog.ui.wizard.DataBaseRegistryWizardPage.java

/**
 * This method is called in response to selection of the lookup button and gets the names of the
 * available databases on the DBMS server. Instead of overriding this method it is better to
 * override the getDatabaseResultSet method if a custom way of getting the database names is
 * needed//from   ww  w.  j  ava2 s  .c o  m
 * 
 * @param con the java.sql.Connection returned by getConnection()
 * @return An array of Strings containing the names of only the databases available on the server
 *         which are suitable for display to the user.
 */
protected String[] lookupDbNamesForDisplay(DataSource dataSource) {
    java.util.List<String> dbList = new ArrayList<String>();
    Connection con = null;
    try {
        con = dataSource.getConnection();
        ResultSet rs = null;
        if (con != null) {
            rs = getDatabaseResultSet(con);
            while (rs.next()) {
                String dbName = rs.getString(1);
                if (!excludeDbFromUserChoices(dbName)) {
                    dbList.add(dbName);
                }
            }
        }
        return dbList.toArray(new String[dbList.size()]);
    } catch (SQLException e) {
        setMessage(Messages.DataBaseRegistryWizardPage_databaseMessage);
        setErrorMessage(e.getLocalizedMessage());
        return null;
    } finally {
        if (con != null) {
            try {
                con.close(); // return to pool
            } catch (SQLException e) {
                // closing anyways
            }
        }
    }
}

From source file:net.refractions.udig.catalog.ui.wizard.DataBaseRegistryWizardPage.java

/**
 * This method is called in response to selection of the lookup button and gets the names of the
 * available schemata on the DBMS server. Like lookupDbNameForDisplay it is better to avoid
 * overiding this method if a database specific implementation is needed. Instead overide
 * getSchemaResultSet WARNING: This should never be called if !dbmsUsesSchema().
 * //from w w  w .  jav a2 s  . co m
 * @param con the java.sql.Connection object returned by getConnection()
 * @return An array of Strings containing the names of the schemata available on the server.
 */
protected String[] lookupSchemaNamesForDisplay(DataSource dataSource) {
    if (dataSource == null) {
        return null; // not connected
    }
    Connection con = null;
    java.util.List<String> schemaList = new ArrayList<String>();
    try {
        con = dataSource.getConnection();
        ResultSet rs = null;
        if (con != null) {
            rs = getSchemasResultSet(con);
            while (rs.next()) {
                String schemaName = rs.getString(1);
                if (!excludeSchemaFromUserChoices(schemaName)) {
                    schemaList.add(schemaName);
                }
            }
        }
        return schemaList.toArray(new String[schemaList.size()]);
    } catch (SQLException e) {
        setMessage(Messages.DataBaseRegistryWizardPage_schemaMessage);
        setErrorMessage(e.getLocalizedMessage());
        return null;
    } finally {
        if (con != null) {
            try {
                con.close(); // return to pool
            } catch (SQLException e) {
                // we are closing anyways - ignore
            }
        }
    }
}

From source file:com.splicemachine.derby.impl.load.HdfsImportIT.java

/**
 * Tests an import scenario where a quoted column is missing the end quote and the EOF is
 * reached before the maximum number of lines in a quoted column is exceeded.
 *
 * @throws Exception//  w  ww.ja va 2s.  c  o m
 */
@Test
public void testMissingEndQuoteForQuotedColumnEOF() throws Exception {
    String badDirPath = BADDIR.getCanonicalPath();
    String csvPath = getResourceDirectory() + "import/missing-end-quote/employees.csv";
    try {
        testMissingEndQuoteForQuotedColumn(spliceSchemaWatcher.schemaName, TABLE_18, csvPath, "NAME,TITLE,AGE",
                badDirPath, 0, 1, "false");
        fail("Expected to many bad records.");
    } catch (SQLException e) {
        assertEquals("Expected too many bad records but got: " + e.getLocalizedMessage(), "SE009",
                e.getSQLState());
        SpliceUnitTest.assertBadFileContainsError(new File(badDirPath), "employees.csv", null,
                "unexpected end of file while reading quoted column beginning on line 2 and ending on line 6");
    }
}

From source file:com.splicemachine.derby.impl.load.HdfsImportIT.java

/**
 * Tests an import scenario where a quoted column is missing the end quote and the
 * maximum number of lines in a quoted column is exceeded.
 *
 * @throws Exception//from   w  ww .  j  a  v a2 s  .  com
 */
@Test
public void testMissingEndQuoteForQuotedColumnMax() throws Exception {
    String badDirPath = BADDIR.getCanonicalPath();
    String csvPath = getResourceDirectory() + "import/missing-end-quote/employeesMaxQuotedColumnLines.csv";
    try {
        testMissingEndQuoteForQuotedColumn(spliceSchemaWatcher.schemaName, TABLE_18, csvPath, "NAME,TITLE,AGE",
                badDirPath, 0, 199999, "false");
        fail("Expected to many bad records.");
    } catch (SQLException e) {
        assertEquals("Expected too many bad records but got: " + e.getLocalizedMessage(), "SE009",
                e.getSQLState());
        SpliceUnitTest.assertBadFileContainsError(new File(badDirPath), "employeesMaxQuotedColumnLines.csv",
                null, "Quoted column beginning on line 3 has exceed the maximum allowed lines");
    }
}

From source file:com.splicemachine.derby.impl.load.HdfsImportIT.java

@Test
public void testFailedImportNullBadDir() throws Exception {
    // DB-5017: When bad record dir is null or empty, the input file dir becomes the bad record dir
    String inputFileName = "constraintViolation.csv";
    String inputFileOrigin = getResourceDirectory() + inputFileName;
    // copy the given input file under a temp folder so that it will get cleaned up
    // this used to go under the "target/test-classes" folder but doesn't work when we execute test from
    // a different location.
    File newImportFile = tempFolder.newFile(inputFileName);
    FileUtils.copyFile(new File(inputFileOrigin), newImportFile);
    assertTrue("Import file copy failed: " + newImportFile.getCanonicalPath(), newImportFile.exists());
    String badFileName = newImportFile.getParent() + "/" + inputFileName + ".bad";

    PreparedStatement ps = methodWatcher.prepareStatement(format("call SYSCS_UTIL.IMPORT_DATA(" + "'%s'," + // schema name
            "'%s'," + // table name
            "null," + // insert column list
            "'%s'," + // file path
            "','," + // column delimiter
            "null," + // character delimiter
            "null," + // timestamp format
            "null," + // date format
            "null," + // time format
            "%d," + // max bad records
            "null," + // bad record dir
            "null," + // has one line records
            "null)", // char set
            spliceSchemaWatcher.schemaName, TABLE_20, newImportFile.getCanonicalPath(), 0));
    try {/*from  w w  w  .j  a  v  a 2s.c o  m*/
        ps.execute();
        fail("Too many bad records.");
    } catch (SQLException e) {
        assertEquals("Expected too many bad records, but got: " + e.getLocalizedMessage(), "SE009",
                e.getSQLState());
    }
    boolean exists = existsBadFile(new File(newImportFile.getParent()), inputFileName + ".bad");
    assertTrue("Bad file " + badFileName + " does not exist.", exists);
}

From source file:edu.fullerton.ldvw.LdvDispatcher.java

/**
 * Process the plot request, generating as many images as necessary
 * @return true if output is to be sent by our caller, false if we already sent another mime type
 * @throws WebUtilException //w  ww  . ja va2 s .c o m
 */
private boolean doPlot() throws WebUtilException {
    boolean ret = true;
    String isDownload = request.getParameter("download");

    if (request.getParameter("selMore") != null) {
        if (request.getParameter("baseSelector") != null) {
            try {
                baseChan();
            } catch (SQLException ex) {
                throw new WebUtilException("Attempting to select more base channels", ex);
            } catch (LdvTableException ex) {
                Logger.getLogger(LdvDispatcher.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            ChannelSelector clf = new ChannelSelector(request, response, db, vpage, vuser);
            clf.setContextPath(contextPath);
            clf.setServletPath(servletPath);
            clf.selectChannels("selMore", false);
        }
    } else {
        if (isDownload == null) {
            vpage.setTitle("Ligodv-web results");
        } else {
            vpage.setTitle("Data download");
        }
        try {
            PluginManager pmanage = new PluginManager(db, vpage, vuser, paramMap);
            pmanage.setContextPath(contextPath);
            pmanage.setServletPath(servletPath);
            pmanage.setResponse(response);
            ret = pmanage.doPlots();
        } catch (SQLException | WebUtilException ex) {
            String ermsg = "Calling PluginManager to create plots or send other mime: "
                    + ex.getClass().getSimpleName() + " - " + ex.getLocalizedMessage();
            throw new WebUtilException(ermsg);
        }
    }
    return ret;
}

From source file:org.orbisgis.corejdbc.internal.ReadRowSetImpl.java

@Override
public void refreshRow() throws SQLException {
    try (Resource res = resultSetHolder.getResource()) {
        currentRow = null;/* ww  w  . j a  v  a2  s  .  c  om*/
        cache.clear();
        currentBatch = new ArrayList<>(fetchSize + 1);
        currentBatchId = -1;
        if (res.getResultSet().getRow() > 0 && !res.getResultSet().isAfterLast()) {
            res.getResultSet().refreshRow();
        }
    } catch (SQLException ex) {
        LOGGER.warn(ex.getLocalizedMessage(), ex);
    }
}