Win a copy of Classic Computer Science Problems in Swift this week in the iOS forum!

Akshata Alandker

Greenhorn
+ Follow
since Sep 11, 2012
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
1
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Akshata Alandker

Hi everyone, i am a beginner in network programming, I have an assignment to develop a simple chat server with 2 clients and server.
This is my code,

server code

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server implements Runnable{
static ServerSocket providerSocket;
static Socket connection = null;
static ObjectOutputStream out;
static ObjectInputStream in;
String message;

Server(){}
//public void run(){
public static void main(String[] args){
int count = 2;

try{
//1. creating a server socket
providerSocket = new ServerSocket(45155);
}catch(IOException ioException){
ioException.printStackTrace();
}
try{
while(true){
//2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());

//3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
Runnable runnable = new Server();
Thread thread = new Thread(runnable);
thread.start();

}


}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
out.close();
providerSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
public void run(){
//4. The two parts communicate via the input and output streams
do{
try{
message = (String)in.readObject();
System.out.println("client>" + message);
if (message.equals("bye")){
sendMessage("bye");
}
Scanner in =new Scanner(System.in);
message = in.nextLine();

sendMessage(message);

}
catch(ClassNotFoundException classnot){
System.err.println("Data received in unknown format");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}while(!message.equals("bye"));

}
static void sendMessage(String msg)
{

try{
out.writeObject(msg);
out.flush();
System.out.println("server>" + msg);
}
catch(IOException ioException){
ioException.printStackTrace();
}
}

}

client code

import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Requester{
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Requester(){}
void run() throws ClassNotFoundException
{
try{
//1. creating a socket to connect to the server
requestSocket = new Socket("localhost", 45155);
System.out.println("Connected to localhost in port 45155");
//2. get Input and Output streams
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
//3: Communicating with the server
getMessage();


}
catch(UnknownHostException unknownHost){
System.err.println("You are trying to connect to an unknown host!");
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
out.close();
requestSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
void getMessage() throws IOException, ClassNotFoundException{
do{
message = (String)in.readObject();
System.out.println("server>" + message);
Scanner in =new Scanner(System.in);
message = in.nextLine();
sendMessage(message);
}while(!message.equals("bye"));
}
void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
System.out.println("client>" + msg);
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
public static void main(String args[])
{
Requester client = new Requester();
try {
client.run();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

I am facing some problems here,1) the server is accepting 2 connections, but the communication is happening only between server and second client, and after some time I am getting this error

java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.peek(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.peek(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at com.simpragma.server1.Server.run(Server.java:67)
at java.lang.Thread.run(Unknown Source)

2) For only one client the communication with server is correct, and is terminated by 'bye' by the client.
3)My task is to communicate between 2 clients via server, the messages should be printed on client consoles.

can anyone tell me where i should modify the code to get the correct communication done... thanks
Is it possible to use triggers and store data from one table in another table, here i want to delete the previous table data for some reason but want to keep back up of the deleted data.
Can this be done using triggers? please guide
I am trying to access my database from another system, i have given the correct url, username and password too, but I am not able to access that database it giving me this error

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1117)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:350)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2408)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2445)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2230)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.simpragma.junk.Junk.main(Junk.java:12)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:259)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300)
... 15 more

when i try to ping the other system, its accessing but when i run my code it gives me the error, what might be the probable error? please guide.
Sorry, but I din't understand what you are trying to say, Campbell Ritchie. I just want to know how to print message from main() method when the event is not found in the file, because my method is in another package and I am calling it in main() method in other class and displaying the returns.
5 years ago
hello everyone,
I have another issue in managing file, i have a method which fetches events by their type, say i give input as birthday, it prints all the birthday events from the file to my console.
The return type of this method is a List<String> and so it returns the string, and this method is in my DAO layer, I am calling this method in the service layer fetch method and the list is printed in my ui which is main() method for time being, and I have a condition not to use any system.out statement in service nor DAO methods.
my problem is, if the event does not exist in my file, how to print user friendly message "no such event found", and where? can a method have multiple returns?

here is my code

public List<String> fetchEventByType(String type) {
logger.info("Entering method fetchEventByType().");
List<String> newList = new ArrayList<String>();


try {
// Open the file that is the first
// command line parameter
File file = new File(
"C:/Akshata/workspace/EventManager/src/com/simpragma/oop/dao/event.txt");
FileInputStream fstream = new FileInputStream(file);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
String[] strArray = strLine.split(CSV_SEPARATOR);

// for (int i = 0; i < strArray.length; i++) {

if (strArray[2].equalsIgnoreCase(type)) {

newList.add(strLine);

break;
}
}

// }
in.close();
} catch (Exception e) {
// Catch exception if any
System.out.println("event of this type does not exist");
// System.err.println("Error: " + e.getMessage());
}
logger.info("exiting the method fetchEventsByType()");
return newList;
}

this is my service layer method
public List<String> fetchEventByType(String type) throws Exception{
logger.info("entering the method fetchEventByType()");
List<String> list = new ArrayList<String>();
list = dao.fetchEventByType(type);
logger.info("exiting the method fetchEventByType()");
return list;
}

and here is my main() method in which this method is called

case 3:

String events = null;
System.out.println("enter the type of event you want to fetch");
String type = input.next();
list = manager.fetchEventByType(type);

for(int i=0; i<list.size(); i++){
events = list.get(i);
System.out.println(events);

}
break;



these are my events in file
1,Akshata,birthday,11-12-2012,04:30,Bangalore
2,Asha,wedding,05-05-2012,05:00,Bangalore
3,xyz,meeting,12-05-2012,12:00,Delhi
4,school,getTogether,12-12-2012,08:00,Bangalore

if user enters some conference event, i should be able to print message from main. how can i do it?
5 years ago
Thanks a lot Swastik Dey, that was of great help, actually i was passing parameter as int so it was not deleting the line, not I am able to do it... thank you so much
5 years ago
hi, I have tried even this also, but result is the same, its adding all the lines from file to the list. the line with ID is also added to the list. I don't want to add that line, except the line with id all other lines should be added to the list
5 years ago
appending is not the issue, i have problem in this line
if ( !array[i].equals(id)){

newList.add(line);

}

when i say -
if( array[i].equals(id)){

newList.add(line);

} it takes the line specified by the id, but when i say " !array[i] " it is taking all the lines in the file without excluding the line with - id .
5 years ago
hello everyone,

I have tried to modify the method and now it is not showing any exception, but still am not able to get the required result, this method should add all the lines in the file except the line of which id is passed as parameter,
but it is not doing the thing, its printing all the lines in the file again, here is my code

public void deleteEvent(int id){

List<String> newList = new ArrayList<String>();
try{

File file = new File("C:/Akshata/workspace/EventManager/src/com/simpragma/oop/dao/event.txt");
FileInputStream fstream = new FileInputStream(file);

// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

String line= null;
while((line = reader.readLine())!=null){
String[] array = line.split(CSV_SEPARATOR);
for(int i = 0; i<array.length; i++){
if(!array[i].equals(id)){

newList.add(line);

}

}
}
System.out.println(newList);
reader.close();
}

catch(Exception e){
e.printStackTrace();
}



String lines=null;
try {
FileWriter filestream = new FileWriter(("C:/Akshata/workspace/EventManager/src/com/simpragma/oop/dao/event.txt"),true);
BufferedWriter out = new BufferedWriter(filestream);

//for (String dataLine : newList) {
int i=0;

for( i = 0; i< newList.size(); i++){
lines = newList.get(i);

}
//System.out.println(lines);
out.write(lines);
out.newLine();
out.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

can any one tell me where my logic is wrong? thanks..
5 years ago
Thanks every one.. I am using the same technique as many suggested, using a temp file and store the contents other then the one to be deleted, i am getting some kind of exception in this, my code is

the exception m getting is,
java.io.IOException: Stream closed

at java.io.BufferedReader.ensureOpen(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at com.simpragma.oop.dao.EventManagerDao.deleteEvent(EventManagerDao.java:177)
at com.simpragma.oop.EventManager.deleteEvent(EventManager.java:41)
at com.simpragma.oop.EventManagerMain.main(EventManagerMain.java:119)

the error is in this line.. while((line = reader.readLine())!=null), please help me on this
5 years ago
hi,
How can i delete contents of a file, for instance
1,Akshata,birthday,11-12-2012,04:30,Bangalore
2,Asha,wedding,05-05-2012,05:00,Bangalore
3,xyz,meeting,12-05-2012,12:00,Delhi
4,school,getTogether,12-12-2012,08:00,Bangalore
5,company,birthday,04-03-2012,03:00,Bangalore ,

these are few events which i have stored in a file, now i want to delete a particular event with id - 1, any suggestions will be help , thanks.
5 years ago

Campbell Ritchie wrote:
Why do you need to sort the array?
Why are you removing an element? That is awkward; you would have to create an array one element smaller, and copy the remaining elements into that new array. It might be easier (a lot easier) to use a List.



In my prob statement i have example inputs and expected outputs, I have to write the code and use same inputs, so I have to give the same elements in the array, I should sort the array and delete the first and last element as per the problem, I know it is lot easy to use 'list' but according to the statement I have to use array only. but I am unable to find how to delete element from the array, please help
5 years ago

Campbell Ritchie wrote:
The error is in the original code. You are assuming you will have more than 50 elements in the array. Using arr[50] looks even more dubious. Why did you choose the 51st element? Please explain your decision.



yes, that was something silly I did. but I am choosing 50 because my limit for the array is 50 elements, it should not exceed the limit. I got another solution to the prob, its similar i.e am writing it inside a method but this is working fine for me

private boolean isValidArray(int[] marks) {
boolean result = true;
if(marks.length>50){
result = false;


}
return result;
}
5 years ago
Can any one help me with syntax to delete an element from an array? i have an array say [20,59,30,98,0,12,45] i'll sort them using Arrays.sort now i want to delete first element from the sorted and even the last element that is smallest and the largest numbers, please help me in this regards, Thank you.
5 years ago
The programs I am working on are assignment programs and I don't have to get user input, I am just hard coding the array in the main method and executing them, so this method works fine for me.
I had another prob validating the length of the array, i tried using similar method as above, which is

private boolean isValidArray(int[] marks) {
boolean result = true;

for (int j = 1; j < marks.length; j++) {
if (marks[j] > marks[50]) {
result = false;
break;
}
}
return result;
}
here i have some problem, if I give array input mare then 50 then it works fine, it gives a message 'enter valid inputs' but if i give valid inputs i.e. if i give inputs less then 50 it gives me an error arrayIndexOutOfBounds at the line if (marks[j] > marks[50]). can any one tell me what is wrong in this method??
5 years ago