I have the methods:
public void sendTroops(ArrayList<Troops> troops){
try {
output.writeObject(troops);
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendTowers(ArrayList<Tower> towers){
try {
output.writeObject(towers);
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendString(ArrayList<String> str){
try {
output.writeObject(str);
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
public ArrayList<Object> receiveObjects(){
try{
return (ArrayList<Object>) input.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
used here:
private void updateConnection(){
if(isClientActive()){
if(player.getType() == 0){
client.sendTowers(towers);
System.out.println("sent towers: " + towers.size());
}else{
client.sendTroops(troops);
System.out.println("sent troops: " + troops.size());
}
ArrayList<Object> obj = client.receiveObjects();
System.out.println("obj: " +obj.size());
if(obj != null && obj.size() > 0){
if (obj.get(0) instanceof Troops) {
mendTroops(obj);
}else if(obj.get(0) instanceof Troops){
mendTowers(obj);
}
}
}else if(isServerActive()){
if(player.getType() == 0){
server.sendTowers(towers);
System.out.println("sent towers: " + towers.size());
}else{
server.sendTroops(troops);
System.out.println("sent troops: " + troops.size());
}
ArrayList<Object> obj = server.receiveObjects();
System.out.println("obj: " +obj.size());
if(obj != null && obj.size() > 0){
if (obj.get(0) instanceof Troops) {
mendTroops(obj);
}else if(obj.get(0) instanceof Troops){
mendTowers(obj);
}
}
}
}
I was able to determine that the size of the object array from server/client.receiveObjects(); is always resulting in a array of size zero. I am unsure why this is the issue (as no errors are thrown). Either this is terrible coding practice (which it very well may be) or I'm over looking something.
I would appreciate any help, and if more code/ information of how this program works is needed, please let me know.
Related
Basically I am developing a multiplayer kart racing game using TCP. There will be two clients and one server. The clients connected will be passed as a thread running. The first connected client will be assigned as player 1 and the later to be player 2.
The protocol that I have developed is:
Player 1 sends its kart's information to server and server forwards it to Player 2.
Player 2 then sends its kart's information to server and server forwards it to Player 1.
I am sending String like "KART1:X:200" over the network. However, when entire project runs, the two clients are successfully connected, but the jFrame shows nothing.
Below is my code for
Server:-
try
{
service = new ServerSocket(8888);
System.out.println("Server has started.");
}
catch (IOException e)
{
System.out.println(e);
}
try
{
while (connectedClient < 2)
{
server = service.accept();
connectedClient++;
BufferedReader reader = new BufferedReader(new InputStreamReader(server.getInputStream()));
DataOutputStream writer = new DataOutputStream(server.getOutputStream());
ClientThread clientThread = new ClientThread(server, String.valueOf(connectedClient), reader, writer);
System.out.println("Player " + connectedClient + " connected. IP Address: " + server.getInetAddress());
Thread thread = new Thread(clientThread);
thread.start();
System.out.println("Player: " + connectedClient + " thread running.");
}
System.out.println("Server is full.");
}
catch (IOException e)
{
System.out.println(e);
}
ClientThread:-
#Override
public void run()
{
try
{
while (keepRunning == true)
{
if (reader.readLine() != null)
{
String[] message = reader.readLine().split(":");
if (message[0].equalsIgnoreCase("KART1"))
{
kartNum = message[0];
if (message[1] == "INDEX")
{
kartNumIndex = message[2];
broadcastToPlayer2(kartNumIndex);
}
else if (message[1] == "X")
{
x = message[2];
broadcastToPlayer2(x);
}
else if (message[1] == "Y")
{
y = message[2];
broadcastToPlayer2(y);
}
else if (message[1] == "SPEED")
{
speed = message[2];
broadcastToPlayer2(speed);
}
}
else if (message[0].equalsIgnoreCase("KART2"))
{
kartNum = message[0];
if (message[1] == "INDEX")
{
kartNumIndex = message[2];
broadcastToPlayer1(kartNumIndex);
}
else if (message[1] == "X")
{
x = message[2];
broadcastToPlayer1(x);
}
else if (message[1] == "Y")
{
y = message[2];
broadcastToPlayer1(y);
}
else if (message[1] == "SPEED")
{
speed = message[2];
broadcastToPlayer1(speed);
}
}
}
}
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
public void broadcastToPlayer1(String value)
{
try
{
clients.get(0).writer.writeBytes(value);
clients.get(0).writer.writeBytes("\n");
clients.get(0).writer.flush();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
public void broadcastToPlayer2(String value)
{
try
{
clients.get(1).writer.writeBytes(value);
clients.get(1).writer.writeBytes("\n");
clients.get(1).writer.flush();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
RacingTrack (JPanel) that will get and send karts' information:-
if (playerNum == 1)
{
// send kart1 information
try
{
writer.writeBytes("KART1:INDEX:" + kart1.getKartImageIndex());
writer.writeBytes("\n");
writer.writeBytes("KART1:X:" + kart1.getXCoordinate());
writer.writeBytes("\n");
writer.writeBytes("KART1:Y:" + kart1.getYCoordinate());
writer.writeBytes("\n");
writer.writeBytes("KART1:SPEED:" + kart1.getSpeed());
writer.writeBytes("\n");
writer.flush();
kart1.draw(g, this);
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
if (playerNum == 2)
{
// get kart1 information
try
{
kartImageIndex = Integer.parseInt(reader.readLine());
x = Integer.parseInt(reader.readLine());
y = Integer.parseInt(reader.readLine());
speed = Integer.parseInt(reader.readLine());
kart1.setKartImageIndex(kartImageIndex);
kart1.setXCoordinate(x);
kart1.setYCoordinate(y);
kart1.setSpeed(speed);
kart1.draw(g, this);
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
// send kart2 information
try
{
writer.writeBytes("KART2:INDEX:" + kart2.getKartImageIndex());
writer.writeBytes("\n");
writer.writeBytes("KART2:X:" + kart2.getXCoordinate());
writer.writeBytes("\n");
writer.writeBytes("KART2:Y:" + kart2.getYCoordinate());
writer.writeBytes("\n");
writer.writeBytes("KART2:SPEED:" + kart2.getSpeed());
writer.writeBytes("\n");
writer.flush();
kart2.draw(g, this);
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
if (playerNum == 1)
{
// get kart2 information
try
{
kartImageIndex = Integer.parseInt(reader.readLine());
x = Integer.parseInt(reader.readLine());
y = Integer.parseInt(reader.readLine());
speed = Integer.parseInt(reader.readLine());
kart2.setKartImageIndex(kartImageIndex);
kart2.setXCoordinate(x);
kart2.setYCoordinate(y);
kart2.setSpeed(speed);
kart2.draw(g, this);
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
Please help :(
public class CatchingExceptions {
private int erroneousMethod(int p) {
if (p == 0) {
throw new IllegalArgumentException();
}
int x = 0x01;
return p / (x >> Math.abs(p)); // this line will throw!
}
The task is to implement the following method to catch and print the two exceptions.
public void catchExceptions(int passthrough) {
erroneousMethod(passthrough); // will throw!
try{
????
} catch (IllegalArgumentException e){
System.out.println("???? ");
}
}
Call the method inside the try block:
public void catchExceptions(int passthrough) {
try{
erroneousMethod(passthrough);
} catch (RuntimeException e) { // catches all unchecked exceptions
String message = e.getMessage() == null ? "" : (": " + e.getMessage());
System.out.println(e.getClass().getSimpleName() + ": " + message);
}
}
I written a method which will acknowledge the controller by returning true and false, I return true inside try if everything goes fine it will return true and I return false inside catch blocks, but still method shows me error "missing return statement" what is the best way to do it.
The below method written in java will send back the true or false to the controller.
Secondly I want to carry the exception message from here to controller, I think of returning string, is it good approach,
Kindly suggest me the best way to do the exception handling
public boolean pickSalayData(String yearMonth, String regionId, String circleId, Userdetail loginUser) throws MyExceptionHandler {
String tableSuffix = yearMonth.substring(4, 6) + yearMonth.substring(0, 4);
log.info("Pick Salary Data From ERP " + DateUtility.dateToStringDDMMMYYYY(new Date()));
List<SalaryDetailReport> detailReports = hRMSPickSalaryDataDAO.findAll(yearMonth, regionId, circleId);
TransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus trstatus = transactionManager.getTransaction(def);
try {
List<SalaryDetailReport> salaryDetailReport = null;
int countDetail = 0;
if (detailReports != null && detailReports.size() > 0) {
for (SalaryDetailReport salary : detailReports) {
try {
if (countDetail % COMMIT_COUNT == 0) {
if (salaryDetailReport != null) {
salaryDetailReportDAO.save(salaryDetailReport, tableSuffix);
reportHistoryDAO.save(salaryDetailReport, loginUser);
}
salaryDetailReport = new ArrayList<SalaryDetailReport>();
}
salaryDetailReport.add(salary);
countDetail++;
} catch (Exception e) {
log.error("Error on Save Salary Pay Head Details Data from ERP to Prayas .");
}
}
if (salaryDetailReport != null && salaryDetailReport.size() > 0) {
salaryDetailReportDAO.save(salaryDetailReport, tableSuffix);
reportHistoryDAO.save(salaryDetailReport, loginUser);
}
} else {
throw new MyExceptionHandler("No record for Save in Database from ERP.");
}
salaryDetailReportDAO.update(tableSuffix, regionId, circleId);
List<SalaryDetailReport> reports = salaryDetailReportDAO.findAll(tableSuffix, regionId, circleId);
if (reports != null && reports.size() > 0) {
for (SalaryDetailReport salaryDetail : reports) {
try {
SalaryDetail sd = new SalaryDetail();
sd.setDetailReport(salaryDetail);
salaryDetailDAO.save(sd, tableSuffix);
} catch (Exception e) {
log.error("Error occured", e);
e.printStackTrace();
throw new MyExceptionHandler(" Error :" + e.getMessage());
}
}
System.out.println("data found");
} else {
log.error("Salary Record Not Found.");
throw new MyExceptionHandler("No record Found.");
}
salaryDetailDAO.updateEarningDeduction(tableSuffix);
//salaryDetailDAO.updateEarningDeductionsInSDT();
transactionManager.commit(trstatus);
try {
hRMSPickSalaryDataDAO.update(regionId, circleId, yearMonth);
return true;
} catch (Exception ex) {
log.error("Some error : ", ex);
}
// // System.out.println("Completed =============================");
} catch (MyExceptionHandler ex) {
transactionManager.rollback(trstatus);
ex.printStackTrace();
log.error("Failed to Save Salary data :" + ex.getMessage());
return false;
} catch (Exception ex) {
transactionManager.rollback(trstatus);
ex.printStackTrace();
log.error("Error occured on Save Salary data.", ex);
return false;
}
}
You are missing return statement for the following catch block :
catch (Exception ex) {
log.error("Some error : ", ex);
}
Either you add return statement in this catch block or at the end of mehtod
If this code throws an Exception, then the following catch code will not be entered into and hence there is no return value
try {
hRMSPickSalaryDataDAO.update(regionId, circleId, yearMonth);
return true;
} catch (Exception ex) {
log.error("Some error : ", ex);
**edit**
return `true||false`;
}
} catch (...) {
return something;
}
I am programatically trying to connect to ssh running remotely. I am running a tomcat server instance. Whenever i need, from the code, i create a session, connect and execute a few commands that are needed within a try block and then close off the connection that was created as part of the finally block at all the places. Things work well and fine, but at some cases when i execute a w or netstat command on the ssh server, I see a few connections that are idle for more than a few hours and the ip address of those connections shows the connection to be from my application, but my java heap dump does not show any instance of my class in the memory, but i see ganymed related class instances in the heap.
I am using ganymed-ssh-260 library to connect to my server.
Is this something that someone has already seen?
Attaching the code snippet that connectes the ssh to the server
public class SSHExecutor{
private OutputStream stdin;
private InputStream stdout;
private InputStream stderr;
private Session sess;
private Connection conn;
public void createConnection(String hostname, int port, String userName, String password) throws Exception {
try {
conn = new Connection(hostname, port);
final boolean isAuthenticated = publicKeyAccess(hostname, userName, password);
if (!isAuthenticated) {
throw new IOException("Authentication failed.");
}
sess = conn.openSession();
final int xWidth = 90;
final int yWidth = 80;
sess.requestPTY("dumb", xWidth, yWidth, 0, 0, null);
sess.startShell();
stdin = sess.getStdin();
stdout = sess.getStdout();
stderr = sess.getStderr();
isConnectionActive = true;
final String response = getResponse();
if (response != null && response.toLowerCase().contains(ObjectConstants.CURRENTLY_NOT_AVAILABLE)) {
throw new IOException("Account is currently not available.");
}
} catch (Exception e) {
log.error("Problem in CreateConnection", e);
isConnectionActive = false;
throw e;
}
}
public String getResponse() {
final StringBuffer responseData = new StringBuffer();
try {
final int byteValue = 8192;
final byte[] buffer = new byte[byteValue];
try {
while (true) {
if ((stdout.available() == 0) && (stderr.available() == 0)) {
int conditions = 1;
if (promptString != null && promptString.length() > 0) {
final int fiveThousand = 5000;
conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA
| ChannelCondition.STDERR_DATA | ChannelCondition.EOF, fiveThousand);
} else {
conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA
| ChannelCondition.STDERR_DATA | ChannelCondition.EOF,
ObjectConstants.THOUSAND_FIVE_HUNDRED);
}
if ((conditions & ChannelCondition.TIMEOUT) != 0) {
break;
}
if ((conditions & ChannelCondition.EOF) != 0) {
if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
break;
}
}
}
while (stdout.available() > 0) {
final int len = stdout.read(buffer);
if (len > 0) {
responseData.append(new String(buffer, 0, len));
}
}
while (stderr.available() > 0) {
final int len = stderr.read(buffer);
if (len > 0) {
responseData.append(new String(buffer, 0, len));
}
}
if (promptString != null && promptString.length() > 0) {
if (responseData.indexOf(promptString) != -1) {
break;
}
}
}
} catch (Exception e) {
log.error("Read Error :", e);
}
} catch (Exception e) {
log.error("getResponse Error ", e);
}
return responseData.toString();
}
public String executeCommand(String command) throws IOException {
String response = null;
if (isConnectionActive && stdin != null) {
try {
stdin.write(command.getBytes());
stdin.flush();
response = getResponse();
} catch (IOException ie) {
throw ie;
} catch (Exception e) {
log.error("Exception in executeCommandForPage()", e);
response = e.getMessage();
}
} else {
response = "Connection not active.";
}
return response;
}
public void closeConnection() {
if (stderr != null) {
try {
stderr.close();
} catch (Exception e) {
log.error("Exception in closeConnection()", e);
}
}
if (stdout != null) {
try {
stdout.close();
} catch (Exception e) {
log.error("Exception in closeConnection()", e);
}
}
if (stdin != null) {
try {
stdin.close();
} catch (Exception e) {
log.error("Exception in closeConnection()", e);
}
}
if (sess != null) {
try {
sess.close();
} catch (Exception e) {
log.error("Exception in closeConnection()", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
log.error("Exception in closeConnection()", e);
}
}
}
}
You're creating a local Connection variable but you're testing what must be a member variable, which is always null, so you're never closing it.
If authentication fails you're leaking the connection.
So what I want to do is when my Jsoup connection times out I want to bring up an alert dialog. Right now it does nothing. It just skips over there error and doesn't catch a timeout exception or crash. I'm new to java so I'm not sure how to catch this sockettimeoutexception and reroute it to another method. Can someone tell me how to go to another method when jsoup time out?
private void waterLevel() {
// TODO Auto-generated method stub
try {
levelDoc = Jsoup.connect("http://waterdata.usgs.gov/va/nwis/uv?site_no=02037500roop").timeout(3000).get();
} catch (SocketTimeoutException a) {
Log.e("MyAPP", "Exception----------A!", a);
a.printStackTrace();
alertdialog();
} catch (Exception e) {
Log.e("MyAPP", "Exception----------E!", e);
}
for (Element table : levelDoc.select("table[id=table_07_00065]")) {
String tableText = table.text();
depthArray = tableText.split(" ");
waterLevel = Double.parseDouble(depthArray[4]);
tvWaterLevel.setText(depthArray[4]+"FT");
if(waterLevel >= 5.0 && waterLevel < 9.0){
tvAlert.setText("LIFE JACKET REQUIRED");
}
else if (waterLevel >= 9.0){
tvAlert.setText("HIGH WATER PERMIT REQUIRED");
}
else{
tvAlert.setText("");
}
}
}
So I add changed the code to this and it gives me what i want:
private void waterLevel() {
// TODO Auto-generated method stub
try {
levelDoc = Jsoup.connect("http://waterdata.usgs.gov/va/nwis/uv?site_no=02037500").timeout(4000).get();
} catch (SocketTimeoutException a) {
Log.e("MyAPP", "Exception----------A!", a);
a.printStackTrace();
} catch (Exception e) {
Log.e("MyAPP", "Exception----------E!", e);
}
tvWaterLevel.setText("");
for (Element table : levelDoc.select("table[id=table_07_00065]")) {
String tableText = table.text();
depthArray = tableText.split(" ");
waterLevel = Double.parseDouble(depthArray[4]);
tvWaterLevel.setText(depthArray[4]+"FT");
if(waterLevel >= 5.0 && waterLevel < 9.0){
tvAlert.setText("LIFE JACKET REQUIRED");
}
else if (waterLevel >= 9.0){
tvAlert.setText("HIGH WATER PERMIT REQUIRED");
}
else{
tvAlert.setText("");
}
}
if (tvWaterLevel.length() < 1){
connectionAlarm();
}
}