Java Code Examples for java.sql.SQLException#getLocalizedMessage()

The following examples show how to use java.sql.SQLException#getLocalizedMessage() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: freeacs   File: AbstractWebPage.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public TemplateModel exec(List args) throws TemplateModelException {
  if (args.size() < 2) {
    throw new TemplateModelException("Wrong number of arguments");
  }
  String id = (String) args.get(0);
  String name = (String) args.get(1);
  Unit unit = units.get(id);
  if (unit == null) {
    try {
      unit = acsUnit.getUnitById(id);
      units.put(id, unit);
    } catch (SQLException e) {
      throw new TemplateModelException("Error: " + e.getLocalizedMessage());
    }
  }
  String up = unit.getParameters().get(name);
  if (up != null && up.trim().isEmpty() && unit.getUnitParameters().get(name) != null) {
    return new SimpleScalar(
        "<span class=\"requiresTitlePopup\" title=\"The unit has overridden the profile value with a blank string\">[blank&nbsp;unit&nbsp;parameter]</span>");
  }
  return new SimpleScalar(up);
}
 
Example 2
Source Project: netbeans   File: QueryBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private void reportDatabaseError(SQLException e) {

        Log.getLogger().log(Level.FINE, null, e);
        
        String msg = isUnsupportedFeature(e)
	    ? NbBundle.getMessage(QueryBuilder.class, "UNSUPPORTED_FEATURE")
	    : e.getLocalizedMessage();
        
        reportProcessingError(msg);

        /*
        ConnectionStatusPanel csp = new ConnectionStatusPanel() ;
        csp.configureDisplay(sqlStatement.getConnectionInfo(), false, e.getLocalizedMessage(),  "", 0, false ) ;
        csp.setGeneralInfo(msg) ;
        csp.displayDialog( sqlStatement.getConnectionInfo() ) ;
        */

    }
 
Example 3
Source Project: quetzal   File: StoreHelper.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static void setPath(Connection conn, String schemaName)
{

if (schemaName != null && schemaName.length() > 0)
   {
   try
      {

      // set even the CURRENT PATH... this is for UDF's
      SQLExecutor.executeUpdate(conn, "set current path = " + schemaName + ",current path");
      }
   catch (SQLExceptionWrapper e)
      {
      SQLException e1 = (SQLException) e.getCause();
      if (e1.getErrorCode() == -585)
         {
         // duplicate schema, no action required
         return;
         }
      throw new RdfStoreException(e1.getLocalizedMessage(), e1);
      }

   }
}
 
Example 4
Source Project: sis   File: MetadataSource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Closes the database connection used by this object.
 *
 * @throws MetadataStoreException if an error occurred while closing the connection.
 */
@Override
public synchronized void close() throws MetadataStoreException {
    try {
        for (int i=0; i < statements.length; i++) {
            final CachedStatement statement = statements[i];
            if (statement != null) {
                statement.close();
                statements[i] = null;
            }
        }
        if (connection != null) {
            connection.close();
            connection = null;
        }
        helper = null;
    } catch (SQLException e) {
        throw new MetadataStoreException(e.getLocalizedMessage(), Exceptions.unwrap(e));
    }
}
 
Example 5
public String checkForUpgrades() {
    Settings customSettings = coreSettings.getAuthSettings();
    try (Connection connection = ConnectionUtils.getConnection("FROST-BasicAuth", customSettings)) {
        return LiquibaseHelper.checkForUpgrades(connection, LIQUIBASE_CHANGELOG_FILENAME);
    } catch (SQLException ex) {
        LOGGER.error("Could not initialise database.", ex);
        return "Failed to initialise database:\n"
                + ex.getLocalizedMessage()
                + "\n";
    }
}
 
Example 6
@Override
public String checkForUpgrades() {
    try {
        Settings customSettings = settings.getPersistenceSettings().getCustomSettings();
        Connection connection = ConnectionUtils.getConnection("FROST-Source", customSettings);
        String liquibaseChangelogFilename = getLiquibaseChangelogFilename();
        return LiquibaseHelper.checkForUpgrades(connection, liquibaseChangelogFilename);
    } catch (SQLException ex) {
        LOGGER.error("Could not initialise database.", ex);
        return "Failed to initialise database:\n"
                + ex.getLocalizedMessage()
                + "\n";
    }
}
 
Example 7
Source Project: BART   File: BartDBMSUtility.java    License: MIT License 5 votes vote down vote up
public static List<String> loadTableNames(AccessConfiguration accessConfiguration) {
    List<String> tableNames = new ArrayList<String>();
    String schemaName = accessConfiguration.getSchemaName();
    ResultSet tableResultSet = null;
    Connection connection = null;
    try {
        if (logger.isDebugEnabled()) logger.debug("Loading table names: " + accessConfiguration);
        connection = QueryManager.getConnection(accessConfiguration);
        String catalog = connection.getCatalog();
        if (catalog == null) {
            catalog = accessConfiguration.getUri();
            if (logger.isDebugEnabled()) logger.debug("Catalog is null. Catalog name will be: " + catalog);
        }
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        tableResultSet = databaseMetaData.getTables(catalog, schemaName, null, new String[]{"TABLE"});
        while (tableResultSet.next()) {
            String tableName = tableResultSet.getString("TABLE_NAME");
            tableNames.add(tableName);
        }
    } catch (DAOException daoe) {
        throw new DBMSException("Error connecting to database.\n" + accessConfiguration + "\n" + daoe.getLocalizedMessage());
    } catch (SQLException sqle) {
        throw new DBMSException("Error connecting to database.\n" + accessConfiguration + "\n" + sqle.getLocalizedMessage());
    } finally {
        QueryManager.closeResultSet(tableResultSet);
        QueryManager.closeConnection(connection);
    }
    return tableNames;
}
 
Example 8
Source Project: BART   File: BartDBMSUtility.java    License: MIT License 5 votes vote down vote up
public static List<Key> loadKeys(AccessConfiguration accessConfiguration) {
    List<Key> result = new ArrayList<Key>();
    String schemaName = accessConfiguration.getSchemaName();
    Connection connection = null;
    ResultSet tableResultSet = null;
    try {
        if (logger.isDebugEnabled()) logger.debug("Loading keys: " + accessConfiguration);
        connection = QueryManager.getConnection(accessConfiguration);
        String catalog = connection.getCatalog();
        if (catalog == null) {
            catalog = accessConfiguration.getUri();
            if (logger.isDebugEnabled()) logger.debug("Catalog is null. Catalog name will be: " + catalog);
        }
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        tableResultSet = databaseMetaData.getTables(catalog, schemaName, null, new String[]{"TABLE"});
        while (tableResultSet.next()) {
            String tableName = tableResultSet.getString("TABLE_NAME");
            if (logger.isDebugEnabled()) logger.debug("Searching primary keys. ANALYZING TABLE  = " + tableName);
            ResultSet resultSet = databaseMetaData.getPrimaryKeys(catalog, null, tableName);
            while (resultSet.next()) {
                String columnName = resultSet.getString("COLUMN_NAME");
                if (logger.isDebugEnabled()) logger.debug("Analyzing primary key: " + columnName);
                if (logger.isDebugEnabled()) logger.debug("Found a Primary Key: " + columnName);
                Key key = new Key(new AttributeRef(tableName, columnName), true);
                result.add(key);
            }
        }
    } catch (DAOException daoe) {
        throw new DBMSException("Error connecting to database.\n" + accessConfiguration + "\n" + daoe.getLocalizedMessage());
    } catch (SQLException sqle) {
        throw new DBMSException("Error connecting to database.\n" + accessConfiguration + "\n" + sqle.getLocalizedMessage());
    } finally {
        QueryManager.closeResultSet(tableResultSet);
        QueryManager.closeConnection(connection);
    }
    return result;
}
 
Example 9
Source Project: kylin   File: QueryController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/tables_and_columns", method = RequestMethod.GET, produces = { "application/json" })
@ResponseBody
public List<TableMeta> getMetadata(MetaRequest metaRequest) throws IOException {
    try {
        return queryService.getMetadataFilterByUser(metaRequest.getProject());
    } catch (SQLException e) {
        throw new InternalErrorException(e.getLocalizedMessage(), e);
    }
}
 
Example 10
Source Project: Kylin   File: QueryController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/tables_and_columns", method = RequestMethod.GET)
@ResponseBody
public List<TableMeta> getMetadata(MetaRequest metaRequest) {
    try {
        return queryService.getMetadata(metaRequest.getProject());
    } catch (SQLException e) {
        logger.error(e.getLocalizedMessage(), e);
        throw new InternalErrorException(e.getLocalizedMessage(), e);
    }
}
 
Example 11
Source Project: quetzal   File: SQLExecutor.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static PreparedStatement prepare(Connection conn, String sql) {
	try {
		return conn.prepareStatement(sql);
	} catch (SQLException e) {
		throw new RdfStoreException(e.getLocalizedMessage(), e);
	}

}
 
Example 12
public void abort() {
	try {
		conn.rollback();
	} catch (SQLException e) {
		log.error("Cannot abort transaction", e);
		throw new RdfStoreException(e.getLocalizedMessage(), e);
	}
}
 
Example 13
public void begin() {
	try {
		conn.setAutoCommit(false);
	} catch (SQLException e) {
		log.error("Cannot begin transaction", e);
		throw new RdfStoreException(e.getLocalizedMessage(), e);
	}
}
 
Example 14
public void commit() {
	try {
		conn.commit();
	} catch (SQLException e) {
		log.error("Cannot commit transaction", e);
		throw new RdfStoreException(e.getLocalizedMessage(), e);
	}
}
 
Example 15
Source Project: quetzal   File: DB2Dataset.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public void commit()
{
try
   {
   connection.commit();
   }
catch (SQLException e)
   {
   throw new RdfStoreException(e.getLocalizedMessage(), e);
   }
}
 
Example 16
Source Project: freeacs   File: UnittypeParametersPage.java    License: MIT License 4 votes vote down vote up
private void saveParameter(ParameterParser params, Unittype unittype, ACS acs) {
  String name = params.getParameter("name::1");
  String old_name = params.getParameter("param.name");
  String flag = params.getParameter("flag::1");

  if (isValidString(name) && isValidString(flag)) {
    try {
      utParam = unittype.getUnittypeParameters().getByName(name);
      if (utParam != null) {
        utParam.getFlag().setFlag(flag);
      } else if ((utParam = unittype.getUnittypeParameters().getByName(old_name)) != null) {
        utParam.setName(name.replaceAll(" ", "_"));
        utParam.getFlag().setFlag(flag);
      } else {
        UnittypeParameterFlag utpFlag = new UnittypeParameterFlag(flag);
        utParam = new UnittypeParameter(unittype, name.replaceAll(" ", "_"), utpFlag);
      }

      if (!utParam.getFlag().isReadOnly()) {
        UnittypeParameterValues utpVals = utParam.getValues();
        if (utpVals == null) {
          utParam.setValues(new UnittypeParameterValues());
        }
        List<String> values = new ArrayList<>();
        String[] tmp = params.getStringParameterArray("value::1::field");
        if (tmp != null) {
          for (String s : tmp) {
            String trimmed = s.trim();
            if (!trimmed.isEmpty()) {
              values.add(trimmed);
            }
          }
        }
        utParam.getValues().setValues(values);
      } else if (utParam.getValues() != null) {
        utParam.getValues().setValues(new ArrayList<String>());
      }

      unittype.getUnittypeParameters().addOrChangeUnittypeParameter(utParam, acs);

      utpAdded = true;
    } catch (SQLException e) {
      error += "Failed to add parameter " + name + ": " + e.getLocalizedMessage();
    } catch (Exception ex) {
      error += ex.getLocalizedMessage() + StackTraceFormatter.getStackTraceAsHTML(ex);
    }
  }
}
 
Example 17
Source Project: BART   File: BartDBMSUtility.java    License: MIT License 4 votes vote down vote up
public static List<ForeignKey> loadForeignKeys(AccessConfiguration accessConfiguration) {
    Map<String, ForeignKey> foreignKeyMap = new HashMap<String, ForeignKey>();
    String schemaName = accessConfiguration.getSchemaName();
    Connection connection = null;
    ResultSet tableResultSet = null;
    try {
        if (logger.isDebugEnabled()) logger.debug("Loading foreign keys: " + accessConfiguration);
        connection = QueryManager.getConnection(accessConfiguration);
        String catalog = connection.getCatalog();
        if (catalog == null) {
            catalog = accessConfiguration.getUri();
            if (logger.isDebugEnabled()) logger.debug("Catalog is null. Catalog name will be: " + catalog);
        }
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        tableResultSet = databaseMetaData.getTables(catalog, schemaName, null, new String[]{"TABLE"});
        while (tableResultSet.next()) {
            String tableName = tableResultSet.getString("TABLE_NAME");
            if (logger.isDebugEnabled()) logger.debug("Searching foreign keys. ANALYZING TABLE  = " + tableName);
            ResultSet resultSet = databaseMetaData.getImportedKeys(catalog, null, tableName);
            while (resultSet.next()) {
                String fkeyName = resultSet.getString("FK_NAME");
                String pkTableName = resultSet.getString("PKTABLE_NAME");
                String pkColumnName = resultSet.getString("PKCOLUMN_NAME");
                String keyPrimaryKey = pkTableName + "." + pkColumnName;
                String fkTableName = resultSet.getString("FKTABLE_NAME");
                String fkColumnName = resultSet.getString("FKCOLUMN_NAME");
                String keyForeignKey = fkTableName + "." + fkColumnName;
                if (logger.isDebugEnabled()) logger.debug("Analyzing Primary Key: " + keyPrimaryKey + " Found a Foreign Key: " + fkColumnName + " in table " + fkTableName);
                if (logger.isDebugEnabled()) logger.debug("Analyzing foreign key: " + keyForeignKey + " references " + keyPrimaryKey);
                addFKToMap(foreignKeyMap, fkeyName, new AttributeRef(pkTableName, pkColumnName), new AttributeRef(fkTableName, fkColumnName));
            }
        }
    } catch (DAOException daoe) {
        throw new DBMSException("Error connecting to database.\n" + accessConfiguration + "\n" + daoe.getLocalizedMessage());
    } catch (SQLException sqle) {
        throw new DBMSException("Error connecting to database.\n" + accessConfiguration + "\n" + sqle.getLocalizedMessage());
    } finally {
        QueryManager.closeResultSet(tableResultSet);
        QueryManager.closeConnection(connection);
    }
    return new ArrayList<ForeignKey>(foreignKeyMap.values());
}
 
Example 18
/**
   * Get the column value returned by a SELECT statement for a specific entity attribute
   * @param resultSet
   * @param mapping
   * @param entityClass
   * @return
   */
  public Object getColumnValueFromResultSet(ResultSet resultSet, AttributeMapping mapping, Class entityClass)
  {
    // calling getObject on Oracle DB returns correct type, however, on SQLLite is alywas return String
    // so we need to proper get method
    String attrName = mapping.getAttributeName();
    Class javaType = EntityUtils.getJavaType(entityClass, attrName);
    Object value = null;
    try
    {
      if (resultSet.getObject(mapping.getColumnName()) == null)
      {
        return value;
      }
      else if (javaType == String.class)
      {
        value = resultSet.getString(mapping.getColumnName());
      }
      else if (javaType == java.util.Date.class || javaType == java.sql.Date.class)
      {
        // dates are saved to SQLIte as timestamp to not loose time part
        Timestamp ts = resultSet.getTimestamp(mapping.getColumnName());
//        value = resultSet.getDate(mapping.getColumnName());
        // ts can be null when stored using wrong format, should be dd-MM-yyyy hh:mm:ss
        if (ts!=null)
        {
          value = new java.sql.Date(ts.getTime());          
        }
      }
      else if (javaType == Time.class || javaType == Timestamp.class)
      {
        value = resultSet.getTime(mapping.getColumnName());
      }
      else if (javaType == Integer.class)
      {
        value = new Integer(resultSet.getInt(mapping.getColumnName()));
      }
      else if (javaType == Long.class)
      {
        value = new Long(resultSet.getLong(mapping.getColumnName()));
      }
      else if (javaType == Float.class)
      {
        value = new Float(resultSet.getFloat(mapping.getColumnName()));
      }
      else if (javaType == Double.class)
      {
        value = new Float(resultSet.getDouble(mapping.getColumnName()));
      }
      else if (javaType == Double.class)
      {
        value = new Float(resultSet.getDouble(mapping.getColumnName()));
      }
      else if (javaType == Clob.class)
      {
        value = resultSet.getClob(mapping.getColumnName());
      }
      else if (javaType == Blob.class)
      {
        value = resultSet.getBlob(mapping.getColumnName());
      }
      else if (javaType == Short.class)
      {
        value = new Short(resultSet.getShort(mapping.getColumnName()));
      }
      else
      {
        value = resultSet.getObject(mapping.getColumnName());
      }
    }
    catch (SQLException e)
    {
      throw new AdfException("Error getting SQL resultSet value for column " + mapping.getColumnName() + ": " +
                             e.getLocalizedMessage(), AdfException.ERROR);
    }
    return value;
  }
 
Example 19
/**
   * Get the column value returned by a SELECT statement for a specific entity attribute
   * @param resultSet
   * @param mapping
   * @param entityClass
   * @return
   */
  public Object getColumnValueFromResultSet(ResultSet resultSet, AttributeMapping mapping, Class entityClass)
  {
    // calling getObject on Oracle DB returns correct type, however, on SQLLite is alywas return String
    // so we need to proper get method
    String attrName = mapping.getAttributeName();
    Class javaType = EntityUtils.getJavaType(entityClass, attrName);
    Object value = null;
    try
    {
      if (resultSet.getObject(mapping.getColumnName()) == null)
      {
        return value;
      }
      else if (javaType == String.class)
      {
        value = resultSet.getString(mapping.getColumnName());
      }
      else if (javaType == java.util.Date.class || javaType == java.sql.Date.class)
      {
        // dates are saved to SQLIte as timestamp to not loose time part
        Timestamp ts = resultSet.getTimestamp(mapping.getColumnName());
//        value = resultSet.getDate(mapping.getColumnName());
        // ts can be null when stored using wrong format, should be dd-MM-yyyy hh:mm:ss
        if (ts!=null)
        {
          value = new java.sql.Date(ts.getTime());          
        }
      }
      else if (javaType == Time.class || javaType == Timestamp.class)
      {
        value = resultSet.getTime(mapping.getColumnName());
      }
      else if (javaType == Integer.class)
      {
        value = new Integer(resultSet.getInt(mapping.getColumnName()));
      }
      else if (javaType == Long.class)
      {
        value = new Long(resultSet.getLong(mapping.getColumnName()));
      }
      else if (javaType == Float.class)
      {
        value = new Float(resultSet.getFloat(mapping.getColumnName()));
      }
      else if (javaType == Double.class)
      {
        value = new Float(resultSet.getDouble(mapping.getColumnName()));
      }
      else if (javaType == Double.class)
      {
        value = new Float(resultSet.getDouble(mapping.getColumnName()));
      }
      else if (javaType == Clob.class)
      {
        value = resultSet.getClob(mapping.getColumnName());
      }
      else if (javaType == Blob.class)
      {
        value = resultSet.getBlob(mapping.getColumnName());
      }
      else if (javaType == Short.class)
      {
        value = new Short(resultSet.getShort(mapping.getColumnName()));
      }
      else
      {
        value = resultSet.getObject(mapping.getColumnName());
      }
    }
    catch (SQLException e)
    {
      throw new AdfException("Error getting SQL resultSet value for column " + mapping.getColumnName() + ": " +
                             e.getLocalizedMessage(), AdfException.ERROR);
    }
    return value;
  }
 
Example 20
Source Project: sis   File: EPSGDataAccess.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Returns the set of authority codes of the given type.
 * This returned set may keep a connection to the EPSG database,
 * so the set can execute efficiently idioms like the following one:
 *
 * {@preformat java
 *     getAuthorityCodes(type).containsAll(others)
 * }
 *
 * The returned set should not be referenced for a long time, as it may prevent this factory to release
 * JDBC resources. If the set of codes is needed for a long time, their values should be copied in another
 * collection object.
 *
 * <h4>Handling of deprecated objects</h4>
 * The collection returned by this method gives an enumeration of EPSG codes for valid objects only.
 * The EPSG codes of deprecated objects are not included in iterations, computation of {@code Set.size()} value,
 * {@code Set.toString()} result, <i>etc.</i> with one exception:
 * a call to {@code Set.contains(…)} will return {@code true} if the given identifier exists
 * for a deprecated object, even if that identifier does not show up in iterations.
 * In other words, the returned collection behaves as if deprecated codes were included in the set but invisible.
 *
 * @param  type  the spatial reference objects type (may be {@code Object.class}).
 * @return the set of authority codes for spatial reference objects of the given type (may be an empty set).
 * @throws FactoryException if access to the underlying database failed.
 */
@Override
public Set<String> getAuthorityCodes(final Class<? extends IdentifiedObject> type) throws FactoryException {
    try {
        return getCodeMap(type).keySet();
    } catch (SQLException exception) {
        throw new FactoryException(exception.getLocalizedMessage(), exception);
    }
}