FileNotFoundException in Netbeans on a Web Service running on Glass Fish server - java

This the event handler when the button is clicked on GUI. Implements the declared
#WebMethod in class.
private void btn_loginActionPerformed(java.awt.event.ActionEvent evt) {
int result;
String username = us_textField.getText();
String password = new String(pw_textField.getPassword());
try {
result = employeeLogin(username, password);
} catch (IOException_Exception ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
result = 0;
} catch (FileNotFoundException_Exception ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
result = 0;
} catch (ClassNotFoundException_Exception ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
result = 0;
}
if (result == 0) {
lbl_loginStatus.setText("Invalid Inputs");
} else if (result == 1) {
lbl_loginStatus.setText("Username and password does not match!");
} else {
lbl_loginStatus.setText("Login Successful!");
new Choose().setVisible(true);
this.dispose();
}
}
This how the web service is declared in the same class.
private static int employeeLogin(java.lang.String username, java.lang.String password) throws IOException_Exception, FileNotFoundException_Exception, ClassNotFoundException_Exception {
ws_employee.CWWsEmployee_Service service = new ws_employee.CWWsEmployee_Service();
ws_employee.CWWsEmployee port = service.getCWWsEmployeePort();
return port.employeeLogin(username, password);
}
This is the Web Service Code.
EmployeeMainController controller = new EmployeeMainController();
#WebMethod(operationName = "EmployeeLogin")
public int EmployeeLogin(#WebParam(name = "username") String username, #WebParam(name = "password") String password) throws IOException, FileNotFoundException, ClassNotFoundException {
//TODO write your implementation code here:
return controller.EmployeeLogin(username, password);
}
This is the EmployeeLogin(username, password) method declared in EmployeeMainController.java class. During this method a ArrayList initialized by LoadData() method.
public int EmployeeLogin(String username, String password) throws FileNotFoundException, IOException, ClassNotFoundException {
// Loading to the array list from the text file.
ArrayList<EmployeeStruct> loadArray = new ArrayList<EmployeeStruct>();
loadArray = LoadList();
for (EmployeeStruct val : loadArray) {
if (val.getEmpUsername().equals(username) && val.getEmpPassword().equals(password)) {
return 2;
} else if (val.getEmpUsername().equals(username) || val.getEmpPassword().equals(password)) {
return 1;
}
}
return 0;
}
The LoadData() method is declared as below. This is simply a deserializing method. A have initialized the file path as this public static String filename = "cw_employeeData.txt";
public ArrayList<EmployeeStruct> LoadList() throws FileNotFoundException, IOException, ClassNotFoundException {
ArrayList<EmployeeStruct> employeeList = new ArrayList<EmployeeStruct>();
File file = new File(filename);
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
EmployeeStruct x = (EmployeeStruct) ois.readObject();
// System.out.println(x.toString());
employeeList.add(x);
}
} catch (EOFException e) {
// TODO Auto-generated catch block
System.out.println("Completed reading from the file " + filename);
}
// employeeList.add(admin);
return employeeList;
}
But when the code is executed, ws_employee.FileNotFoundException_Exception: cw_employeeData.txt (The system cannot find the file specified)... error comes in the console.
Even I have located the cw_employeeData.txt file in the root directory alongside the Root/src folder.

Related

Print To File in Java

i have a problem in my java exercise.
i need to print a multiply contact information to a file, but when i print more then 1 contact, only 1 contact is displayed in the file..
i tried to debug that but i cant find any mistake
i will put the code of my classes here:
This is Demo Class which i run the code from
public class Demo {
public static void main(String[] args) {
System.out.println("Insert number of Contacts:");
Scanner scanner = new Scanner(System.in);
int val = scanner.nextInt();
Contact[] contacts = new Contact[val];
for(int i = 0 ; i < val; i++) {
System.out.println("Contact #"+(i+1));
System.out.print("Owner: \n");
String owner = scanner.next();
System.out.print("Phone number: \n");
String phoneNum = scanner.next();
System.out.print("Please Select Group:\n"
+ "1 For FRIENDS,\n" +
"2 For FAMILY,\n" +
"3 For WORK,\n" +
"4 For OTHERS");
int enumNum = scanner.nextInt();
Group group;
switch(enumNum) {
case 1:
group=Group.FRIENDS;
break;
case 2:
group=Group.FAMILY;
break;
case 3:
group=Group.WORK;
break;
default:
group=Group.OTHERS;
}//switch end
contacts[i] = new Contact(owner,phoneNum,group);
}//loop end
System.out.println("Insert File name");
String fileName = scanner.next();
File f=null;
for(int i = 0 ; i < val; i++) {
if(i==0) {
f = new File(fileName);
contacts[0].Save(fileName);
}
else {
contacts[i].Save(f);
}
}
}
}
This is Contact Class:
enum Group {
FRIENDS,
FAMILY,
WORK,
OTHERS
};
public class Contact {
private String phoneNumber,owner;
private Group group;
PrintWriter pw = null;
public Contact(String owner ,String phoneNumber,Group group) {
setPhoneNumber(phoneNumber);
setOwner(owner);
setGroup(group);
}
public Contact(String fileName) {
File file = new File(fileName+".txt");
try {
Scanner scanner = new Scanner(file);
phoneNumber=scanner.nextLine();
owner=scanner.nextLine();
String str=scanner.nextLine();
group = Group.valueOf(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
public Contact(File file) {
try {
Scanner scanner = new Scanner(file);
phoneNumber=scanner.nextLine();
owner=scanner.nextLine();
String str=scanner.nextLine();
group = Group.valueOf(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public void Save(String fileName) {
File f = new File(fileName+".txt");
try {
if(f.createNewFile()) {
System.out.println("File created");
pw = new PrintWriter(f); //יצירת מדפסת לקובץ
pw.println(phoneNumber+"\n"+owner+"\n"+group+"\n\n\n");
}
} catch (IOException e) {
e.printStackTrace();
}
pw.close();
}
public void Save(File f) {
PrintWriter pw=null;
try {
pw = new PrintWriter(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.println(phoneNumber+"\n"+owner+"\n"+group);
pw.close();
}
public String toString() {
return phoneNumber+"\n"+owner+"\n"+group;
}
}
Every time you create PrintWriter the file is being overwritten. Since you create a new PrintWriter for each contact, the file contains only the last contact information. What you should do is to create PrintWriter only once and use it for all contacts.
Firstly, let's create a new save method with such signature:
public void save(PrintWriter writer)
I have also used the lowercase name of the method due to Java naming convention.
Now the implementation of save method will look like this:
writer.println(phoneNumber);
writer.println(owner);
writer.println(group + "\n\n\n");
Then we should replace the usage of Save method with the new one. Here is your code:
String fileName = scanner.next();
File f = null;
for (int i = 0; i < val; i++) {
if(i == 0) {
f = new File(fileName);
contacts[0].Save(fileName);
} else {
contacts[i].Save(f);
}
}
In order to fix the issue we can change it like this:
String fileName = scanner.next();
File file = new File(fileName);
try (PrintWriter writer = new PrintWriter(file)) {
for (int i = 0; i < val; i++) {
contacts[i].save(writer);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I have also used try-with-resources which closes the PrintWriter automatically.
From the Javadoc of the constructor of PrintWriter:
public PrintWriter​(File file)
Parameters: file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
In the Save function you create a PrintWriter everytime. So everytime the file is truncated, and then you lose the contact you saved before.
Since File I/O classes in java use Decorator Design pattern, you can use a FileWriter to take advantage of appending to a file. So you can use this code for Save() method :
public void Save(String fileName) {
File f = new File(fileName+".txt");
try {
//System.out.println("File created"); You don't need to create new file.
FileWriter fw=new FileWriter(f,true):// second argument enables append mode
pw = new PrintWriter(fw); //יצירת מדפסת לקובץ
pw.println(phoneNumber+"\n"+owner+"\n"+group+"\n\n\n");
} catch (IOException e) {
e.printStackTrace();
}
pw.close();
}

Java: My ArrayList empties itself as soon as I empty the text file from which the ArrayList gets its contents

I´m writing my own library in java, where you can save variables very simple. But I have a problem in changing the values of the variables. The ArrayList empties itself as soon as the txt file is empty.
My Code:
public class SaveGameWriter {
private File file;
private boolean closed = false;
public void write(SaveGameFile savegamefile, String variableName, String variableValue, SaveGameReader reader) throws FileNotFoundException
{
if(!reader.read(savegamefile).contains(variableName))
{
file = savegamefile.getFile();
OutputStream stream = new FileOutputStream(file, true);
try {
String text = variableName+"="+variableValue;
stream.write(text.getBytes());
String lineSeparator = System.getProperty("line.separator");
stream.write(lineSeparator.getBytes());
}catch(IOException e)
{}
do {
try {
stream.close();
closed = true;
} catch (Exception e) {
closed = false;
}
} while (!closed);
}
}
public void setValueOf(SaveGameFile savegamefile, String variableName, String Value, SaveGameReader reader) throws IOException
{
ArrayList<String> list = reader.read(savegamefile);
if(list.contains(variableName))
{
list.set(list.indexOf(variableName), Value);
savegamefile.clear();
for(int i = 0; i<list.size()-1;i+=2)
{
write(savegamefile,list.get(i),list.get(i+1),reader);
}
}
}
}
Here my SaveGameReader class:
public class SaveGameReader {
private File file;
private ArrayList<String> result = new ArrayList<>();
public String getValueOf(SaveGameFile savegamefile, String variableName)
{
ArrayList<String> list = read(savegamefile);
if(list.contains(variableName))
{
return list.get(list.indexOf(variableName)+1);
}else
return null;
}
public ArrayList<String> read(SaveGameFile savegamefile) {
result.clear();
file = savegamefile.getFile();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("=");
for (String part : splited) {
result.add(part);
}
}
} catch (IOException e) {
} finally {
boolean closed = false;
while(!closed)
{
try {
in.close();
closed=true;
} catch (Exception e) {
closed=false;
}
}
}
result.remove("");
return result;
}
}
And my SaveGameFile class:
public class SaveGameFile {
private File file;
public void create(String destination, String filename) throws IOException {
file = new File(destination+"/"+filename+".savegame");
if(!file.exists())
{
file.createNewFile();
}
}
public File getFile() {
return file;
}
public void clear() throws IOException
{
PrintWriter pw = new PrintWriter(file.getPath());
pw.close();
}
}
So, when I call the setValueOf() methode the ArrayList is empty and in the txt file there´s just the first variable + value. Hier´s my data structure:
Name=Testperson
Age=40
Phone=1234
Money=1000
What´s the problem with my code?
In your SaveGameReader.read() method you have result.clear(); which clears ArrayList. And you do it even before opening the file. So basically before every read from file operation you are cleaning up existing state and reread from file. If file is empty then you finish with empty list

Fast zipping folder using java ParallelScatterZipCreator

What should be the value of or initialize InputStreamSupplier?
I was trying to zip all the files in a directory and that should be fast.
So multi threading is the option i'm going for.
public class ScatterSample {
ParallelScatterZipCreator scatterZipCreator = new ParallelScatterZipCreator();
ScatterZipOutputStream dirs = ScatterZipOutputStream.fileBased(File.createTempFile("scatter-dirs", "tmp"));
public ScatterSample() throws IOException {
}
public void addEntry(ZipArchiveEntry zipArchiveEntry, InputStreamSupplier streamSupplier) throws IOException {
if (zipArchiveEntry.isDirectory() && !zipArchiveEntry.isUnixSymlink())
dirs.addArchiveEntry(ZipArchiveEntryRequest.createZipArchiveEntryRequest(zipArchiveEntry, streamSupplier));
else
scatterZipCreator.addArchiveEntry( zipArchiveEntry, streamSupplier);
}
public void writeTo(ZipArchiveOutputStream zipArchiveOutputStream)
throws IOException, ExecutionException, InterruptedException {
dirs.writeTo(zipArchiveOutputStream);
dirs.close();
scatterZipCreator.writeTo(zipArchiveOutputStream);
}
}
FirstMain Class:
public class FirstMain {
public FirstMain() {
// TODO Auto-generated constructor stub
}
public static void compressFolder(String sourceFolder, String absoluteZipfilepath)
{
try
{
ScatterSample scatterSample=new ScatterSample();
File srcFolder = new File(sourceFolder);
if(srcFolder != null && srcFolder.isDirectory())
{
Iterator<File> i = FileUtils.iterateFiles(srcFolder, new String []{"pdf"}, true);
File zipFile = new File(absoluteZipfilepath);
OutputStream outputStream = new FileOutputStream(zipFile);
ZipArchiveOutputStream zipArchiveOutputStream= new ZipArchiveOutputStream(outputStream);
int srcFolderLength = srcFolder.getAbsolutePath().length() + 1; // +1 to remove the last file separator
while(i.hasNext())
{
File file = i.next();
String relativePath = file.getAbsolutePath().substring(srcFolderLength);
InputStreamSupplier streamSupplier=new InputStreamSupplier(){
#Override
public InputStream get() {
// TODO Auto-generated method stub
return null;
}
};
ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(relativePath);
scatterSample.addEntry(zipArchiveEntry, streamSupplier);
}
scatterSample.writeTo(zipArchiveOutputStream);
}
}catch (Exception e) {
e.printStackTrace();
}
}
public static void main( String[] args )
{
compressFolder("C:\\Users\\akatm\\Desktop\\Stuff\\zipdata\\Newtry\\","C:/Users/akatm/Desktop/Stuff/Newtry.zip");
}
}
The get() method must return an InputStream to the file.
You could define an internal class as the following:
static class FileInputStreamSupplier implements InputStreamSupplier {
private Path sourceFile;
FileInputStreamSupplier(Path sourceFile) {
this.sourceFile = sourceFile;
}
#Override
public InputStream get() {
InputStream is = null;
try {
is = Files.newInputStream(sourceFile);
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
That you could then invoke as:
scatterSample.addEntry(zipArchiveEntry, new FileInputStreamSupplier(file.toPath());
You need to set the compress method in the ZipEntry
ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(relativePath);
zipArchiveEntry.setMethod(ZipArchiveEntry.STORED);
scatterSample.addEntry(zipArchiveEntry, streamSupplier);
if you don't set the compress method, the method throws an exception.

How to get variables from exception code block

I want to get user1.name variable from public static void FileRead()to private void jButton1ActionPerformed but It doesn't read user1.name. Can you explain me how can I use that variable.
public static class Users {
public String name;
public String password;
Users(String name1, String password1) {
name = name1;
password = password1;
}
}
public static void FileRead() {
try {
BufferedReader in = new BufferedReader(new FileReader("C:/Users/B_Ali/Documents/NetBeansProjects/JavaApplication20/UserNamePassword.txt"));
String[] s1 = new String[5];
String[] s2 = new String[5];
int i = 0;
while ((s1[i] = in.readLine()) != null) {
s1[i] = s2[i];
i = i + 1;
if (i == 1) {
Users user1 = new Users(s2[0], s2[1]);
}
else if (i == 3) {
Users user2 = new Users(s2[2], s2[3]);
}
else if (i == 5) {
Users user3 = new Users(s2[4], s2[5]);
}
}
in.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null, user1.name);
// TODO add your handling code here:
}
where should I declare it?
Edit: if i declare it as you said before. It becomes meaningless because i want to use user1.name which is defined in FileRead().
Declare it global.
Users user1;
public static class Users {
public String name;
public String password;
Users(String name1, String password1) {
name = name1;
password = password1;
}
public String getName()
{ return this.name;
}
public String getPassword()
{return this.password;
}
}
Users user1, user2;
public static void FileRead() {
try {
BufferedReader in = new BufferedReader(new FileReader("C:/Users/B_Ali/Documents/NetBeansProjects/JavaApplication20/UserNamePassword.txt"));
String[] s1 = new String[5];
String[] s2 = new String[5];
int i = 0;
while ((s1[i] = in.readLine()) != null) {
s1[i] = s2[i];
i = i + 1;
if (i == 1) {
Users user1 = new Users(s2[0], s2[1]);
}
else if (i == 3) {
Users user2 = new Users(s2[2], s2[3]);
}
else if (i == 5) {
Users user3 = new Users(s2[4], s2[5]);
}
}
in.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null, user1.getName());
// TODO add your handling code here:
}
You need to declare the variables you need outside of the try clause like:
String global = null;
try{
global = "abc";
throw new Exception();
}
catch(Exception e){
if (global != null){
//your code
}
}

How do I get my map to load in j2me?

My midlet
public void commandAction(Command command, Displayable displayable) {
// write pre-action user code here
if (displayable == form) {
if (command == exitCommand) {
// write pre-action user code here
exitMIDlet();
// write post-action user code here
} else if (command == okCommand) {
try {
// write pre-action user code here
connection = startConnection(5000, myip);
sendMessage("Query,map,$,start,211,Arsenal,!");
String unformattedurl= receiveMessage();
stringItem.setText(stringItem.getText()+" "+unformattedurl);
String url=getURL(unformattedurl,200,200);
Imageloader imageloader=new Imageloader(stringItem,item,url);
Thread thread=new Thread(imageloader);
thread.start();
}
catch(Exception e){
stringItem.setText(stringItem.getText()+" "+e.getMessage());
}
}
}
// write post-action user code here
}
private void sendMessage(String message) throws IOException{
stringItem.setText(stringItem.getText()+2);
DataOutputStream dos = connection.openDataOutputStream();
System.out.println("Sending...."+message);
dos.writeUTF(message);
stringItem.setText(stringItem.getText()+3);
}
public SocketConnection startConnection(int port,String ip) throws IOException{
return (SocketConnection) Connector.open("socket://"+ip+":"+port);
}
public static String[] split(String str,String delim) throws Exception{
String copy=str;
int len=0;
int index = copy.indexOf(delim)+1;
if (index==0){
throw new Exception("Data format not supported");
}
else{
int prev_index=0;
Vector array=new Vector();
//System.out.println(index);
array.addElement(copy.substring(0,index-1));
while (index !=0){
len++;
copy=copy.substring(index);
index = copy.indexOf(delim)+1;
//System.out.println(copy+" "+index);
if (copy.indexOf(delim)==-1){
array.addElement(copy);
}
else{
//System.out.println(0+" "+copy.indexOf(delim));
array.addElement(copy.substring(0,copy.indexOf(delim)));
}
}
String[] array2=new String [array.size()];
for (int i=0;i<array.size();i++){
array2[i]=(String)array.elementAt(i);
//System.out.println(array2[i]);
}
return array2;
}
}
private String receiveMessage() throws IOException{
stringItem.setText(stringItem.getText()+5);
DataInputStream dis = connection.openDataInputStream();
stringItem.setText(stringItem.getText()+6);
return dis.readUTF();
}
private String getURL(String message,int width,int height) throws Exception{
item.setLabel(item.getLabel()+6);
System.out.println("TEst1");
//System.out.println("Formatted message is "+query);
//System.out.println("Getting height......"+label.getMaximumSize().height);
String[] messagearr=split(message,",");
System.out.println("TEst2");
String color,object;
String url="http://maps.google.com/maps/api/staticmap?center=Mauritius&zoom=10&size="+width+"x"+height+"&maptype=roadmap";
//&markers=color:green|label:Bus21|40.702147,-74.015794&markers=color:blue|label:User|40.711614,-74.012318&sensor=false";
String lat,longitude;
System.out.println("TEst3");
if (messagearr[0].equals("query")){
System.out.println("TEst4");
if (messagearr[1].equals("Error")){
String error=messagearr[2];
System.out.println("TEst5"+error);
item.setAltText(error);
item.setLabel("Test"+error);
}
else {
System.out.println("Wrong number");
int startindex=5;
String distance,time;
distance=messagearr[2];
time=messagearr[3];
String name=messagearr[4];
imageLabel="The bus is at :"+time+"min and "+distance +"km from user";
for (int i=startindex;i<messagearr.length;i+=2){
System.out.println("TEst8");
lat=messagearr[i];
longitude=messagearr[i+1];
if (i==startindex){
object="U";
color="Blue";
}
else{
object="B";
color="Green";
}
url=url+"&markers=color:"+color+"|label:"+object+"|"+lat+","+longitude;
item.setLabel(7+url);
System.out.println("TEst10"+" name "+name+" long "+longitude+" lat "+lat+" url "+url );
}
url+="&sensor=false";
System.out.println("Image loaded .... "+url);
return url;
}
}
item.setLabel(item.getLabel()+8);
throw new Exception("Url is wrong");
}
}
public class Imageloader implements Runnable{
StringItem stringitem=null;
ImageItem imageitem=null;
String url=null;
Imageloader(StringItem stringitem,ImageItem imageitem,String url){
this.stringitem=stringitem;
this.imageitem=imageitem;
this.url=url;
stringitem.setText(stringitem.getText()+1);
}
private void loadImage() throws IOException{
stringitem.setText(stringitem.getText()+2);
imageitem.setImage(getImage(url));
}
public Image getImage(String url) throws IOException {
stringitem.setText(stringitem.getText()+3);
HttpConnection hpc = null;
DataInputStream dis = null;
try {
hpc = (HttpConnection) Connector.open(url);
System.out.println(hpc.getResponseMessage());
//hpc.getResponseMessage()
stringitem.setText(stringitem.getText()+" ... "+hpc.getResponseMessage());
int length = (int) hpc.getLength();
System.out.println("Length is "+length);
stringitem.setText(stringitem.getText()+" ... "+length);
byte[] data = new byte[length];
dis = new DataInputStream(hpc.openInputStream());
dis.readFully(data);
return Image.createImage(data, 0, data.length);
} finally {
if (hpc != null)
hpc.close();
if (dis != null)
dis.close();
}
}
public void run() {
try {
stringitem.setText(stringitem.getText()+5);
loadImage();
} catch (IOException ex) {
imageitem.setLabel(ex.getMessage()+5);
ex.printStackTrace();
}
}
}
I am unable to load an image in my mobile phone howerver it works fine using an emulator.
The exception says "Error in HTTP connection"..
and it occurs in the loadImage() method ..
How do I sort this out?
make sure your application has access to make http connection and you have got working connection with your phone

Categories

Resources