Working on a project where I am trying to allow a user to enter an ISBN on the client (LibrarySystem), and when the button searchARL is pressed, it sends the ISBN to the server (ARLibrary). If the ISBN is present in the ARLibrary, it tells the client its available. If it doesn't exist in the ARLibrary database, it tells the client that the ISBN does not exist.
My problem is that I cannot seem to establish a connection between my server/client. I really have no idea what I am doing wrong but any help would be appreciated.
UPDATE: It seems like I DID get them to connect, but on line 164:
String resultFromARLibrary = (String) inputStream.readObject();
I am getting an exception that states:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
How do I go about fixing this?
Server code:
import java.net.ServerSocket;
import java.net.Socket;
import java.net.InetAddress;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import javax.swing.JOptionPane;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class ARLibraryServer{
private ServerSocket serverSocket;
private Socket socket;
private ObjectInputStream inputStream;
private ObjectOutputStream outputStream;
private ResultSet result;
public ARLibraryServer(){
String URL = "jdbc:mysql://localhost/mulibrary?user=root&password=";
System.out.println("Server is running...");
try{
serverSocket = new ServerSocket(1098, 500);
while(true){
socket = serverSocket.accept();
inputStream = new ObjectInputStream(socket.getInputStream());
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(URL);
int isbn = (int) inputStream.readObject();
socket = new Socket(InetAddress.getByName("localhost"), 1097);
outputStream = new ObjectOutputStream(socket.getOutputStream());
String messageMU = "ISBN: " + isbn +
"\nAvailable at Arlington Library";
Statement search_arlingtonrs = con.createStatement();
String sql_statement = "select title from book where isbn = "+isbn+"";
result = search_arlingtonrs.executeQuery(sql_statement);
int iffound = 0;
while(result.next()) {
iffound = 1;
System.out.println(result.getString(1));
outputStream.writeObject("ISBN: " +isbn+
"\nTitle: " + result.getString(1) +
"\nAvailable at Arlington Library");
outputStream.flush();
}
if (iffound == 0){
String notfound = "ISBN: " +isbn+ "is not available at Arlington Library.";
outputStream.flush();
}
}
}
catch(ClassNotFoundException e){e.printStackTrace();}
catch(SQLException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
public static void main(String [] args){
new ARLibraryServer();
}
}
Client Code:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.net.Socket;
import java.net.InetAddress;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.io.ObjectInputStream;
//COMMANDS USED TO CREATE DATABASE:
//Applications/XAMPP/bin/mysql -u root
//show databases;
//create database mulibrary;
//use mulibrary;
//create table book (
//isbn char(9) primary key not null,
//title varchar(25));
public class LibrarySystem extends JFrame implements ActionListener{
private JLabel isbnLabel, titleLabel;
private JTextField isbnField, titleField;
private JButton addBook, searchMU, searchARL;
private JPanel centerPanel, centerPanel2, southPanel;
private ServerSocket serverSocket;
private Socket socket;
private ObjectInputStream inputStream;
private ObjectOutputStream outputStream;
private ResultSet result;
public LibrarySystem() {
isbnLabel = new JLabel("ISBN:");
titleLabel = new JLabel("Title:");
centerPanel = new JPanel();
centerPanel2 = new JPanel();
isbnField = new JTextField(15);
titleField = new JTextField(15);
centerPanel.add(isbnLabel);
centerPanel.add(isbnField);
centerPanel.add(titleLabel);
centerPanel.add(titleField);
centerPanel2.add(centerPanel);
centerPanel.setLayout(new GridLayout(2,2));
add(centerPanel2, BorderLayout.CENTER);
addBook = new JButton("Add New Book:");
addBook.addActionListener(this);
searchMU = new JButton("Search ISBN - MU Library");
searchMU.addActionListener(this);
searchARL = new JButton("Search ISBN - Arlington Library");
searchARL.addActionListener(this);
southPanel = new JPanel();
southPanel.add(addBook);
southPanel.add(searchMU);
southPanel.add(searchARL);
add(southPanel, BorderLayout.SOUTH);
setTitle("Library System");
setSize(600, 150);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event) {
String URL = "jdbc:mysql://localhost/mulibrary?user=root&password=";
if(event.getSource()==addBook){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(URL);
String isbnint = isbnField.getText();
int isbn = Integer.parseInt(isbnint);
String title = titleField.getText();
String output = "The following book has been added to the Marymount Library:" +
"\nISBN: " + isbn +
"\nTitle: " + title;
String insert_add = "insert into book (isbn, title) values ('"+isbn+"','"+title+"')";
Statement add = con.createStatement();
add.execute(insert_add);
System.out.println("Insert Successful.");
JOptionPane.showMessageDialog(null, output);
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
catch(SQLException e){
e.printStackTrace();
}
}
else if(event.getSource()==searchMU){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(URL);
String isbnint = isbnField.getText();
int isbn = Integer.parseInt(isbnint);
String title = titleField.getText();
Statement search_marymount = con.createStatement();
String sql_statement = "select title from book where isbn = "+isbn+"";
ResultSet result = search_marymount.executeQuery(sql_statement);
int lookfor = 0;
while(result.next()){
lookfor = 1;
System.out.println(result.getString(1));
JOptionPane.showMessageDialog(null, "ISBN: " + isbn + "\nTitle: " +
result.getString(1) + "\nAvailable at MU Library");
}
if(lookfor == 0){
String notfound = "ISBN: " + isbn + " is not available at MU Library.";
JOptionPane.showMessageDialog(null, notfound);
}
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
catch(SQLException e){
e.printStackTrace();
}
}
else if(event.getSource()==searchARL){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(URL);
String isbnint = isbnField.getText();
int isbn = Integer.parseInt(isbnint);
String title = titleField.getText();
serverSocket = new ServerSocket(1098, 500);
while(true){
socket = new Socket(InetAddress.getByName("localhost"), 1098);
outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.writeObject(isbn);
outputStream.flush();
System.out.println("Message has been sent.");
socket = serverSocket.accept();
inputStream = new ObjectInputStream(socket.getInputStream());
String resultFromARLibrary = (String) inputStream.readObject();
JOptionPane.showMessageDialog(null, resultFromARLibrary);
}
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
catch(SQLException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
}
}
public static void main(String [] args){
LibrarySystem app = new LibrarySystem();
}
}
An attempt you can try is to replace localhost with 127.0.0.1
Related
Tried below code but receiving Data Provider Mismatch error. Could anyone help out on this?
package appModules;
import org.testng.annotations.Test;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.BeforeTest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
public class NewTest {
public WebDriver driver;
public WebDriverWait wait;
String appURL =
"https://dev.agencyport.rsagroup.ca:8443/agencyportal/ProcessLogoff";
//Locators
private By username = By.id("USERID");
private By password = By.id("PASSWORD");
#BeforeClass
public void testSetup() {
System.setProperty("webdriver.firefox.marionette",
"C:\\Automation\\geckodriver.exe");
driver=new FirefoxDriver();
driver.manage().window().maximize();
wait = new WebDriverWait(driver, 5);
}
#Test(dataProvider = "login")
public void Login(String Username, String Password) {
driver.findElement(username).sendKeys(Username);
driver.findElement(password).sendKeys(Password);
}
#DataProvider (name="login")
public Object[][] dp() throws Exception{
Object[][] arrayObject =
getExcelData("C:\\Automation\\testData.xls","New");
return arrayObject;
}
public String[][] getExcelData(String fileName, String sheetName) throws
Exception {
String[][] arrayExcelData = null;
try {
FileInputStream fs = new FileInputStream(fileName);
Workbook wb = Workbook.getWorkbook(fs);
Sheet sh = wb.getSheet(sheetName);
int totalNoOfCols = sh.getColumns();
System.out.println(totalNoOfCols);
int totalNoOfRows = sh.getRows();
System.out.println(totalNoOfRows);
arrayExcelData = new String[totalNoOfRows-1][totalNoOfCols];
for (int i=1 ; i <totalNoOfRows; i++) {
for (int j=0; j <totalNoOfCols; j++) {
arrayExcelData[i-1][j] = sh.getCell(j, i).getContents();
System.out.println(arrayExcelData[i-1][j]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
return arrayExcelData;
}
#Test
public void tearDown() {
driver.quit();
}
}
Received below error -
org.testng.internal.reflect.MethodMatcherException:
Data provider mismatch
Method: Login([Parameter{index=0, type=java.lang.String,
declaredAnnotations=[]}, Parameter{index=1, type=java.lang.String,
declaredAnnotations=[]}])
Arguments: [(java.lang.String) agent,(java.lang.String) password,
(java.lang.String) ]
atorg.testng.internal.reflect.DataProviderMethodMatcher.getConformingArguments(DataProviderMethodMatcher.java:45)
at org.testng.internal.Parameters.injectParameters(Parameters.java:796)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:982)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)`
You are passing return value of arrayObject with incorrect Data Type,
You need to get String value from Excel File in Data Provider Method, and That you need to pass in Object.
Refer below Example, for Reference:
#DataProvider
public Iterator<Object[]> getTestData()
{
ArrayList<Object[]> testdata = new ArrayList<Object[]>();
try {
reader = new excelUtility(excelTestDataFile);
} catch (Exception e) {
e.printStackTrace();
}
sheetName = className;
for (int rowNumber = 2; rowNumber <= reader.getRowCount(sheetName); rowNumber++) {
String caseNo = reader.getCellData(sheetName, "Case", rowNumber);
String emailid = reader.getCellData(sheetName, "Email ID", rowNumber);
String password = reader.getCellData(sheetName, "Password", rowNumber);
String message = reader.getCellData(sheetName, "Expected Result", rowNumber);
Object ob[] =
{ caseNo, emailid, password, message };
testdata.add(ob);
}
return testdata.iterator();
}
And this is the #Test Receiver of Data Provider:
#Test(dataProvider = "getTestData")
public void calllogin(String caseNO, String emailid, String password, String expectedResult) throws Exception
{
******
}
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'm sure it's just a minor problem but I can't figure out what I need to change: I have a register page in my app. When the user inserts data, the data is passed to php script and stored in MYSQL database. The connection works as I get a new user in the db, but the json $success doesn't work - I want to make a Toast and change to a new activity if the user could register, but it does nothing when I click on the button.
Here is my Java Code:
package com.example.android.festivalapp;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class JetztRegistrieren extends Startseite {
Button bRegistrierungAbschliessen;
EditText etUserName, etUserMail, etUserPasswort, etUserPasswort2, etGeburtsdatum, etTelefonnummer;
RadioButton rbMaennlich, rbWeiblich;
RadioGroup rgGeschlecht;
protected String enteredname, enteredemail, enteredpassword, enteredpassword2, enteredGeb, enteredTelnr, userGender;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jetzt_registrieren);
bRegistrierungAbschliessen = (Button) findViewById(R.id.bRegistrierungAbschliessen);
etUserName = (EditText) findViewById(R.id.etUserName);
etUserMail = (EditText) findViewById(R.id.etUserMail);
etUserPasswort = (EditText) findViewById(R.id.etUserPasswort);
etUserPasswort2 = (EditText) findViewById(R.id.etUserPasswort2);
etGeburtsdatum = (EditText) findViewById(R.id.etGeburtsdatum);
etTelefonnummer = (EditText) findViewById(R.id.etTelefonnummer);
rgGeschlecht = (RadioGroup) findViewById(R.id.rgGeschlecht);
rbMaennlich = (RadioButton) findViewById(R.id.rbMaennlich);
rbWeiblich = (RadioButton) findViewById(R.id.rbWeiblich);
bRegistrierungAbschliessen.setOnClickListener(new View.OnClickListener() {
//testen, ob Mail und Passwort ausgefüllt oder lang genug
#Override
public void onClick(View v) {
enteredname = etUserName.getText().toString();
enteredemail = etUserMail.getText().toString();
enteredpassword = etUserPasswort.getText().toString();
enteredpassword2 = etUserPasswort2.getText().toString();
enteredTelnr = etTelefonnummer.getText().toString();
enteredGeb = etGeburtsdatum.getText().toString();
userGender = ((RadioButton) findViewById(rgGeschlecht.getCheckedRadioButtonId())).getText().toString();
String serverUrl = "http://www.pou-pou.de/stagedriver/android/register.php";
AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute(serverUrl, enteredname, enteredemail, enteredpassword, enteredpassword2, enteredTelnr, enteredGeb, userGender);
if (enteredname.equals("") || enteredemail.equals("") || enteredpassword.equals("") || enteredpassword2.equals("") || enteredGeb.equals("")) {
Toast.makeText(JetztRegistrieren.this, "Bitte alle Felder ausfüllen", Toast.LENGTH_LONG).show();
return;
}
}
class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost("http://www.pou-pou.de/stagedriver/android/register.php");
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("enteredname", params[1]));
nameValuePairs.add(new BasicNameValuePair("enteredemail", params[2]));
nameValuePairs.add(new BasicNameValuePair("enteredpassword", params[3]));
nameValuePairs.add(new BasicNameValuePair("enteredpassword2", params[4]));
nameValuePairs.add(new BasicNameValuePair("enteredTelnr", params[5]));
nameValuePairs.add(new BasicNameValuePair("enteredGeb", params[6]));
nameValuePairs.add(new BasicNameValuePair("userGender", params[7]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
int jsonResult = returnParsedJsonObject(result);
if (jsonResult == 0) {
Toast.makeText(JetztRegistrieren.this, "Passwörter stimmen nicht überein", Toast.LENGTH_LONG).show();
return;
}
if (jsonResult == 1) {
Intent intent = new Intent(JetztRegistrieren.this, Startseite.class);
Toast.makeText(JetztRegistrieren.this, "Willkommen bei Stage Driver! Jetzt loslegen.", Toast.LENGTH_LONG).show();
startActivity(intent);
return;
}
System.out.println("Resulted Value: " + result);
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
private int returnParsedJsonObject(String result) {
JSONObject resultObject = null;
int returnedResult = 2;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
});
}
}
And this is the php file:
<?php
include('config.php');
session_start();
$name = $_POST["enteredname"];
$pass = $_POST["enteredpassword"];
$pass2 = $_POST["enteredpassword2"];
$email = $_POST["enteredemail"];
$tel = $_POST["enteredTelnr"];
$geb = $_POST["enteredGeb"];
$gender = $_POST["userGender"];
if($pass != $pass2) {
$success = 0;
}
else {
$hash = md5($pass);
$speichern = "INSERT INTO user (user_name, user_pw, user_mail, user_tel, user_geb, user_geschl)
VALUES('$name', '$hash', '$email', '$tel', '$geb', '$gender');";
mysql_query($speichern) or die(mysql_error());
if($speichern) {
$success = 1;
}
}
echo json_encode($success);
?>
Thanks in advance!
The problem is that you are not returning an HTTP header for the content type you are returning.
Add this to the top of your php script:
header("Content-Type: application/json;charset=utf-8");
So I think I found the error, in the log it says the jsonresult cannot be converted, it's because in the php script I wrote $success = 0; but instead I think it has to be something like $response["success"] = 0;
I had a problem in my servlet regarding deleting record from my database.
Please look over my servlet code and please do correct me. Thank you in advance
DeleteRow servlet is working perfectly right when a single ID is given manually.
Scenario is:
ManageSinger.java servlet displays the records in database along with a "Delete" hyperLink in every row. But problem is whenever i try to press delete button.. it receives a null value for ID in deleterow.java servlet ..
Please guide me from here how can only that corresponding ID can be pass to another servlet.
ManageSinger.java
package com.ea.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class ManageSinger extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<html><body>");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/EATWO","root","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from singerdetails");
out.println("<form method = \"post\">");
out.println("<table border=1 width=50% height=50%>");
out.println("<tr><th align=\"center\">Singer Name</th><th align=\"center\">StageName</th><th align=\"center\">Language</th><th></th><tr>");
while (rs.next()) {
String singername = rs.getString("singername");
String stagename = rs.getString("stagename");
String language = rs.getString("language");
String id = rs.getString("userID");
HttpSession session = req.getSession(true);
session.setAttribute("userID",id);
out.println("<tr><td align=\"center\">" + singername + "</td><td align=\"center\">" + stagename + "</td><td align=\"center\">" + language + "</td><td align=\"center\">Delete</td></tr>");
}
out.println("</table>");
out.println("</form");
out.println("</body></html>");
con.close();
}
catch (Exception e) {
e.printStackTrace();
}finally{
}
}
}
DeleteRow.java
package com.ea.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.jws.Oneway;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class DeleteRow extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Connection con;
PreparedStatement st;
ResultSet rs;
try
{
HttpSession session = req.getSession(true);
Class.forName("com.mysql.jdbc.Driver");
String id = (String) session.getAttribute("id");
System.out.println(id);
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/EATWO","root","");
st= con.prepareStatement("delete from singerdetails where userID = ?");
st.setString(1, id);
st.executeUpdate();
int i = st.executeUpdate();
if(i!=0)
pw.println("Deleting row...");
else if (i==0)
{
pw.println("<br>Row has been deleted successfully.");
}
}
catch(SQLException sx)
{
pw.println(sx);
}
catch(ClassNotFoundException cx)
{
pw.println(cx);
}
}
}
In DeleteRow.java say you should do String id = (String) session.getAttribute("userID"); instead of (String) session.getAttribute("id") .In ManageSinger.java you are setting the attribute as follows session.setAttribute("userID",id);
As per your current ManageSinger.java only the last userID gets set in session, which is why the last userID gets deleted. In ManageSinger.java instead of setting the userID as session attribute you can set it as url parameter for each record.
Following lists the changes:
//HttpSession session = req.getSession(true);
//session.setAttribute("userID",id);
out.println("<tr><td align=\"center\">" + singername + "</td><td align=\"center\">" + stagename + "</td><td align=\"center\">" + language + "</td><td align=\"center\">Delete</td></tr>");
In DeleteRow.java instead of getting the userID from session, you can get it from the url as following:
//HttpSession session = req.getSession(true);
//String id = (String) session.getAttribute("id");
String id = req.getParameter("userID").toString();
I have a problem with google docs. I want to retrieve all your files by using OAuth 2.0. The problem is that once you do, and authorization when trying to download a file gives me this error:
Exception in thread "main" java.lang.NullPointerException
at GoogleBlack.readUrl(GoogleBlack.java:95)
at GoogleBlack.getDocument(GoogleBlack.java:87)
at GoogleBlack.go(GoogleBlack.java:187)
at GoogleBlack.main(GoogleBlack.java:222)
Here's the code I use
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.GoogleAuthTokenFactory.UserToken;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.util.ServiceException;
public class GoogleBlack {
private static final String APPLICATION_NAME = "Homework";
public DocsService service;
public GoogleService spreadsheetsService;
static String CLIENT_ID = "***********";
static String CLIENT_SECRET = "**************";
static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
static List<String> SCOPES = Arrays.asList("https://docs.google.com/feeds");
public void getSpreadSheet(String id, String i, String ids, String type) throws Exception {
UserToken docsToken = (UserToken) service.getAuthTokenFactory()
.getAuthToken();
UserToken spreadsheetsToken = (UserToken) spreadsheetsService
.getAuthTokenFactory().getAuthToken();
service.setUserToken(spreadsheetsToken.getValue());
URL url = null;
if(type.equals("doc"))
{
url = new URL("https://docs.google.com/feeds/download/documents/Export?id="+ ids);
}
else
{
url = new URL("https://docs.google.com/feeds/download/spreadsheets/Export?key="+ ids +"&exportFormat="+ type + "&gid=0");
i += ".xls";
}
System.out.println("Spred = " + url.toString());
readUrl1(url.toString(), i, type);
service.setUserToken(docsToken.getValue());
}
public void readUrl1(String url, String i, String type) throws IOException, ServiceException
{
MediaContent mc = new MediaContent();
mc.setUri(url);
MediaSource ms = service.getMedia(mc);
System.out.println("Name: "+i);
BufferedInputStream bin = new BufferedInputStream(ms.getInputStream());
OutputStream out = new FileOutputStream(i);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
}
public void getDocument(String id, String i) throws Exception {
URL url = new URL(id);
readUrl(url,i);
}
public void readUrl(URL url, String i) throws Exception {
MediaContent mc = new MediaContent();
mc.setUri(url.toString());
System.out.println("Url "+ url.toString());
System.out.println("MC: " + mc.toString());
MediaSource ms = service.getMedia(mc);
System.out.println("Name: "+i);
BufferedInputStream bin = new BufferedInputStream(ms.getInputStream());
OutputStream out = new FileOutputStream(i);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
// FileOutputStream fout = null;
// fout = new FileOutputStream(i);
// fout.write(cbuf.);
// fout.close();
}
static Credential getCredentials() {
HttpTransport transport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
// Step 1: Authorize -->
String authorizationUrl =
new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URI, SCOPES).build();
// Point or redirect your user to the authorizationUrl.
System.out.println("Go to the following link in your browser:");
System.out.println(authorizationUrl);
// Read the authorization code from the standard input stream.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is the authorization code?");
String code = null;
try {
code = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Step 1 <--
// Step 2: Exchange -->
GoogleTokenResponse response = null;
try {
response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
code, REDIRECT_URI).execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Step 2 <--
// Build a new GoogleCredential instance and return it.
return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.setJsonFactory(jsonFactory).setTransport(transport).build()
.setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken());
}
public void go() throws Exception {
DocsService service = new DocsService(APPLICATION_NAME);
service.setOAuth2Credentials(getCredentials());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
DocumentListFeed feed = service.getFeed(feedUrl, DocumentListFeed.class);
System.out.println("Feed " + feed.getEntries().size());
for(int i = 0; i < feed.getEntries().size(); i++)
{
DocumentListEntry entry = feed.getEntries().get(i);
if(entry.getType().equals("file"))
{
MediaContent mc1 = (MediaContent) entry.getContent();
String UrlForDownload = mc1.getUri();
System.out.println("Type is: " + entry.getType());
System.out.println("File Name is: " + entry.getTitle().getPlainText());
System.out.println("URL "+ UrlForDownload);
getDocument(UrlForDownload, entry.getFilename());
}
else
{
MediaContent mc1 = (MediaContent) entry.getContent();
String UrlForDownload = mc1.getUri();
System.out.println("URL "+ UrlForDownload);
System.out.println("Type is: " + entry.getType());
System.out.println("File Name is: " + entry.getTitle().getPlainText());
if(entry.getTitle().getPlainText().equals("Web Design 2011/2012 - Материали"))
{
continue;
}
if(entry.getType().equals("spreadsheet"))
{
String name = entry.getTitle().getPlainText().replaceAll(" ", "");
System.out.println("name: " + name);
getSpreadSheet(UrlForDownload, name, entry.getDocId(),"xls");
}
else
{
String name = entry.getTitle().getPlainText().replaceAll(" ", "");
System.out.println("name: " + name);
getSpreadSheet(UrlForDownload, name, entry.getDocId(),"doc");
}
}
}
}
public static void main(String[] args) throws Exception {
new GoogleBlack().go();
}
}
95 row - MediaSource ms = service.getMedia(mc);
87 row - readUrl(url,i);
187 row - getDocument(UrlForDownload, entry.getFilename());
222 row - new GoogleBlack().go();
I apologize if I am not well explained!!!
You never initialized the "public DocsService service;" member of your GoogleBlack class, so when you call "service.getMedia(mc);" you're getting a NullPointerException.