When I use Windows to run eclipse Android emulator to connect socket,it was successful.
However, when I use Mac os lion to run the "Same" code ,the emulator shows"unfortunately
client test was stop!!"please help me solve this.And I already add the permission to internet!
package com.example.testclientokok;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Socket socket=new Socket(InetAddress.getLocalHost(), 8888);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
server part
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
If I understand correctly, you are executing MyServer on your machine, where you also run the emulator. If the Activity running in the emulator wants to establish a connection with MyServer, then it should use the following IP address : 10.0.2.2 (and not localhost, which references the emualor loopback interface).
See http://developer.android.com/tools/devices/emulator.html#networkaddresses
Related
I am trying to implment CompletableFuture which invokes a dummy callback method when completed.
However, after adding CompletableFuture.get() method my main class doesn't terminate.
I tried replacing CompletableFuture.get() with Thread.sleep(5000) but it doesn't seem to be right approach.
Please suggest what is causing CompletableFuture.get() to keep blocking even if the thread is complete.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.IntStream;
public class CallableAsyncWithCallBack {
public static void main(String[] args) throws InterruptedException {
CompletableFuture<String> compFuture=new CompletableFuture<String>();
compFuture.supplyAsync(()->{
//Compute total
long count=IntStream.range(Integer.MIN_VALUE, Integer.MAX_VALUE).count();
return ""+count;
}).thenApply(retVal->{
try {
return new CallBackAsynchClass(retVal).toString();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
);
System.out.println("Main Thread 1");
try {
compFuture.get();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("Lock cleared");
}
}
class CallBackAsynchClass
{
String returnVal="";
public CallBackAsynchClass(String ret) throws InterruptedException, ExecutionException {
System.out.println("Callback invoked:"+ret);
returnVal=ret;
}
#Override
public String toString() {
return "CallBackAsynchClass [returnVal=" + returnVal + "]";
}
}
I am expecting "Lock cleared" to be outputted but .get() seems to be holding up the lock.
.thenApply function returns a new instance of CompletableFuture, and it's this instance that you need to use, try using this way instead :
public class CallableAsyncWithCallBack {
public static void main(String[] args) throws InterruptedException {
CompletableFuture<String> compFuture = CompletableFuture.supplyAsync(() -> {
//Compute total
long count = IntStream.range(Integer.MIN_VALUE, Integer.MAX_VALUE).count();
return "" + count;
});
CompletableFuture<String> future = compFuture.thenApply(retVal -> {
try {
return new CallBackAsynchClass(retVal).toString();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ""; });
System.out.println("Main Thread 1");
try {
future.get();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("Lock cleared");
}
}
Hope this helps
I have a problem with syntax SQL. When i mvn jetty:run then occur following error:
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "user" at
line 1, co lumn 14.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknow
n Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source
)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException
(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Un
known Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown So
urce)
at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown So
urce)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at edu.java.spring.service.user.controller.CustomContextLoaderListener.c
reateTableNotExist(CustomContextLoaderListener.java:68)
at edu.java.spring.service.user.controller.CustomContextLoaderListener.c
reateTable(CustomContextLoaderListener.java:48)
at edu.java.spring.service.user.controller.CustomContextLoaderListener.c
ontextInitialized(CustomContextLoaderListener.java:36)
Here file CustomContextLoaderListene which encouter error:
package edu.java.spring.service.user.controller;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletContextEvent;
import org.springframework.web.context.ContextLoaderListener;
public class CustomContextLoaderListener extends ContextLoaderListener{
#Override
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
System.out.println("hibernate shutdown database");
try {
DriverManager.getConnection("jdbc:derby:D:/PROJECTSPRING/userdb;shutdown=true");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\n Spring-MVC application destroyed \n");
super.contextDestroyed(event);
}
#Override
public void contextInitialized(ServletContextEvent event) {
// TODO Auto-generated method stub
System.out.println("\n Spring-MVC application inited \n");
try {
createTable();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.contextInitialized(event);
}
public void createTable() throws SQLException{
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection connection = DriverManager.getConnection("jdbc:derby:D:/PROJECTSPRING/subjectdb;create=true");
createTableNotExist(connection,"user", "create table user"
+ "(username varchar(1000) primary key,"
+ "password varchar(1000),birthday date,"
+ "age integer,gender varchar(100))");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void createTableNotExist(Connection connection,
String tableName,String createTableSQL) throws SQLException{
DatabaseMetaData dbmd = connection.getMetaData();
ResultSet rs = dbmd.getTables(null, null,tableName.toUpperCase(), null);
if (rs.next()){
System.out.println("Table" + rs.getString("TABLE_NAME") + "already exists");
return;
}
Statement statement = connection.createStatement();
statement.execute(createTableSQL);
System.out.println("\n\n executed" + createTableSQL + "\n\n");
statement.close();
}
}
"user" it is a built-in function in derby. Enter another table name and it should start work
So I have a new project I work which I move in a room (panoramic picture). Now I want to open something on mouseClick. But when I try even to print something to the console in the mouseClick event it doesn't work.
package noam;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class room extends JPanel{
ImageIcon img;
int locationX=0,locationY=0;
int cp=0,cr=0,c=0;//cp clickpresed cr clickreleased c clicked
public room()
{
addMouseMotionListener(new MML());
//addMouseMotionListener(new ML());
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
img =new ImageIcon("VRpano.jpg");
Image s=img.getImage();
g.drawImage(s, locationX,locationY,img.getIconWidth(),img.getIconHeight(), null);
}
class MML extends MouseAdapter{
/*public void mousePressed(MouseEvent e) {
}*/
public void mouseMoved(MouseEvent e) {
if(e.getX()>1100){
if(locationX>-6350)
locationX-=20;
if(locationX<=-6350)
locationX=0;
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(e.getX()<200){
if(locationX<0)
locationX+=20;
if(locationX>=0)
locationX=-6300;
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
//System.out.println("x="+e.getX()+" y="+e.getY());
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
System.out.println("click!");
c++;
System.out.println(c);
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
super.mousePressed(e);
System.out.println("Pressed!");
cp++;
System.out.println(cp);
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseReleased(e);
System.out.println("Released!");
cr++;
System.out.println(cr);
}
}
/*public class ML extends MouseAdapter{
public void MOUSE_ENTERED(MouseEvent me){
System.out.println("click!");
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame f=new JFrame("Asteroids MS Ver 1 (c) 2014");
room bp=new room();
f.add(bp);
f.setSize(1650,1080);
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setVisible(true);
}
}
im trying to connect my java to db2 database but im getting an error :
"Execution failed due to a distribution protocol error that will affect the successful execution of subsequent DDM commands or SQL statements.
A connection could not be established to the database because manager 0x2407 at level 0x3 is not supported."
What do you think im doing wrong? Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class conUrl {
public static void main(String[] args) {
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://host:50000/test";
String user="dbuser";
String password="passwrod";
Connection connection = null;
//Statement st = null;
//Result rs = null;
try {
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
connection = DriverManager.getConnection(url,user,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(connection!=null){
System.out.println("Connected successfully.");
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
*import java.util.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.*;
public class LocaleProgram {
public static void main(String[] args) {
try {
Class c = Class.forName("java.util.Locale");
Class c1 = Class.forName("java.util.Locale$Category");
Class[] paramTypes = { c1 };
try {
Method m = c.getMethod("getDefault", paramTypes);
try {
//Object o = m.invoke(c1);
Object o = m.invoke(c1,new Object[]{"FORMAT"});
System.out.println("Object:" + (Locale)o);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}*
Basically I want Locale.getDefault(Locale.Category.FORMAT) using reflection, so that I can run this code on other than Java version 7.But I am trouble with calling invoke method, it's giving me java.lang.IllegalArgumentException: argument type mismatch exception.
Many thanks in advance
Change this line
Object o = m.invoke(c1,new Object[]{"FORMAT"});
to
Object o = m.invoke(c1,new Object[]{Locale.Category.FORMAT});
However, this may not be what you want, as you want to create the used enum by using reflection?
This will not work under Java 1.6 as these enums didn't exist yet.
Some handy stuff to read: http://blog.ej-technologies.com/2011/12/default-locale-changes-in-java-7.html
As Timmos stated the IllegalArgumentException results from the fact that you pass a String instead of a Locale.Category enum constant. The correct way to get the Locale.Category.FORMAT is by using java.lang.reflect.Field class:
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;
public class GetDefaultLocale {
public static void main(String[] args){
Locale locale = null;
try {
Class<?> LOCALE_CATEGORY_Class = Class.forName("java.util.Locale$Category");
Class<?> LOCALE_Class = Class.forName("java.util.Locale");
Class<?>[] paramTypes = { LOCALE_CATEGORY_Class };
Method m = LOCALE_Class.getMethod("getDefault", paramTypes);
Field FORMAT_Field = LOCALE_CATEGORY_Class.getField("FORMAT");
//we pass null because the FORMAT is an enumeration constant(the same applies for class variables)
Object FORMAT = FORMAT_Field.get(null);
locale = (Locale)m.invoke(LOCALE_CATEGORY_Class, new Object[]{FORMAT});
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//for jre 6
if(locale == null){
locale = Locale.getDefault();
}
}