public static int saveHost(String host, String protocol, String ip, String subdomain,
int port, String countrycode, String encoding, int trusted, int status,
int wired) throws Exception {
Logger logger = Logger.getLogger(Main.class.getName());
Connection connection = null;
try {
int id = 0;
connection = DatabaseTools.getDBConnection();
String sql = "Select * FROM hosts WHERE host = ?";
PreparedStatement statement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
statement.setString(1, host);
ResultSet entry = statement.executeQuery();
entry.last();
int rows = entry.getRow();
entry.beforeFirst();
logger.info("Host count: " + rows);
if(rows == 0)
{
logger.info("Creating new Host entry");
sql = "INSERT INTO hosts ( host, protocol, ip, subdomain, port, countrycode, encoding, firstcrawl, lastcrawl, trusted, status) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
statement = connection.prepareStatement(sql);
statement.setString(1, host);
statement.setString(2, protocol);
statement.setString(3, ip);
statement.setString(4, subdomain);
statement.setInt(5, port);
statement.setString(6, countrycode);
statement.setString(7, encoding);
statement.setTimestamp(8, new java.sql.Timestamp(System.currentTimeMillis()));
statement.setTimestamp(9, new java.sql.Timestamp(System.currentTimeMillis()));
statement.setInt(10, trusted);
statement.setInt(11, 0);
statement.execute();
logger.info("Statement" + statement);
// Getting new id
sql = "Select * FROM hosts WHERE host = ? AND status = 0";
statement = connection.prepareStatement(sql);
statement.setString(1, host);
entry = statement.executeQuery();
while(entry.next())
{
id = entry.getInt("id");
}
} else {
while (entry.next())
{
logger.info("Host is already in index");
id = entry.getInt("id");
}
entry.first();
entry.updateTimestamp("lastcrawl", new java.sql.Timestamp(System.currentTimeMillis()));
if (entry.getString("ip") != null)
{
if(entry.getString("ip").equals(ip))
{
entry.updateString("ip", ip);
logger.info("Host has a new ip adress: " + ip);
}
}
int crawlcount = entry.getInt("crawlcount");
crawlcount++;
entry.updateInt("crawlcount", crawlcount);
logger.info("Updated number of crawl to: " + crawlcount);
entry.updateRow();
}
entry.close();
statement.close();
connection.close();
return id;
} finally {
try {
if (connection != null)
connection.close();
} catch (Exception e) {
logger.log(Level.WARNING, "Something went wrong saving host " + host, e);
}
}
}// End Save Host