In prepareStatement string value is not setting in its placeholder. help me to sort out this? - prepared-statement

This is my code and see the error help me. in this code i am trying to get username and password from table student1. by using preparedStatement but i am getting an error .
package jdbcMY;
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.Scanner;
public class demo {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Connection con = null;
try {
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/abhi", "root", "root");
String sql = "select * from student1 where username = ? ";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, "abhi");
ResultSet rs = ps.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
More details:
here is the table i created in mysql
here is the error that i got

Related

LoginFailed on connecting outlook 365

package com.email.test;
import java.util.Arrays;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class SampleEmailReader {
public static final int SUCCESS = 0;
public static final int FAILURE = -1;
private transient static final Logger logger = LoggerFactory.getLogger(SampleEmailReader.class);
public SampleEmailReader() {
}
public void processEmailAttachements() {
try {
logger.info("Started processEmailAttachements ");
Properties emailProperties = new Properties();
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
emailProperties.setProperty("mail.imaps.socketFactory.class", SSL_FACTORY);
emailProperties.setProperty("mail.imaps.socketFactory.fallback", "false");
emailProperties.setProperty("mail.imaps.port", "993");
emailProperties.setProperty("mail.imaps.socketFactory.port", "993");
emailProperties.setProperty("mail.imaps.auth", "true");
emailProperties.setProperty("mail.imaps.host", "outlook.office365.com");
emailProperties.setProperty("mail.imaps.auth.plain.disable", "true");
emailProperties.setProperty("mail.imaps.auth.gssapi.disable", "true");
emailProperties.setProperty("mail.imaps.auth.ntlm.disable", "true");
emailProperties.setProperty("mail.imaps.ssl.enable", "true");
Session session = Session.getInstance(emailProperties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("test#outlook.com", "password#2016");
}
});
Store store = session.getStore("imaps");
store.connect();
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
logger.info("Inbox MessageCount-->" + inbox.getMessageCount());
Message messages[] = inbox.search(new FlagTerm(
new Flags(Flag.SEEN), false));
logger.info("Number of UnRead Mails = " + messages.length);
for (Message inboxMessage : messages) {
int status = processMessageBody(inboxMessage);
if (status == SUCCESS) {
inboxMessage.setFlag(Flag.SEEN, true);
} else {
inboxMessage.setFlag(Flag.SEEN, false);
}
}
inbox.close(true);
store.close();
} catch (Exception ex) {
ex.printStackTrace();
logger.error("Error in processEmailAttachements", ex);
}
}
private int processMessageBody(Message message) {
int status = FAILURE;
try {
logger.info("Started processMessageBody*******");
logger.info("Message Subject******" + message.getSubject());
logger.info("From Address *******"
+ Arrays.toString(message.getFrom()));
Object content = message.getContent();
if (content instanceof String) {
logger.error("Invalid Content Type.No need to process the Mail with Subject "
+ message.getSubject());
} else if (content instanceof Multipart) {
Multipart multiPart = (Multipart) content;
try {
for (int i = 0; i < multiPart.getCount(); i++) {
BodyPart bodyPart = multiPart.getBodyPart(i);
if (bodyPart.getDisposition() != null
&& bodyPart.getDisposition().equalsIgnoreCase(
Part.ATTACHMENT)
&& bodyPart.getFileName() != null) {
status = readExcel(bodyPart);
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("BatchException in procesMultiPart", e);
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("Exception in processMessageBody", e);
}
return status;
}
public abstract int readExcel(BodyPart bodyPart);
}
Executing
package EmailTable;
import javax.mail.BodyPart;
public class Email {
public static void main(String[] args) {
// TODO Auto-generated method stub
SampleEmailReader reader = new SampleEmailReader() {
#Override
public int readExcel(BodyPart bodyPart) {
// TODO Auto-generated method stub
return 0;
}
};
reader.processEmailAttachements();
}
}
Getting Autheticate Failed.. But username password is correct. and i am able to login outlook 365 with the username and password. ONLY difference I am seeing there is certitificate displayed on the browser.. Do I need to use any certificate to read the mail?
javax.mail.AuthenticationFailedException: LOGIN failed.
at com.sun.mail.imap.IMAPStore.protocolConnect

Login JSP and servlet connect to database

I have a JSP login page within which I'm taking in username and password and they get passed to my servlet, which validates them using my users table in psaviour database, and then on success or failure, should forward them to the welcome page or back to the login.
Yet I'm stuck trying to connect to my database from my checklogin 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.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(urlPatterns = {"/checkLogin"})
public class checkLogin extends HttpServlet {
private final String DB_URL = "jdbc:mysql://localhost:3306/psaviour";
private final String JDBC_DRIVER="com.mysql.jdbc.Driver";
private final String USER = "root";
private final String PASS = "root";
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");//.toString();
String passkey = request.getParameter("passkey");//.toString();
try {
Class.forName(JDBC_DRIVER);
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt=conn.prepareStatement("SELECT * FROM users WHERE 'username' =
? AND 'passkey' = ?");
stmt.setString(1, username);
stmt.setString(2, passkey);
rs = stmt.executeQuery();
} catch (SQLException e){
e.printStackTrace();
} catch (ClassNotFoundException ce){
ce.printStackTrace();
}
}
while (rs.next()){
//need to point to my welcome.jsp page or
}
//otherwise reload login page....
}
}
How about this?
if (rs.next()){
//need to point to my welcome.jsp page or
RequestDispatcher dispatch = request.getRequestDispatcher("/welcome.jsp");
dispatch.forward(request, response);
} else {
//otherwise reload login page....
request.setAttribute("errorMessage", "Authentication failure!");
response.sendRedirect("/login");
}
if (rs.next()){
response.sendRedirect("success.html");
return;
} else {
//otherwise reload login page...
response.sendRedirect("login.html");
return;
}

Read Excel data and use it in selenium

This script is to read data from excel and use it in selenium script. This uses Apache POI to read the data, store it in variables and use it.
You can try following code. I have taken facebook as sample application.
package testPackage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.*;
import org.testng.annotations.DataProvider;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class ExcelReadingwithDP {
WebDriver driver;
#BeforeTest
public void OpenApp()
{
System.setProperty("webdriver.chrome.driver", "E:/Selenium/Webdriver/Softwares/chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("http://facebook.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#Test(dataProvider="empLogin")
public void login(String username, String password)
{
WebElement login1 = driver.findElement(By.id("email"));
login1.clear();
login1.sendKeys(username);
WebElement passwd=driver.findElement(By.id("pass"));
passwd.clear();
passwd.sendKeys(password);
driver.findElement(By.xpath("//*[#id='u_0_q']")).click();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
WebElement back = driver.findElement(By.xpath("//*[#id='blueBarDOMInspector']/div/div[1]/div/div/h1/a/i"));
back.click();
}
#DataProvider(name="empLogin")
public Object[][] logindata()
{
Object[][] arrayobject = getexceldata("E://Deepak/IntranetLogin.xls","Sheet1");
return arrayobject;
}
public String[][] getexceldata(String filename, String sheetname)
{
String[][] arrayexceldata = null;
try
{
FileInputStream fis = new FileInputStream(filename);
Workbook wb = Workbook.getWorkbook(fis);
Sheet sh = wb.getSheet(sheetname);
int row = sh.getRows();
int col = sh.getColumns();
arrayexceldata = new String[row-1][col];
for (int i=1;i< row;i++)
{
for(int j=0;j<col;j++)
{
arrayexceldata[i-1][j]=sh.getCell(j,i).getContents();
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
return arrayexceldata;
}
}
/*
* Download Apache POI from https://www.apache.org/dyn/closer.lua/poi/release/bin/poi-bin-3.16-20170419.zip
*
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FormFill {
public static void main(String[] args) throws Exception {
try {
FileInputStream fileInputStream = new FileInputStream("C:\\data.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet("sheet1");
HSSFRow row1 = worksheet.getRow(0);
HSSFCell cellA1 = row1.getCell((short) 0);
String a1Val = cellA1.getStringCellValue();
HSSFCell cellB1 = row1.getCell((short) 1);
String b1Val = cellB1.getStringCellValue();
System.out.println("A1: " + a1Val);
System.out.println("B1: " + b1Val);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String url = "http://thedemosite.co.uk/addauser.php";
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(url);
//Thread.sleep(30000);
driver.findElement(By.name("username")).sendKeys(a1Val);
driver.findElement(By.name("password")).sendKeys(b1Val);
}
}
I feel csv is better than Excel because Excel more time to read the data but csv is fast.
private static final String CSV_SEPARATOR = ",(?=(?:[^\"]\"[^\"]\")[^\"]$)";
public List<String[]> parseFile(String fileName) {
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
br.readLine(); // skip header;
String line = br.readLine();
List<String[]> lines = new ArrayList();
while (line != null) {
//System.out.println(line.toString());
lines.add(line.split(CSV_SEPARATOR));
line = br.readLine();
}
return lines;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

how to export and import realm data in android

I know there are those questions which are similar to mine have already raised.
However, I can not go further more on some point.
** I can not copy file on below.-> realm.writeCopyTo(exportRealmFile);
** The code that I referred to is below.
https://stackoverflow.com/a/36324183/6650123
And let me share my application class which I defaulted Realm.
Wondering if the realm file can not be copied because of that..
Would you take a look and advise?
**
public class MyApplication extends Application {
private static MyApplication singleton;
private RealmConfiguration realmConfig;
String TAG=getClass().getName();
public static MyApplication getSingleton(){;
return singleton;
}
public void onCreate() {
super.onCreate();
singleton=this;
// Create the Realm configuration
realmConfig = new RealmConfiguration.Builder(this).build();
Realm.setDefaultConfiguration(realmConfig);
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public void onLowMemory() {
super.onLowMemory();
}
public void onTerminate() {
super.onTerminate();
}
}
// my codes for backup realm
package com.first.project;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import io.realm.Realm;
public class RealmBackupRestore {
private final static String TAG = RealmBackupRestore.class.getName();
private Context context;
private Realm realm;
public RealmBackupRestore(Context context) {
realm= Realm.getDefaultInstance();
//this.realm = Realm.getInstance(BaseApplication.realmConfiguration);
this.context = context;
}
public void backup() {
Log.d(TAG, "realm은"+realm);
Log.d(TAG, "Realm.getDefaultInstance();은"+Realm.getDefaultInstance());
File exportRealmFile = null;
File exportRealmPATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.d(TAG, "exportRealmPATH"+exportRealmPATH);
String exportRealmFileName = "aa.realm";
Log.d(TAG, "Realm DB Path = " + realm.getPath());
try {
// create a backup file
exportRealmFile = new File(exportRealmPATH, exportRealmFileName);
// if backup file already exists, delete it
exportRealmFile.delete();
// copy current realm to backup file
realm.writeCopyTo(exportRealmFile);
} catch (IOException e) {
e.printStackTrace();
}
String msg = "File exported to Path: " +Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
Log.d(TAG, msg);
realm.close();
}
public void restore() {
//Restore
File exportRealmPATH = context.getExternalFilesDir(null);
String FileName = "default.realm";
String restoreFilePath = context.getExternalFilesDir(null) + "/" + FileName;
Log.d(TAG, "oldFilePath = " + restoreFilePath);
copyBundledRealmFile(restoreFilePath, FileName);
Log.d(TAG, "Data restore is done");
}
private String copyBundledRealmFile(String oldFilePath, String outFileName) {
try {
File file = new File(context.getFilesDir(), outFileName);
Log.d(TAG, "context.getFilesDir() = " + context.getFilesDir().toString());
FileOutputStream outputStream = new FileOutputStream(file);
FileInputStream inputStream = new FileInputStream(new File(oldFilePath));
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, bytesRead);
}
outputStream.close();
return file.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String dbPath() {
return realm.getPath();
}
}

ArrayIndexOutOfBoundsException error when writing to a tag

I followed a tutorial on how to write a NDEF message to a tag. and now when I run it. it detects the tag and when I press the button to write the message and the app crashes. it gives me JAVA.LANG.ArrayIndexOutOfBoundsException can someone please help me on what I'm doing wrong.
this is the error I see in logcat.
any help is appreciated.
Here is the code:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class WriteMessage extends Activity {
NfcAdapter adapter;
PendingIntent pendingIntent;
IntentFilter writeTagFilters[];
boolean writeMode;
Tag myTag;
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_message);
ctx=this;
Button WriteTag = (Button) findViewById (R.id.WriteTag);
final TextView Message = (TextView) findViewById (R.id.MessageBox);
WriteTag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
if(myTag==null){
Toast.makeText(ctx, "Error_detected", Toast.LENGTH_LONG).show();
}else{
write(Message.getText().toString(), myTag);
Toast.makeText(ctx, "Ok_Writing", Toast.LENGTH_LONG).show();
}
}catch(IOException e){
Toast.makeText(ctx, "Error_Writing", Toast.LENGTH_LONG).show();
e.printStackTrace();
//} catch(FormatException e){
e.printStackTrace();
} catch (FormatException e) {
// TODO Auto-generated catch block
Toast.makeText(ctx, "Error_Writing", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
adapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent (this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter (NfcAdapter.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
writeTagFilters = new IntentFilter[] {tagDetected };
}
private void write(String text, Tag myTag)throws IOException, FormatException {
NdefRecord[] records = {createRecord(text)};
NdefMessage message = new NdefMessage(records);
Ndef ndef = Ndef.get(myTag);
ndef.connect();
ndef.writeNdefMessage(message);
ndef.close();
}
private NdefRecord createRecord (String text ) throws UnsupportedEncodingException {
String lang = "en";
byte[] textBytes = text.getBytes();
byte[] langBytes = lang.getBytes("US-ASCII");
int langLength = langBytes.length;
int textLength = textBytes.length;
byte[] payload = new byte [1+ langLength + textLength ];
payload[0] = (byte) langLength;
System.arraycopy(langBytes, 0, payload, 1, langLength);
System.arraycopy(langBytes, 0, payload, 1 + langLength, textLength);
NdefRecord recordNFC = new NdefRecord (NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);
return recordNFC;
}
#Override
protected void onNewIntent(Intent intent){
if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Toast.makeText(this, "ok_detection" + myTag.toString(), Toast.LENGTH_LONG ).show();
}
}
#Override
public void onPause(){
super.onPause();
WriteModeOff();
}
#Override
public void onResume(){
super.onResume();
WriteModeOn();
}
private void WriteModeOn(){
writeMode = true;
adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
}
private void WriteModeOff(){
writeMode = false;
adapter.disableForegroundDispatch(this);
}
}
Looks like createRecord() is copying langBytes into payload twice instead of copying textBytes, but with the length of textBytes. If textBytes is longer than langBytes, it won't find enough data to copy from the source.
See the documentation on arraycopy.

Resources