Showing posts with label java programming. Show all posts
Showing posts with label java programming. Show all posts

Saturday, 4 July 2020

Java Code for java.sql.ResultSet more Examples

Java Code  for java.sql.ResultSet more Examples

The following are top voted examples for showing how to use java.sql.ResultSet. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.

Example 1


public static ArrayList<Privilege> getAssignedUserPrivileges(User u) throws Exception {
    ArrayList<Privilege> al = new ArrayList<>();
    String query = "SELECT system_privileges.prv_id, system_privileges.prv_code, "
            + "system_privileges.prv_name, system_privileges.prv_display_name, system_privileges.prv_parent "
            + "FROM user_privileges "
            + "INNER JOIN system_privileges ON user_privileges.prv_id = system_privileges.prv_id "
            + "WHERE user_privileges.user_id = ?";
    PreparedStatement ps = con.prepareStatement(query);
    ps.setInt(1, u.getUserId());
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
        Privilege sp = new Privilege();
        sp.setPrvId(rs.getInt("prv_id"));
        sp.setPrvCode(rs.getString("prv_code"));
        sp.setPrvName(rs.getString("prv_name"));
        sp.setPrvDisplayName(rs.getString("prv_display_name"));
        sp.setPrvParent(rs.getInt("prv_parent"));
        al.add(sp);
    }
    return al;
}
 

Example 2


public static List<Attribute> createAttributes(ResultSet rs) throws SQLException {
    LinkedList attributes = new LinkedList();
    if(rs == null) {
        throw new IllegalArgumentException("Cannot create attributes: ResultSet must not be null!");
    } else {
        ResultSetMetaData metadata;
        try {
            metadata = rs.getMetaData();
        } catch (NullPointerException var7) {
            throw new RuntimeException("Could not create attribute list: ResultSet object seems closed.");
        }

        int numberOfColumns = metadata.getColumnCount();

        for(int column = 1; column <= numberOfColumns; ++column) {
            String name = metadata.getColumnLabel(column);
            Attribute attribute = AttributeFactory.createAttribute(name, getRapidMinerTypeIndex(metadata.getColumnType(column)));
            attributes.add(attribute);
        }

        return attributes;
    }
}
 

Example 3


@Override
public DataContainer<ResultSet> next(DataContainer<ResultSet> container) {
       LOGGER.debug("next() called on {}", this);
       if (resultSet == null)
        return null;
try {
if (resultSet.next()) {
return container.setData(resultSet);
} else {
IOUtil.close(this);
return null;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
 

Example 4


@SuppressWarnings("synthetic-access")
CallableStatementParamInfo(java.sql.ResultSet paramTypesRs) throws SQLException {
    boolean hadRows = paramTypesRs.last();

    this.nativeSql = CallableStatement.this.originalSql;
    this.catalogInUse = CallableStatement.this.currentCatalog;
    this.isFunctionCall = CallableStatement.this.callingStoredFunction;

    if (hadRows) {
        this.numParameters = paramTypesRs.getRow();

        this.parameterList = new ArrayList<CallableStatementParam>(this.numParameters);
        this.parameterMap = new HashMap<String, CallableStatementParam>(this.numParameters);

        paramTypesRs.beforeFirst();

        addParametersFromDBMD(paramTypesRs);
    } else {
        this.numParameters = 0;
    }

    if (this.isFunctionCall) {
        this.numParameters += 1;
    }
}
 

Example 5


public User registerUser(User user) throws Exception {
    try {            
        connect();
        String sql = String.format("CALL register_user('%s', '%s', '%s');", user.getUserName(), user.getEmail(), user.getPassword());                        
        statement = connection.createStatement();            
        ResultSet resultSet = statement.executeQuery(sql);            
        if(resultSet.first()) {
            user.setId(resultSet.getInt("Id"));
            
        } else {
            user = null;
        }            
        disconnect();
        return user;
    } catch (Exception e) {
        throw new Exception("error occured while saving the user data!");
    }
}
 

Example 6


 
@Test
public void testSelectFirstOrderByNullsLastGetUndocumentedResult() throws SQLException {
  SelectFirstStatement selectOrderByNullsLastStat = selectFirst( field("field2")).from(tableRef("OrderByNullsLastTable")).orderBy(field("field1").desc().nullsLast());

  String sql = convertStatementToSQL(selectOrderByNullsLastStat);

  sqlScriptExecutorProvider.get().executeQuery(sql, new ResultSetProcessor<Void>() {

    @Override
    public Void process(ResultSet resultSet) throws SQLException {
      List<String> expectedResultField2 = Lists.newArrayList("3","4");
      assertTrue(resultSet.next());
      assertTrue(expectedResultField2.contains(resultSet.getString(1)));
      assertFalse(resultSet.next());
      return null;
    };
  });
}
 

Example 7


private void enhanceIntrospectedTable(IntrospectedTable introspectedTable) {
    try {
        FullyQualifiedTable fqt = introspectedTable.getFullyQualifiedTable();

        ResultSet rs = databaseMetaData.getTables(fqt.getIntrospectedCatalog(), fqt.getIntrospectedSchema(),
                fqt.getIntrospectedTableName(), null);
        if (rs.next()) {
            String remarks = rs.getString("REMARKS"); //$NON-NLS-1$
            String tableType = rs.getString("TABLE_TYPE"); //$NON-NLS-1$
            introspectedTable.setRemarks(remarks);
            introspectedTable.setTableType(tableType);
        }
        closeResultSet(rs);
    } catch (SQLException e) {
        warnings.add(getString("Warning.27", e.getMessage())); //$NON-NLS-1$
    }
}
 

Example 8


public List<RolePermission> getUserGrantedAuthority(int userId) {
String sql = "SELECT * FROM role_permission WHERE userId=?";
List<RolePermission> roleperms = jdbcInsert.getJdbcTemplate().query(sql, new Object[]{userId}, new RowMapper<RolePermission>() {

@Override
public RolePermission mapRow(ResultSet rs, int rowNum) throws SQLException {
RolePermission roleperm = new RolePermission();
roleperm.setId(rs.getInt("id"));
roleperm.setRoleId(rs.getInt("roleId"));
roleperm.setPermissionId(rs.getInt("permissionId"));
roleperm.setUserId(rs.getInt("userId"));
return roleperm;
}
});
return roleperms;
}
 

Example 9

t
public void testDataSource() throws SQLException {

assertNotNull(dataSource);

assertTrue(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource);

try (Connection c = dataSource.getConnection()) {
assertNotNull(c);

try (ResultSet rs = c.createStatement().executeQuery("select str from testx where key=1")) {
rs.next();
assertEquals("One", rs.getString(1));
}
}

}
 

Example 10


@Test
public void testExecuteQueryFilter() throws Exception {
cleanInsert(Paths.get("src/test/resources/data/setup", "testExecuteQuery.ltsv"));

List<String> log = TestAppender.getLogbackLogs(() -> {
SqlContext ctx = agent.contextFrom("example/select_product")
.paramList("product_id", new BigDecimal("0"), new BigDecimal("2"))
.param("_userName", "testUserName").param("_funcId", "testFunction").setSqlId("111");
ctx.setResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE);

agent.query(ctx);
});

assertThat(log, is(Files.readAllLines(
Paths.get("src/test/resources/data/expected/AuditLogSqlFilter", "testExecuteQueryFilter.txt"),
StandardCharsets.UTF_8)));
}
 

Example 11


public ResultSet getFromTo(String pfrom_ap,String pto_ap) {
    PreparedStatement pst;
    try {
        String sql = "SELECT * FROM `flight_leg` WHERE `from_aID` = ? AND `to_aID` = ?";
        pst = this.conn.prepareStatement(sql);
        pst.setString(1, pfrom_ap);
        pst.setString(2, pto_ap);
        ResultSet rs;
        rs = pst.executeQuery();
        return rs;
    } catch (SQLException e) {
        System.out.println("Error : while excicuting prepared statement");
        System.out.println(e);
        return null;
    }
}
 

Example 12


private long getNewToolContentId(long newToolId, Connection conn) throws DeployException {
PreparedStatement stmt = null;
ResultSet results = null;
try {
    stmt = conn.prepareStatement("INSERT INTO lams_tool_content (tool_id) VALUES (?)");
    stmt.setLong(1, newToolId);
    stmt.execute();
    stmt = conn.prepareStatement("SELECT LAST_INSERT_ID() FROM lams_tool_content");
    results = stmt.executeQuery();
    if (results.next()) {
return results.getLong("LAST_INSERT_ID()");
    } else {
throw new DeployException("No tool content id found");
    }

} catch (SQLException sqlex) {
    throw new DeployException("Could not get new tool content id", sqlex);
} finally {
    DbUtils.closeQuietly(stmt);
    DbUtils.closeQuietly(results);
}
   }
 

Example 13


private Object executeSingleResultQuery(String query, Map<?, ?> params)
{
return jdbcTemplate.query(query, params, new ResultSetExtractor()
{
@Override
public Object extractData(ResultSet rs) throws SQLException, DataAccessException
{
Object data = null;
if( rs.next() )
{
data = rs.getObject(1);

// Sanity check - ensure only a single result
if( rs.next() )
{
throw new IncorrectResultSizeDataAccessException(1);
}
}
return data;
}
});
}
 

Example 14


@Override
public List<Permission> getPermissions() {
String sql = "SELECT * FROM permission";
List<Permission> perms = jdbcInsert.getJdbcTemplate().query(sql,  new RowMapper<Permission>() {

@Override
public Permission mapRow(ResultSet rs, int rowNum) throws SQLException {
Permission perm = new Permission();
perm.setId(rs.getInt("id"));
perm.setName(rs.getString("name"));
    perm.setDescription(rs.getString("description"));

return perm;
}
});
return perms;
}
 

Example 15


private static void demo3_execute_insert(){
    executeUpdate("delete from enums where id < 7"); //to make the demo re-runnable

    System.out.println();
    try (Connection conn = getDbConnection()) {
        try (Statement st = conn.createStatement()) {
            boolean res = st.execute("insert into enums (id, type, value) values(1,'vehicle','car')");
            if (res) {
                ResultSet rs = st.getResultSet();
                while (rs.next()) {
                    int id = rs.getInt(1); //More efficient than rs.getInt("id")
                    String type = rs.getString(2);
                    String value = rs.getString(3);
                    System.out.println("id = " + id + ", type = " + type + ", value = " + value);
                }
            } else {
                int count = st.getUpdateCount();
                System.out.println("Update count = " + count);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 

Example 16


public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException
{
    if (getCapitializeUsername() && schemaPattern != null) schemaPattern = schemaPattern.toUpperCase();
    String query = (String)properties.get(PROP_PROCEDURES_QUERY);
    if (query != null) {
        if (con != null) {
            PreparedStatement stmt = con.prepareStatement(query);
            stmt.setString(1, catalog);
            stmt.setString(2, schemaPattern);
            stmt.setString(3, procedureNamePattern);
            return stmt.executeQuery();
        } else throw new SQLException(bundle.getString("EXC_NoConnection")); // NOI18N
    }

    if (dmd == null) throw new SQLException(bundle.getString("EXC_NoDBMetadata")); // NOI18N
    return dmd.getProcedures(catalog, schemaPattern, procedureNamePattern);
}
 

Example 17


@Override
protected boolean exceedsThreshold(final HttpServletRequest request) {
    final String query = "SELECT AUD_DATE FROM COM_AUDIT_TRAIL WHERE AUD_CLIENT_IP = ? AND AUD_USER = ? "
            + "AND AUD_ACTION = ? AND APPLIC_CD = ? AND AUD_DATE >= ? ORDER BY AUD_DATE DESC";
    final String userToUse = constructUsername(request, getUsernameParameter());
    final Calendar cutoff = Calendar.getInstance();
    cutoff.add(Calendar.SECOND, -1 * getFailureRangeInSeconds());
    final List<Timestamp> failures = this.jdbcTemplate.query(
            query,
            new Object[] {request.getRemoteAddr(), userToUse, this.authenticationFailureCode, this.applicationCode, cutoff.getTime()},
            new int[] {Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.TIMESTAMP},
            new RowMapper<Timestamp>() {
                @Override
                public Timestamp mapRow(final ResultSet resultSet, final int i) throws SQLException {
                    return resultSet.getTimestamp(1);
                }
            });
    if (failures.size() < 2) {
        return false;
    }
    // Compute rate in submissions/sec between last two authn failures and compare with threshold
    return NUMBER_OF_MILLISECONDS_IN_SECOND / (failures.get(0).getTime() - failures.get(1).getTime()) > getThresholdRate();
}
 

Example 18


public void showNote() {
    try {
        Connection con = DatabaseConnection.getConnection();
        try (PreparedStatement ps = con.prepareStatement("SELECT * FROM notes WHERE `to`=?", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) {
            ps.setString(1, getName());
            try (ResultSet rs = ps.executeQuery()) {
                rs.last();
                int count = rs.getRow();
                rs.first();
                client.getSession().write(CSPacket.showNotes(rs, count));
            }
        }
    } catch (SQLException e) {
        System.err.println("Unable to show note" + e);
    }
}
 

Example 19


public static int saveClassConfig(ClassConfig config, String name) throws Exception {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
conn = getConnection();
stat = conn.createStatement();
String jsonStr = JSON.toJSONString(config);
String sql = String.format("replace into ClassConfig(name,value) values('%s', '%s')", name, jsonStr);
int result = stat.executeUpdate(sql);
return result;
} finally {
if (rs != null)
rs.close();
if (stat != null)
stat.close();
if (conn != null)
conn.close();
}
}
 

Example 20


public static ArrayList<EmpenhoEntrada> retreaveAll() throws SQLException {
    Statement stm
            = Database.createConnection().
                    createStatement();
    String sql = "SELECT * FROM empenhos_entradas";
    ResultSet rs = stm.executeQuery(sql);
    ArrayList<EmpenhoEntrada> eie = new ArrayList<>();
    while (rs.next()) {
        eie.add(new EmpenhoEntrada(
                rs.getInt("id"),
                rs.getInt("empenho"),
                rs.getInt("entrada")));
    }
    rs.next();
    return eie;
}
 

Example 21


public String getString(String id) throws SQLException {
final String sql = "SELECT CONTENT_ FROM BDF2_CLOB_STORE WHERE ID_=?";
List<String> list = super.getJdbcTemplate().query(sql, new Object[]{id}, new RowMapper<String>() {
public String mapRow(ResultSet resultset, int i)
throws SQLException {
String content = LobStoreServiceImpl.this
.getLobHandler().getClobAsString(resultset, 1);
return content;
}
});
if(list.size() > 0){
return list.get(0);
}else{
return null;
}
}
 

Example 22


@Test public void testPrepareBindExecuteFetchVarbinary() throws Exception {
  ConnectionSpec.getDatabaseLock().lock();
  try {
    final Connection connection = getLocalConnection();
    final String sql = "select x'de' || ? as c from (values (1, 'a'))";
    final PreparedStatement ps =
        connection.prepareStatement(sql);
    final ParameterMetaData parameterMetaData = ps.getParameterMetaData();
    assertThat(parameterMetaData.getParameterCount(), equalTo(1));

    ps.setBytes(1, new byte[]{65, 0, 66});
    final ResultSet resultSet = ps.executeQuery();
    assertTrue(resultSet.next());
    assertThat(resultSet.getBytes(1),
        equalTo(new byte[]{(byte) 0xDE, 65, 0, 66}));
    resultSet.close();
    ps.close();
    connection.close();
  } finally {
    ConnectionSpec.getDatabaseLock().unlock();
  }
}
 

Example 23


public int delete(Emp emp)
{
if(null != findEmp(emp.getEmpno()))
{
ResultSet rs = null;
String fsql = "DELETE FROM emp WHERE empno = %s";
String sql = String.format(fsql, emp.getEmpno());
rs = getResultSet(sql);

return 1;
}
else
{
return 0;
}
}
 

Example 24


@Override
public Object[] transform(ResultSet rs) {
    if (rs == null) {
        return null;
    }

    try {
        // ??Resultset?????????.
        ResultSetMetaData rsmd = rs.getMetaData();
        int cols = rsmd.getColumnCount();

        // ??????????,???????????'????'?.
        if (rs.next()) {
            Object[] objArr = new Object[cols];
            for (int i = 0; i < cols; i++)  {
                objArr[i] = rs.getObject(i + 1);
            }
            return objArr;
        }
    } catch (Exception e) {
        throw new ResultsTransformException("?'ResultSet'??????'????'??!", e);
    }

    return null;
}
 

Example 25


@Override
public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException
{
    checkClosed();
    VoltTable vtable = new VoltTable(
            new ColumnInfo("PKTABLE_CAT", VoltType.STRING),
            new ColumnInfo("PKTABLE_SCHEM", VoltType.STRING),
            new ColumnInfo("PKTABLE_NAME", VoltType.STRING),
            new ColumnInfo("PKCOLUMN_NAME", VoltType.STRING),
            new ColumnInfo("FKTABLE_CAT", VoltType.STRING),
            new ColumnInfo("FKTABLE_SCHEM", VoltType.STRING),
            new ColumnInfo("FKTABLE_NAME", VoltType.STRING),
            new ColumnInfo("FKCOLUMN_NAME", VoltType.STRING),
            new ColumnInfo("KEY_SEQ", VoltType.SMALLINT),
            new ColumnInfo("UPDATE_RULE", VoltType.SMALLINT),
            new ColumnInfo("DELETE_RULE", VoltType.SMALLINT),
            new ColumnInfo("FK_NAME", VoltType.STRING),
            new ColumnInfo("PK_NAME", VoltType.STRING),
            new ColumnInfo("DEFERRABILITY", VoltType.SMALLINT)
    );

    JDBC4ResultSet res = new JDBC4ResultSet(this.sysCatalog, vtable);
    return res;
}
 

Example 26


public ExampleSet createExampleSet() throws OperatorException {
    int dataRowType = this.getParameterAsInt("datamanagement");
    ResultSet resultSet = this.getResultSet();
    List attributeList = null;

    try {
        attributeList = DatabaseHandler.createAttributes(resultSet);
    } catch (SQLException var6) {
        throw new UserError(this, var6, 304, new Object[]{var6.getMessage()});
    }

    this.setNominalValues(attributeList, resultSet, find(attributeList, this.getParameterAsString("label_attribute")));
    ResultSetDataRowReader reader = new ResultSetDataRowReader(new DataRowFactory(dataRowType, '.'), attributeList, resultSet);
    MemoryExampleTable table = new MemoryExampleTable(attributeList, reader);
    this.tearDown();
    return createExampleSet(table, this);
}
 

Example 27


private RowId createSubEvents(final String query, RowId rid, String tableName, boolean isChildQuery) throws SyncError {
logger.info("createSubEvents called with parameters : isChildQuery =" + isChildQuery + " , rid = " + rid
+ " , tableName = " + tableName + " , query = " + query);
PreparedStatement rowIdpstmt = null;
ResultSet rowIdSet = null;
RowId maxRid = null;
RowId minRid = null;
try {
rowIdpstmt = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT);
if (isChildQuery) {
rowIdpstmt.setRowId(1, rid);
}
rowIdpstmt.setFetchSize(5000);
rowIdSet = rowIdpstmt.executeQuery();
rowIdSet.next();
minRid = rowIdSet.getRowId(1);
for (++subEventCount; subEventCount < (degree - 1); subEventCount++) {
rowIdSet.relative((int) optimalRange);
maxRid = rowIdSet.getRowId(1);
getSubEvent(minRid, maxRid, false);
minRid = maxRid;
fetchCount += optimalRange;
if (fetchCount > 1000000L) {
break;
}
}
if (subEventCount == (degree - 1)) {
rowIdSet.last();
maxRid = rowIdSet.getRowId(1);
getSubEvent(minRid, maxRid, true);
logger.info("Total subEvents created :" + eventCount);
}
} catch (Exception e) {
logger.error("Error while creating subEvents ", e);
throw new SyncError(e);
} finally {
DbResourceUtils.closeResources(rowIdSet, rowIdpstmt, null);
}
return maxRid;
}
 

Example 28


public ResultSet query(String sqlStatement){
    try{
        rs = st.executeQuery(sqlStatement);
        if(rs!=null){
         return rs;
        }else{
         return null;
        }
    }catch(Exception e){
     log.error("????"+e.toString());
        return null;
    }
}
 

Example 29


private static int getNumCompletedDatabaseCreations(Connection conn,
        String db) throws SQLException {
    Statement cmd = conn.createStatement();
    ResultSet resultSet = cmd.executeQuery("SELECT COUNT(*) FROM sys.dm_operation_status \r\n"
            + "WHERE resource_type = 0 -- 'Database' \r\n AND major_resource_id = '" + db + "' \r\n" + "AND state = 2 -- ' COMPLETED'");
    if (resultSet.next()) {
        return resultSet.getInt(1);
    }
    return -1;
}
 

Example 30


public void testBigIntSimpleRead() {
    ResultSet rs = null;
    Statement st = null;
    try {
        st = netConn.createStatement();
        rs = st.executeQuery("SELECT * FROM alltypes WHERE id in (1, 2)");
        assertTrue("Got no rows with id in (1, 2)", rs.next());
        assertEquals(Long.class, rs.getObject("bi").getClass());
        assertTrue("Got only one row with id in (1, 2)", rs.next());
        assertEquals(6, rs.getLong("bi"));
        assertFalse("Got too many rows with id in (1, 2)", rs.next());
    } catch (SQLException se) {
        junit.framework.AssertionFailedError ase
            = new junit.framework.AssertionFailedError(se.getMessage());
        ase.initCause(se);
        throw ase;
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
        } catch(Exception e) {
        }
    }
}
 

Example 31


@Test
public void test_next_blocksFurtherAccessAfterEnd()
    throws SQLException
{
  Connection connection =
      new Driver().connect( "jdbc:dremio:zk=local", JdbcAssert.getDefaultProperties() );
  Statement statement = connection.createStatement();
  ResultSet resultSet =
      statement.executeQuery( "SELECT 1 AS x \n" +
                              "FROM cp.`donuts.json` \n" +
                              "LIMIT 2" );

  // Advance to first row; confirm can access data.
  assertThat( resultSet.next(), is( true ) );
  assertThat( resultSet.getInt( 1 ), is ( 1 ) );

  // Advance from first to second (last) row, confirming data access.
  assertThat( resultSet.next(), is( true ) );
  assertThat( resultSet.getInt( 1 ), is ( 1 ) );

  // Now advance past last row.
  assertThat( resultSet.next(), is( false ) );

  // Main check:  That row data access methods now throw SQLException.
  try {
    resultSet.getInt( 1 );
    fail( "Didn't get expected SQLException." );
  }
  catch ( SQLException e ) {
    // Expect something like current InvalidCursorStateSqlException saying
    // "Result set cursor is already positioned past all rows."
    assertThat( e, instanceOf( InvalidCursorStateSqlException.class ) );
    assertThat( e.toString(), containsString( "past" ) );
  }
  // (Any other exception is unexpected result.)

  assertThat( resultSet.next(), is( false ) );

  // TODO:  Ideally, test all other accessor methods.
}
 

Example 32


public void enableStreamingResults() throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        this.originalResultSetType = this.resultSetType;
        this.originalFetchSize = this.fetchSize;

        setFetchSize(Integer.MIN_VALUE);
        setResultSetType(ResultSet.TYPE_FORWARD_ONLY);
    }
}
 

Example 33


public T process(ResultSet rs) throws SQLException {

int row = 0;

// skip offset
while (row < offset && rs.next())
row++;

// checks if an empty element should be returned
if (!rs.next())
return null;

// map columns
ResultSetMetaData meta = rs.getMetaData();
int[] ordinals = new int[meta.getColumnCount()];
for (int i = 0; i < ordinals.length; i++)
ordinals[i] = aspect.indexOfColumnName(meta.getColumnLabel(i + 1));

// create entity
T entity = aspect.newInstance();
for (int j = 0; j < ordinals.length; j++) {
if (ordinals[j] >= 0) {
Object value = rs.getObject(j + 1);
if (value != null)
aspect.setValue(entity, ordinals[j], value);
}
}
return entity;

}
 

Example 34


public Object getResult(ResultSet rs, int columnIndex) throws SQLException {

            java.sql.Timestamp sqlTimestamp = rs.getTimestamp(columnIndex);
            if (rs.wasNull()) {
                return null;
            }
            else {
                return new java.util.Date(sqlTimestamp.getTime());
            }
        }
 

Example 35


public void update_object() throws Exception {
    String sql = " update db1.mytable1 set author['age'] = 24 where id = 1";
    int affectRows = stmt.executeUpdate(sql);
    assertEquals(1, affectRows);

    String searchSQL = " select author['age'] from db1.mytable1 WHERE id = 1";
    ResultSet rs = stmt.executeQuery(searchSQL);
    int age = 0;
    while (rs.next()) {
        age = rs.getInt("author['age']");
    }
    assertEquals(24, age);
}
 

Example 36


public MetaResultSet getTablePrivileges(ConnectionHandle ch, String catalog, Pat schemaPattern,
    Pat tableNamePattern) {
  try {
    final ResultSet rs =
        getConnection(ch.id).getMetaData().getTablePrivileges(catalog,
            schemaPattern.s, tableNamePattern.s);
    int stmtId = registerMetaStatement(rs);
    return JdbcResultSet.create(ch.id, stmtId, rs);
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
}
 

Example 37


public void fileToField(ResultSet resultset, String s)
    throws ServletException, IOException, SmartUploadException, SQLException
{
    long l = 0L;
    int i = 0x10000;
    int j = 0;
    int k = m_startData;
    if(resultset == null)
        throw new IllegalArgumentException("The RecordSet cannot be null (1145).");
    if(s == null)
        throw new IllegalArgumentException("The columnName cannot be null (1150).");
    if(s.length() == 0)
        throw new IllegalArgumentException("The columnName cannot be empty (1155).");
    l = BigInteger.valueOf(m_size).divide(BigInteger.valueOf(i)).longValue();
    j = BigInteger.valueOf(m_size).mod(BigInteger.valueOf(i)).intValue();
    try
    {
        for(int i1 = 1; (long)i1 < l; i1++)
        {
            resultset.updateBinaryStream(s, new ByteArrayInputStream(m_parent.m_binArray, k, i), i);
            k = k != 0 ? k : 1;
            k = i1 * i + m_startData;
        }

        if(j > 0)
            resultset.updateBinaryStream(s, new ByteArrayInputStream(m_parent.m_binArray, k, j), j);
    }
    catch(SQLException sqlexception)
    {
        byte abyte0[] = new byte[m_size];
        System.arraycopy(m_parent.m_binArray, m_startData, abyte0, 0, m_size);
        resultset.updateBytes(s, abyte0);
    }
    catch(Exception exception)
    {
        throw new SmartUploadException("Unable to save file in the DataBase (1130).");
    }
}
 

Example 38


String fixupColumnDefRead(TransferTable t, ResultSetMetaData meta,
                          String columnType, ResultSet columnDesc,
                          int columnIndex) throws SQLException {

    String SeqName   = new String("_" + columnDesc.getString(4) + "_seq");
    int    spaceleft = 31 - SeqName.length();

    if (t.Stmts.sDestTable.length() > spaceleft) {
        SeqName = t.Stmts.sDestTable.substring(0, spaceleft) + SeqName;
    } else {
        SeqName = t.Stmts.sDestTable + SeqName;
    }

    String CompareString = "nextval(\'\"" + SeqName + "\"\'";

    if (columnType.indexOf(CompareString) >= 0) {

        // We just found a increment
        columnType = "SERIAL";
    }

    for (int Idx = 0; Idx < Funcs.length; Idx++) {
        String PostgreSQL_func = Funcs[Idx][PostgreSQL];
        int    iStartPos       = columnType.indexOf(PostgreSQL_func);

        if (iStartPos >= 0) {
            String NewColumnType = columnType.substring(0, iStartPos);

            NewColumnType += Funcs[Idx][HSQLDB];
            NewColumnType +=
                columnType.substring(iStartPos
                                     + PostgreSQL_func.length());
            columnType = NewColumnType;
        }
    }

    return (columnType);
}
 

Example 39


public List<Map<String, Object>> getAllEventsInfo() throws SQLException {

List<Map<String, Object>> lst_events = new ArrayList<>();

Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select * from event_info";

con = DBConnection.getConnection();
ps = con.prepareStatement(sql);

rs = ps.executeQuery();

while (rs.next()) {
Map<String, Object> eventInfo = new HashMap<String, Object>();

eventInfo.put("eventd", rs.getInt(1));
eventInfo.put("latitude", rs.getDouble(2));
eventInfo.put("Longitude", rs.getDouble(3));

Timestamp eventEntireDate = rs.getTimestamp(4);
if (eventEntireDate != null) {
String eventDateTimeStr = eventEntireDate.toString();

eventInfo.put("date", eventDateTimeStr.substring(0, 10));
eventInfo.put("time", eventDateTimeStr.substring(11, eventDateTimeStr.length()));
}

eventInfo.put("eventName", rs.getString(5));

lst_events.add(eventInfo);
}

con.close();

return lst_events;
}
 

Example 40


@Override
public long getElementCountForQualifier(long qialifierId) {
    return (Long) template.queryForObject("SELECT COUNT(*) FROM " + prefix
            + "elements WHERE qualifier_id=?", new RowMapper() {
        @Override
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            return rs.getLong(1);
        }
    }, qialifierId, true);
}
 

public void testBug3557() throws Exception {
    boolean populateDefaults = ((com.mysql.jdbc.ConnectionProperties) this.conn).getPopulateInsertRowWithDefaultValues();

    try {
        ((com.mysql.jdbc.ConnectionProperties) this.conn).setPopulateInsertRowWithDefaultValues(true);

        this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3557");

        this.stmt.executeUpdate(
                "CREATE TABLE testBug3557 (`a` varchar(255) NOT NULL default 'XYZ', `b` varchar(255) default '123', PRIMARY KEY  (`a`(100)))");

        Statement updStmt = this.conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        this.rs = updStmt.executeQuery("SELECT * FROM testBug3557");

        assertTrue(this.rs.getConcurrency() == ResultSet.CONCUR_UPDATABLE);

        this.rs.moveToInsertRow();

        assertEquals("XYZ", this.rs.getObject(1));
        assertEquals("123", this.rs.getObject(2));
    } finally {
        ((com.mysql.jdbc.ConnectionProperties) this.conn).setPopulateInsertRowWithDefaultValues(populateDefaults);

        this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3557");
    }
}
 

Example 42


public Event mapRow(ResultSet rs, int rowNum) throws SQLException {
    CalendarUser attendee = ATTENDEE_ROW_MAPPER.mapRow(rs, rowNum);
    CalendarUser owner = OWNER_ROW_MAPPER.mapRow(rs, rowNum);

    Event event = new Event();
    event.setId(rs.getInt("events.id"));
    event.setSummary(rs.getString("events.summary"));
    event.setDescription(rs.getString("events.description"));
    Calendar when = Calendar.getInstance();
    when.setTime(rs.getDate("events.when"));
    event.setWhen(when);
    event.setAttendee(attendee);
    event.setOwner(owner);
    return event;
}
 

Example 43


protected void queryCheckVersion() throws SQLException {
    setCurrentOperation("version checking query");
    try (ResultSet res = statement.executeQuery(JdbcQueries.QUERY_CHECK_VERSION)) {
        while (res.next()) {
            version = res.getInt(VERSION);
        }
    }
}
 

Example 44


private boolean isResultSetClosedForTestBug69746(ResultSet resultSet) {
    try {
        resultSet.first();
    } catch (SQLException ex) {
        return ex.getMessage().equalsIgnoreCase(Messages.getString("ResultSet.Operation_not_allowed_after_ResultSet_closed_144"));
    }
    return false;
}
 

Example 45

Project: momo-2   File: MacroObject.java   Source Code and License 5 votes vote downvote up
/**
 * Search for macros by user and given guild
 * @param userId UserID to search for
 * @param guildId GuildID to search in
 * @return Null if no results, populated string array of macro names if results
 */
public static String[] searchByUser(String userId, String guildId) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
ArrayList<String> toReturn = new ArrayList<String>(10);
try {
conn = ConnectionPool.getConnection(guildId);
String sql = "SELECT macro FROM `discord_macro` WHERE user_id = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, userId);
rs = stmt.executeQuery();
if(!rs.isBeforeFirst())
return null;
while(rs.next()) {
toReturn.add(rs.getString(1));
}
return toReturn.toArray(new String[0]);
} catch(SQLException e) {
e.printStackTrace();
return null;
} finally {
SQLUtils.closeQuietly(rs);
SQLUtils.closeQuietly(stmt);
SQLUtils.closeQuietly(conn);
}
}
 

Example 46


public void testBug27431() throws Exception {
    createTable("bug27431", "(`ID` int(20) NOT NULL auto_increment, `Name` varchar(255) NOT NULL default '', PRIMARY KEY  (`ID`))");

    this.stmt.executeUpdate("INSERT INTO bug27431 (`ID`, `Name`) VALUES (1, 'Lucho'),(2, 'Lily'),(3, 'Kiro')");

    Statement updStmt = this.conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
    this.rs = updStmt.executeQuery("SELECT ID, Name FROM bug27431");

    while (this.rs.next()) {
        this.rs.deleteRow();
    }

    assertEquals(0, getRowCount("bug27431"));
}
 

Example 47


private static Class<?> getColumnType(DatabaseMetaData databaseMetaData, String tableName, String columnName)
throws SQLException {
try (ResultSet rs = databaseMetaData.getColumns(null, null, tableName, columnName)) {
if (rs.next()) {
return jdbcTypeToClass(rs.getInt("DATA_TYPE"));
}
}
return null;
}
 
Example 48
Project: elastic-job-cloud   File: JobEventRdbStorage.java   Source Code and License 5 votes vote downvote up
private void createJobExecutionTableAndIndexIfNeeded(final Connection conn) throws SQLException {
    DatabaseMetaData dbMetaData = conn.getMetaData();
    try (ResultSet resultSet = dbMetaData.getTables(null, null, TABLE_JOB_EXECUTION_LOG, new String[]{"TABLE"})) {
        if (!resultSet.next()) {
            createJobExecutionTable(conn);
        }
    }
}
 

Example 49

Project: ProyectoPacientes   File: BaseTestCase.java   Source Code and License 5 votes vote downvote up
protected int getRowCount(String tableName) throws SQLException {
    ResultSet countRs = null;

    try {
        countRs = this.stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);

        countRs.next();

        return countRs.getInt(1);
    } finally {
        if (countRs != null) {
            countRs.close();
        }
    }
}
 
Example 50

public Object nullSafeGet(
ResultSet rs,
String columnName,
SessionImplementor session,
Object owner)
throws HibernateException, SQLException {

return userType.nullSafeGet( rs, new String[] {columnName}, session, owner );
}
 

Example 51


@SuppressWarnings("unchecked")
public OracleJdbc4NativeJdbcExtractor() {
try {
setConnectionType((Class<Connection>) getClass().getClassLoader().loadClass("oracle.jdbc.OracleConnection"));
setStatementType((Class<Statement>) getClass().getClassLoader().loadClass("oracle.jdbc.OracleStatement"));
setPreparedStatementType((Class<PreparedStatement>) getClass().getClassLoader().loadClass("oracle.jdbc.OraclePreparedStatement"));
setCallableStatementType((Class<CallableStatement>) getClass().getClassLoader().loadClass("oracle.jdbc.OracleCallableStatement"));
setResultSetType((Class<ResultSet>) getClass().getClassLoader().loadClass("oracle.jdbc.OracleResultSet"));
}
catch (Exception ex) {
throw new IllegalStateException(
"Could not initialize OracleJdbc4NativeJdbcExtractor because Oracle API classes are not available: " + ex);
}
}
 

Example 52


public static  void closeResultSet(ResultSet rs)
{
if(rs != null)
{
try
{
rs.close();
}
catch(SQLException e)
{
LOGGER.catching(e);
}
}
}
 

Example 53


@Override
public void updateExpiryTime(Connection txn, ContactId c, MessageId m,
int maxLatency) throws DbException {
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = "SELECT txCount FROM statuses"
+ " WHERE messageId = ? AND contactId = ?";
ps = txn.prepareStatement(sql);
ps.setBytes(1, m.getBytes());
ps.setInt(2, c.getInt());
rs = ps.executeQuery();
if (!rs.next()) throw new DbStateException();
int txCount = rs.getInt(1);
if (rs.next()) throw new DbStateException();
rs.close();
ps.close();
sql = "UPDATE statuses SET expiry = ?, txCount = txCount + 1"
+ " WHERE messageId = ? AND contactId = ?";
ps = txn.prepareStatement(sql);
long now = clock.currentTimeMillis();
ps.setLong(1, calculateExpiry(now, maxLatency, txCount));
ps.setBytes(2, m.getBytes());
ps.setInt(3, c.getInt());
int affected = ps.executeUpdate();
if (affected != 1) throw new DbStateException();
ps.close();
} catch (SQLException e) {
tryToClose(rs);
tryToClose(ps);
throw new DbException(e);
}
}
 

Example 54


private void load(Topic t)
{
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM posts WHERE post_forum_id=? AND post_topic_id=? ORDER BY post_id ASC"))
{
ps.setInt(1, t.getForumID());
ps.setInt(2, t.getID());
try (ResultSet rs = ps.executeQuery())
{
while (rs.next())
{
final CPost cp = new CPost();
cp.postId = rs.getInt("post_id");
cp.postOwner = rs.getString("post_owner_name");
cp.postOwnerId = rs.getInt("post_ownerid");
cp.postDate = rs.getLong("post_date");
cp.postTopicId = rs.getInt("post_topic_id");
cp.postForumId = rs.getInt("post_forum_id");
cp.postTxt = rs.getString("post_txt");
_post.add(cp);
}
}
}
catch (Exception e)
{
LOGGER.log(Level.WARNING, "Data error on Post " + t.getForumID() + "/" + t.getID() + " : " + e.getMessage(), e);
}
}
 
Example 55
Project: lams   File: LoadingCollectionEntry.java   Source Code and License 5 votes vote downvote up
LoadingCollectionEntry(
ResultSet resultSet,
CollectionPersister persister,
Serializable key,
PersistentCollection collection) {
this.resultSet = resultSet;
this.persister = persister;
this.key = key;
this.collection = collection;
}
 

Example 56


public static List<ProductoObjetoGasto> selectObjetoGastoCosto(String condicion)throws SQLException{
Connection conect=ConnectionConfiguration.conectarSpr();

String query = " select distinct objeto_gasto from asignacion_presi " + condicion 
+ " and version = "
                 + " (select max(version) from asignacion_presi " + condicion + ") "
                 + " order by objeto_gasto";

Statement statement = null;
ResultSet rs=null;
List<ProductoObjetoGasto> objetos = new ArrayList<ProductoObjetoGasto>();

try {
statement = conect.createStatement();
rs=statement.executeQuery(query);

while(rs.next()){
ProductoObjetoGasto objeto = new ProductoObjetoGasto();
objeto.setCodigoObjetoGasto(rs.getInt("objeto_gasto"));
objetos.add(objeto);
  }
}
catch (SQLException e) {e.printStackTrace();}
finally{
  if (statement != null) {statement.close();}
  if (conect != null) {conect.close();}
}
return objetos;
}
 

Example 57


public MetaResultSet getVersionColumns(ConnectionHandle ch, String catalog, String schema,
    String table) {
  LOG.trace("getVersionColumns catalog:{} schema:{} table:{}", catalog, schema, table);
  try {
    final ResultSet rs =
        getConnection(ch.id).getMetaData().getVersionColumns(catalog, schema, table);
    int stmtId = registerMetaStatement(rs);
    return JdbcResultSet.create(ch.id, stmtId, rs);
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
}
 

Example 58


public JSONArray selectAllRow(String query) throws SQLException {
try {
Statement st =  connection.createStatement();
// st.execute("use "+databaseName);
ResultSet rs = st.executeQuery(query);
return ResultSetConverter.convert(rs);
} catch(SQLException e) {
e.printStackTrace();
throw e;
}
}
 

Example 59


static void listFiles(Connection conn, String name) throws SQLException {

    System.out.println("Files like '" + name + "'");

    // Convert to upper case, so the search is case-insensitive
    name = name.toUpperCase();

    // Create a statement object
    Statement stat = conn.createStatement();

    // Now execute the search query
    // UCASE: This is a case insensitive search
    // ESCAPE ':' is used so it can be easily searched for '\'
    ResultSet result = stat.executeQuery("SELECT Path FROM Files WHERE "
                                         + "UCASE(Path) LIKE '%" + name
                                         + "%' ESCAPE ':'");

    // Moves to the next record until no more records
    while (result.next()) {

        // Print the first column of the result
        // could use also getString("Path")
        System.out.println(result.getString(1));
    }

    // Close the ResultSet - not really necessary, but recommended
    result.close();
}
 

Example 60


public CSQLResultSet executeQueryCursor(SQL sql)
{
if(isLogSql())
Log.logDebug("CSQLPreparedStatement::executeQueryCursor:"+m_csQueryString);
if(m_PreparedStatement != null)
{
try
{
sql.startDbIO();
ResultSet r = m_PreparedStatement.executeQuery();
if(r != null)
{
CSQLResultSet rs = new CSQLResultSet(r, m_semanticContextDef, sql);
sql.m_sqlStatus.setSQLCode(SQLCode.SQL_OK) ;
sql.endDbIO();
return rs ;
}
else
{
sql.m_sqlStatus.setSQLCode(SQLCode.SQL_NOT_FOUND) ;
sql.endDbIO();
}
}
catch (SQLException e)
{
sql.endDbIO();
manageSQLException("executeQueryCursor", e, sql);
}
}
return null;
}
 

Convert Text to HTML

Convert Text to HTML

      

In this section, We are discussing the conversion of text into html file .This program functionally provides you converting text to html file by using FileOutputStream. The FileOutputStream() is a constructor.

Code Description:

In this program, you will also learn about the OutputStreamWriter. The OutputStreamWriter is a constructor. The FileOutputStream create an output file stream to write to the file with the specified name.

Here is the code of this program:
package com.mycompany.internationalyouthacuity;
import java.math.*;
import java.io.*;

public class TextToHTML{ 
  public static void main(String arg[]){
  try{
  FileOutputStream fs = new FileOutputStream("TextToHTML.html");
  OutputStreamWriter out = new OutputStreamWriter(fs);
  System.out.println("This is text to html convertor program:");
  out.write("<html>");  
  out.write("<head>"); 
  out.write("<title>");  
  out.write("Convert text to html");
  out.write("</title>");  
  out.write("</head>");
  out.write("<body>");
  out.write("Welcome to html<br>This query through the java code");
  out.write("<br>Welcome to Roseindia<br>This is good site");
  out.write("</body>");
  out.write("</html>");
  out.close();
  }
  catch (IOException e){
  System.err.println(e);
  }
  }
}

What is the difference between an enum type and java.lang.Enum?

What is the difference between an enum type and java.lang.Enum?

An enum type, also called enumeration type, is a type whose fields consist of a fixed set of constants. The purpose of using enum type is to enforce type safety.

While java.lang.Enum is an abstract class, it is the common base class of all Java language enumeration types. The definition of Enum is:

public abstract class Enum>
extends Object
implements Comparable, Serializable
All enum types implicitly extend java.lang.Enum.

The enum is a special reference type, it is not a class by itself, but more like a category of classes that extends from the same base class Enum. Any type declared by the key word "enum" is a different class. They easiest way to declare a enum type is like:

public enum Season {
    SPRING, SUMMER, AUTUM, WINTER
}

or

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY
}

Here Season and Day are both enum, but they are different type. All the constants in a enum type is of the same type. For example, SPRING and SUMMER are both of type Season.

Since all enum types All enum types implicitly extend java.lang.Enum, all the methods defined in the Enum class are available to all enum types, such as the

String name() method, which returns the name of this enum constant

int ordinal() method, which returns the ordinal of this enumeration constant, starts from 0

For more information, refer to SCJP Study Guide: Enums

Note: Since Java does not support multiple inheritance, an enum cannot extend anything else.

How to display stack trace information in java programming language?

How to display stack trace information in java programming language?

here given a good example of source code ,by using source code you can
handle data of display of stack trace information.

 

class ClassUtil {
    
    public String fullyQualifiedName;
    public ClassUtil(String fullyQualifiedName) {
        super();
        if (fullyQualifiedName == null) 
            this.fullyQualifiedName = "";
        else {
            this.fullyQualifiedName = fullyQualifiedName.trim();
        }
    }
    
    public ClassUtil(Class c) {
        
        super();
        this.fullyQualifiedName = c.getName();
        
    }
    public String getFullClassName() {
        return this.fullyQualifiedName;
    }
    
    public String getPackageName() {
        int lastDot = fullyQualifiedName.lastIndexOf ('.');
        return (lastDot<=0)?"":fullyQualifiedName.substring (0, lastDot);
    }
         
    public String getClassName() {
        int lastDot = fullyQualifiedName.lastIndexOf ('.');
        return (lastDot<=0)?fullyQualifiedName:fullyQualifiedName.substring (++lastDot);
    }
    
}
public class StackTraceDisplay {
    public static void main(String[] args) {
        doFun1();
    }
    public static void doFun1(){
        doFun2();
    }
    public static void doFun2(){
        displayStackTrace(Thread.currentThread().getStackTrace());
    }
    
    public static void displayStackTrace(StackTraceElement e[]) {
        
        for (StackTraceElement s : e) {
            if (s.getMethodName().equals("getStackTrace"))
                continue;
            System.out.println ("Filename: " + s.getFileName());
            System.out.println ("Line number: " + s.getLineNumber());
            ClassUtil cu = new ClassUtil(s.getClassName());
            System.out.println ("Package name: " + cu.getPackageName());
            System.out.println ("Full Class name: " + cu.getFullClassName());
            System.out.println ("Classlass name: " + cu.getClassName());
            System.out.println ("Method name: " + s.getMethodName());
            System.out.println ("Native method?: " + s.isNativeMethod());
            System.out.println ("toString(): " + s.toString());
            System.out.println ("");
        }
    }
}

Which replace function works with regex in java programming language?

Which replace function works with regex in java programming language?

More than often we need to manipulate a string, substitute characters inside a string. In Java, the String class, there are a couple of methods that we can use to complete this task.

1. public String replace(char oldChar, char newChar)


   This method "returns a new string resulting from replacing all occurrences of oldChar in this string with newChar."
   Both oldChar and newChar are single char.
   For example, String a = "This is a cat.";
   String b = a.replace('c', 'r');
   b has the value of "This is a rat.".

2. public String replace(CharSequence target, CharSequence replacement)


   This method "replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence."      
   String c = "This is a cat.";
   String d = c.replace("ca", "rabbi");
   d has the value of "This is a rabbit.".
  
   Note: this method only works with replacing a sub string with a string, it doesn't work with regex. For example:
  
   String e = "This is a cat.";
   String f = e.replace("\\s", "b");
   f is still "This is a cat.". Because the function is looking for a string like "\s" to replace.

   Sometimes, you need to replace many characters, regex comes handy. For example, you want to create a clean url for an article by using its title, but a title can contain special characters that may break your url. One way to do this is to strip out all the non-alphanumerics from the string. Then you will need to use the following method to handle regex target.

3. public String replaceAll(String regex, String replacement)


   This method "replaces each substring of this string that matches the given regular expression with the given replacement."

   String title = "Since When Do Politicians \"Care\" About Newspapers?";
   String result = title.replaceAll("[^a-zA-Z0-9\\s]", "");
   result = result.replaceAll("\\s", "-"); // replace white spaces to "-".
   The result is "Since-When-Do-Politicians-Care-About-Newspapers";

4. public String replaceFirst(String regex, String replacement)


   This method "replaces the first substring of this string that matches the given regular expression with the given replacement."

   String title = "Since When Do Politicians Care About Newspapers?";
   String result = title.replaceAll("[^a-zA-Z0-9\\s]", "");
   result = result.replaceAll("\\s", "-"); // replace white spaces to "-".
   The result is "Since-WhenDo Politicians Care About Newspapers?".