My Java API compares Team members from another application with Rally. The compared results is updated in Rally. It takes the reference of Project name and Res name.
The code throws "java.lang.IndexOutOfBoundsException: Index: 0, Size: 0" error. I coudn't spot the error. Could some one help? Following is the code and the output
package teammembership;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.QueryRequest;
import com.rallydev.rest.response.QueryResponse;
import com.rallydev.rest.request.UpdateRequest;
import com.rallydev.rest.response.UpdateResponse;
import com.rallydev.rest.util.Fetch;
import com.rallydev.rest.util.QueryFilter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.io.*;
import java.sql.*;
import javax.xml.parsers.DocumentBuilder;
import org.apache.soap.util.xml.*;
import org.w3c.dom.*;
//import org.json.*;
//import static projectteammembers.JsonUtil.getJsonValue;
public class TeamMembership {
public static Connection makeConnection(String propertiesFile) throws SQLException, Exception {
Connection conn = null;
DocumentBuilder docBuilder = XMLParserUtils.getXMLDocBuilder();
Document doc = docBuilder.parse(new File(propertiesFile));
// Retrieve database parameters
Element database = (Element) doc.getElementsByTagName("database").item(0);
String url = database.getAttribute("url");
String serviceId = database.getAttribute("serviceId");
String username = database.getAttribute("username");
String password = database.getAttribute("password");
String host = url.substring(url.indexOf("//"), url.indexOf(";"));
String connectString = "jdbc:oracle:thin:#" + host + "/" + serviceId;
// Load JDBC Driver
String driverClass = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverClass);
try {
conn = DriverManager.getConnection(connectString, username, password);
} catch (SQLException ex) {
throw new SQLException(ex);
} catch (Exception ex) {
throw new Exception(ex);
}
return conn;
}
public static void main(String[] args) throws URISyntaxException, IOException, SQLException {
String host = "https://rally1.rallydev.com";
String username = "username#abc.com";
String password = "password";
//String userRef = "";
String applicationName = "update team membership";
//int queryLimit = 4000;
Connection conn = null;
String propertiesFile = "";
propertiesFile = "c:/app/c/properties_prod.xml";
String projid = "";
String resid = "";
//String returnValue = "";
String selectString = "";
RallyRestApi restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setApplicationName(applicationName);
System.out.println(restApi.getWsapiVersion());
try {
conn = makeConnection(propertiesFile);
// Select compared records of Team member present in table1 not in table2
selectString += "select Prj_name ";
selectString += ",res_name";
selectString += " from CUST_table1_v c ";
selectString += " WHERE NOT EXISTS( select 1 from CUST_table2_v r";
selectString += " where c.prj_name = r.Prj_name and c.res_name = r.res_name)";
// Create select statement
Statement st = (Statement) conn.createStatement();
// Execute select statement
ResultSet rs = st.executeQuery(selectString);
while (rs.next()) {
projid = rs.getString("Prj_name");
resid = "(" + rs.getString("res_name") + ")";
System.out.println(projid);
System.out.println(resid);
QueryRequest projectRequest = new QueryRequest("Project");
projectRequest.setFetch(new Fetch("Name"));
projectRequest.setQueryFilter(new QueryFilter("Name", "=", projid));
QueryResponse projectQueryResponse = restApi.query(projectRequest);
JsonObject projectObj = projectQueryResponse.getResults().get(0).getAsJsonObject();
QueryRequest userRequest = new QueryRequest("User");
userRequest.setFetch(new Fetch("UserPermissions", "TeamMemberships"));
userRequest.setQueryFilter(new QueryFilter("DisplayName", "contains", resid));
QueryResponse userQueryResponse = restApi.query(userRequest);
System.out.println(userQueryResponse);
JsonObject userObject = userQueryResponse.getResults().get(0).getAsJsonObject();
//JsonObject projectObj = new JsonObject(projid);
String userRef = userObject.get("_ref").toString();
System.out.println("Found User with Ref: " + userRef);
JsonArray existTeamMemberships = (JsonArray) userQueryResponse.getResults().get(0).getAsJsonObject().get("TeamMemberships");
// add or remove projects for user
existTeamMemberships.add(projectObj);
// Setup update fields/values for Team Membership
JsonObject updateUserTeamMembershipObj = new JsonObject();
updateUserTeamMembershipObj.add("TeamMemberships", existTeamMemberships);
UpdateRequest updateTeamMembershipsRequest = new UpdateRequest(userRef, updateUserTeamMembershipObj);
UpdateResponse updateTeamMembershipResponse = restApi.update(updateTeamMembershipsRequest);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
restApi.close();
conn.close();
}
}
}
Following is the error out put
v2.0
DT-E2E Automation
(tmanjunath)
com.rallydev.rest.response.QueryResponse#193d23b
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at com.google.gson.JsonArray.get(JsonArray.java:92)
at teammembership.TeamMembership.main(TeamMembership.java:125)
BUILD SUCCESSFUL (total time: 11 seconds)
You have a List (an ArrayList to be exact) which contains nothing (no single object) and you try to access the first object (which doesn't exist). That's what the error tells you. You try to access index 0 (the first position in the list) but there is no element in it (so the size is 0). It happens around line 125. Since your formatting in the question doesn't seem to be correct, I can only guess which line in your question is line 125 (and I don't want to read 125 lines of code by the way). So I think the exception occurs here:
JsonObject userObject = userQueryResponse.getResults().get(0).getAsJsonObject();
Try to track it down. Make sure the list returned from userQueryResponse.getResults() contains something:
list = userQueryResponse.getResults();
System.out.println(list.size());
If not, that's your problem. If you cannot solve it, ask a specific question about this problem without posting 150 line of code.
get("_ref").toString() used to work with the older versions, and the code you refer to is older. When using 2.0.4 jar (which by default uses the most recent version of WS API in production, v2.0) replace all instances of it with get("_ref").getAsString().
For example,
String userRef = userObject.get("_ref").toString();
will generate java.lang.NullPointerException: key == null
Related
I have downloaded aws sdk and connected my account and the database. But now I do not know what I need to do next. How do insert, delete or create table through java on eclipse.
I know to do these in a local database. I tried changing the url in getConnection() function to the my endpoint on eclipse but I keep getting error stating
"Access denied for user 'aws'#'xxx.xxx.xxx.xxx' (using password: YES)" (real IP modified for security reasons).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
public class MySQLAccess {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
private static final String url = "jdbc:mysql://aws.cyduxshnlizb.ap-south-1.rds.amazonaws.com:3306";
final private String user = "myusername";
final private String passwd = "mypassword";
public void readDataBase() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection(url,user,passwd);
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement
.executeQuery("select * from feedback.comments");
writeResultSet(resultSet);
// PreparedStatements can use variables and are more efficient
preparedStatement = connect
.prepareStatement("insert into feedback.comments values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summary, COMMENTS from feedback.comments");
// Parameters start with 1
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "TestEmail");
preparedStatement.setString(3, "TestWebpage");
preparedStatement.setDate(4, new java.sql.Date(2009, 12, 11));
preparedStatement.setString(5, "TestSummary");
preparedStatement.setString(6, "TestComment");
preparedStatement.executeUpdate();
preparedStatement = connect
.prepareStatement("SELECT myuser, webpage, datum, summary, COMMENTS from feedback.comments");
resultSet = preparedStatement.executeQuery();
writeResultSet(resultSet);
// Remove again the insert comment
preparedStatement = connect
.prepareStatement("delete from feedback.comments where myuser= ? ; ");
preparedStatement.setString(1, "Test");
preparedStatement.executeUpdate();
resultSet = statement
.executeQuery("select * from feedback.comments");
writeMetaData(resultSet);
} catch (Exception e) {
throw e;
} finally {
close();
}
}
private void writeMetaData(ResultSet resultSet) throws SQLException {
// Now get some metadata from the database
// Result set get the result of the SQL query
System.out.println("The columns in the table are: ");
System.out.println("Table: " + resultSet.getMetaData().getTableName(1));
for (int i = 1; i<= resultSet.getMetaData().getColumnCount(); i++){
System.out.println("Column " +i + " "+ resultSet.getMetaData().getColumnName(i));
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("myuser");
String website = resultSet.getString("webpage");
String summary = resultSet.getString("summary");
Date date = resultSet.getDate("datum");
String comment = resultSet.getString("comments");
System.out.println("User: " + user);
System.out.println("Website: " + website);
System.out.println("Summary: " + summary);
System.out.println("Date: " + date);
System.out.println("Comment: " + comment);
}
}
// You need to close the resultSet
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}
}
I have written below code to read cells from excel and then update it to MySQL table. There are more than 2000 records and this code is only updating the last record but not all the records. If I put 'pstm.executeBatch();' inside for loop, then it updates all the records but one by one, which takes about 2 minutes. I want to reduce this time, so added "&rewriteBatchedStatements=true" in URL and put 'pstm.executeBatch();' outside for loop. In console it shows reading of all the records but the database has only the last record updated.
package com.company.testdata;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class UpdateDataCopy {
public static void main(String[] args) throws Exception {
String user = "root";
String pass = "test";
String jdbcUrl = "jdbc:mysql://192.1.2.1/db_bro_mumbai?useSSL=false"+
"&rewriteBatchedStatements=true";
String driver = "com.mysql.jdbc.Driver";
try {
PreparedStatement pstm = null;
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
FileInputStream input = new FileInputStream("E:\\Work\\TestData.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(input);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row;
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = (XSSFRow) sheet.getRow(i);
int id = (int)row.getCell(0).getNumericCellValue();
System.out.println(id);
String firstname = row.getCell(2).getStringCellValue();
System.out.println(firstname);
String middlename = row.getCell(3).getStringCellValue();
System.out.println(middlename);
String lastname = row.getCell(4).getStringCellValue();
System.out.println(lastname);
int physicalFitness = (int)row.getCell(25).getNumericCellValue();
System.out.println(physicalFitness);
String sql = "UPDATE fitness_details as p SET p.physicalFitness = ? "
+ " WHERE CandidateID_FK1 = ?";
pstm = (PreparedStatement) myConn.prepareStatement(sql);
pstm.setInt(1, physicalFitness);
pstm.setInt(2, id);
pstm.addBatch();
//Adding below line will update record one by one which is time consuming, so I commented this and added it after for loop.
//pstm.executeBatch();
System.out.println("Import rows " + i);
}
pstm.executeBatch();
System.out.println("Imported");
//myConn.commit();
//pstm.close();
//myConn.close();
input.close();
}
catch (Exception exc) {
exc.printStackTrace();
throw new ServletException(exc);
}
}
}
Has mentioned in my comment...
package com.company.testdata;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class UpdateDataCopy {
public static void main(String[] args) throws Exception {
String user = "root";
String pass = "test";
String jdbcUrl = "jdbc:mysql://172.16.206.197/db_bro_mumbai?useSSL=false"+
"&rewriteBatchedStatements=true";
String driver = "com.mysql.jdbc.Driver";
try {
PreparedStatement pstm = null;
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
String sql = "UPDATE fitness_details as p SET p.physicalFitness = ? WHERE CandidateID_FK1 = ?";
pstm = myConn.prepareStatement(sql);
FileInputStream input = new FileInputStream("E:\\Work\\TestData.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(input);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row;
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = (XSSFRow) sheet.getRow(i);
int id = (int)row.getCell(0).getNumericCellValue();
String firstname = row.getCell(2).getStringCellValue();
String middlename = row.getCell(3).getStringCellValue();
String lastname = row.getCell(4).getStringCellValue();
int physicalFitness = (int)row.getCell(25).getNumericCellValue();
pstm.setInt(1, physicalFitness);
pstm.setInt(2, id);
pstm.addBatch();
System.out.println("Import rows " + I + "ID: " + id + " Middlename:" + middlename + " Lastname:" + lastname + " Physicalfitness:" + physicalFitness );
}
pstm.executeBatch();
System.out.println("Imported");
//myConn.commit();
pstm.close();
myConn.close();
input.close();
}
catch (Exception exc) {
exc.printStackTrace();
throw new ServletException(exc);
}
}
}
I got the solution. The reason for time delay was due to 'AutoCommit' set to 'true' by default. So I set 'myConn.setAutoCommit(false);' before loop and then run the code. It took about 8 seconds to update db for 2000 records which was about 2 minutes earlier. Below is the code for reference -
package com.company.testdata;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class UpdateDataCopy {
public static void main(String[] args) throws Exception {
String user = "root";
String pass = "test";
String jdbcUrl = "jdbc:mysql://192.1.2.1/db_bro_mumbai?useSSL=false";
String driver = "com.mysql.jdbc.Driver";
try {
PreparedStatement pstm = null;
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
FileInputStream input = new FileInputStream("E:\\Work\\TestData.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(input);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row;
myConn.setAutoCommit(false);
/*final int batchSize = 1000;
int count = 0;*/
long start = System.currentTimeMillis();
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = (XSSFRow) sheet.getRow(i);
int id = (int)row.getCell(0).getNumericCellValue();
System.out.println(id);
String firstname = row.getCell(2).getStringCellValue();
System.out.println(firstname);
String middlename = row.getCell(3).getStringCellValue();
System.out.println(middlename);
String lastname = row.getCell(4).getStringCellValue();
System.out.println(lastname);
int physicalFitness = (int)row.getCell(25).getNumericCellValue();
System.out.println(physicalFitness);
String sql = "UPDATE fitness_details as p SET p.physicalFitness = ? "
+ " WHERE CandidateID_FK1 = ?";
pstm = (PreparedStatement) myConn.prepareStatement(sql);
pstm.setInt(1, physicalFitness);
pstm.setInt(2, id);
pstm.addBatch();
pstm.executeBatch();
System.out.println("Import rows " + i);
}
System.out.println("Time Taken="+(System.currentTimeMillis()-start));
myConn.commit();
myConn.setAutoCommit(true);
pstm.close();
myConn.close();
input.close();
}
catch (Exception exc) {
exc.printStackTrace();
throw new ServletException(exc);
}
}
}
I want to use select max from a table. I want to use a PreparedStatement. I have a composite primary key which consists of the t.v series and the epo number. When I add new epo it will for table and bring the t.v series code from guidline table the content of all the programs and the code for each and then add to the new table. I want it to get the last epo by getting the max and then increment +1 "an automation app".
So how can I select max where id =??
If you get me its like
pstm2=con.prepareStatement(max);
String max="select MAX(epono) as eponoo from archieve wwhere id like ? ";
This program would be helpful
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SelectRecordsUsingPreparedStatement {
public static Connection getConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#localhost:1521:databaseName";
String username = "name";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void main(String[] args) {
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "select deptno, deptname, deptloc from dept where deptno > ?";
pstmt = conn.prepareStatement(query); // create a statement
pstmt.setInt(1, 1001); // set input parameter
rs = pstmt.executeQuery();
// extract data from the ResultSet
while (rs.next()) {
int dbDeptNumber = rs.getInt(1);
String dbDeptName = rs.getString(2);
String dbDeptLocation = rs.getString(3);
System.out.println(dbDeptNumber + "\t" + dbDeptName + "\t" + dbDeptLocation);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
I'm trying to connect from a Google Endpoints server to a Google Cloud SQL server. I'm modifying the Greetings.getGreeting() method in this tutorial:
https://cloud.google.com/appengine/docs/java/endpoints/getstarted/backend/helloendpoints
to call the Cloud mysql database as demonstrated in this tutorial (see doGet method):
https://cloud.google.com/appengine/docs/java/cloud-sql/#enable_connector_j
I have made sure that I can connect to the database from my machine mysql client. The database instance "simple" has a single table "simpletable" who's rows hold an entityID and a string. (But I'm not able to connect, so that's not too important yet.)
This is my endpoints code:
package com.example.helloendpoints;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.response.NotFoundException;
import com.google.appengine.api.users.User;
import java.sql.*;
import java.util.ArrayList;
import javax.inject.Named;
/**
* Defines v1 of a helloworld API, which provides simple "greeting" methods.
*/
#Api(
name = "helloworld",
version = "v1",
scopes = {Constants.EMAIL_SCOPE},
clientIds = {Constants.WEB_CLIENT_ID,
Constants.ANDROID_CLIENT_ID,
Constants.IOS_CLIENT_ID,
Constants.API_EXPLORER_CLIENT_ID},
audiences = {Constants.ANDROID_AUDIENCE}
)
public class Greetings {
public static ArrayList<HelloGreeting> greetings = new ArrayList<HelloGreeting>();
static {
greetings.add(new HelloGreeting("hello world!"));
greetings.add(new HelloGreeting("goodbye world!"));
}
public HelloGreeting getGreeting(#Named("id") Integer id) throws NotFoundException {
// pair to use when running local endpoint server
String urlFromDev = "jdbc:mysql://173.194.XXX.90:3306/simple?user=root";
String classForNameFromDev = "com.mysql.jdbc.Driver";
// pair to use when running cloud endpoint server
String classForNameFromCloud = "com.mysql.jdbc.GoogleDriver";
String urlFromCloud = "jdbc:google:mysql://"
+ Constants.PROJECT_ID + ":"
+ Constants.CLOUD_SQL_INSTANCE_NAME +"/"
+ Constants.DATABASE_NAME + "?user=root";
HelloGreeting helloGreeting = new HelloGreeting();
try {
Class.forName(classForNameFromDev);
// Class.forName(classForNameFromCloud);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
Connection connection = DriverManager.getConnection(urlFromDev);
// Connection connection = DriverManager.getConnection(urlFromCloud);
try {
String statement = "Select simplestring from simpletable where entryID = ?";
PreparedStatement preparedStatement = connection.prepareStatement(statement);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
if (!resultSet.wasNull()) {
helloGreeting.setMessage(resultSet.getString("simplestring"));
} else {
throw new NotFoundException("Greeting not found with an index: " + id);
}
} finally {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
return helloGreeting;
}
#ApiMethod(name = "greetings.multiply", httpMethod = "post")
public HelloGreeting insertGreeting(#Named("times") Integer times, HelloGreeting greeting) {
HelloGreeting response = new HelloGreeting();
StringBuilder responseBuilder = new StringBuilder();
for (int i = 0; i < times; i++) {
responseBuilder.append(greeting.getMessage());
}
response.setMessage(responseBuilder.toString());
return response;
}
#ApiMethod(name = "greetings.authed", path = "hellogreeting/authed")
public HelloGreeting authedGreeting(User user) {
HelloGreeting response = new HelloGreeting("hello " + user.getEmail());
return response;
}
}
I have tried to enable mysql connector/j in my appengine-web.xml
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<use-google-connector-j>true</use-google-connector-j>
<application>backendapitutorial-1XXX</application>
<version>${app.version}</version>
<threadsafe>true</threadsafe>
<system-properties>
<property name="java.util.logging.config.file" value="WEB- INF/logging.properties"/>
</system-properties>
</appengine-web-app>
Whichever way I build+depl0y it (Dev or cloud), I always get
java.sql.SQLException: No suitable driver found for jdbc:mysql://173.194.XXX.90:3306/simple?user=root
or
java.sql.SQLException: No suitable driver found for jdbc:google:mysql://backendapitutorial-XXXX:simple/simple?user=root
(I replaced the real IP and project name with "X"s for this post).
I've already looked at these:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname
ClassNotFoundException: com.mysql.jdbc.GoogleDriver
What does 'Class.forName("org.sqlite.JDBC");' do?
I'm building with Maven and working on IntelliJ IDE.
Any help is greatly appreciated. Thanks.
I am making a web application project using JSP in Netbeans IDE.
I have a java Class called Login which has a static method called authenticate.When I am running this file it gives me the required output. Now I have a web page called auth.jsp which calls the method authenticate but when I try to run this web page the value returned by the method is "error" that is sql exception is being thrown by the method. Could someone please tell why this is happening? Thanks in advance.
package server;
import java.sql.*;
public class Login {
public static void main(String args[]) {
System.out.print(authenticate("260","abc"));
}
public static String authenticate(String username, String password) {
String auth="",pass="";
int blocked_status=0;
String url = "jdbc:mysql://localhost:3306/radio";
try{
Connection conn = DriverManager.getConnection(url,"root","rishabh");
Statement stmt = conn.createStatement();
String sql = "select password,blocked from user where username = \"" + username + "\"";
ResultSet rs = stmt.executeQuery(sql);
int flag=0;
while(rs.next()){
pass = rs.getString("password");
blocked_status = rs.getInt("blocked");
flag++;
}
if(flag>0) {
if(blocked_status==1)
auth = "blocked";
else if(pass.equals(password))
auth = "authenticated";
else if(pass.equalsIgnoreCase(pass))
auth = "wrong_case";
else
auth = "wrong_password";
}
else{
auth = "incorrect_username";
}
} catch(SQLException e){
auth = "sqlerror";
System.out.print(" ERROR " );
}
return auth;
}
}