Search Results

Search found 64 results on 3 pages for 'inetaddress'.

Page 1/3 | 1 2 3  | Next Page >

  • Avoid using InetAddress - Getting a raw IP address in network byte order

    - by Mylo
    Hey, I am trying to use the MaxMind GeoLite Country database on the Google App Engine. However, I am having difficulty getting the Java API to work as it relies on the InetAddress class which is not available to use on the App Engine. However, I am not sure if there is a simple workaround as it appears it only uses the InetAddress class to determine the IP of a given hostname. In my case, the hostname is always an IP anyway. What I need is a way to convert an IP address represented as a String into a byte array of network byte order (which the addr.getAddress() method of the InetAddress class provides). This is the code the current API uses, I need to find a way of removing all references to InetAddress whilst ensuring it still works! Thanks for your time. /** * Returns the country the IP address is in. * * @param ipAddress String version of an IP address, i.e. "127.0.0.1" * @return the country the IP address is from. */ public Country getCountry(String ipAddress) { InetAddress addr; try { addr = InetAddress.getByName(ipAddress); } catch (UnknownHostException e) { return UNKNOWN_COUNTRY; } return getCountry(bytesToLong(addr.getAddress())); }

    Read the article

  • Android Debugging InetAddress.isReachable

    - by badMonkey
    I am trying to figure out how to tell if a particular ipaddress is available in my android app during debugging ( I haven't tried this on an actual device ). From reading it appears that InetAddress.isReachable should do this for me. Initially I thought that I could code something like: InetAddress address = InetAddress.getByAddress( new byte[] { (byte) 192, (byte) 168, (byte) 254, (byte) 10 ); success = address.isReachable( 3000 ); This returns false even though I am reasonably sure it is a reachable address. I found that if I changed this to 127, 0, 0, 1 it returned success. My next attempt was same code, but I used the address I got from a ping of www.google.com ( 72.167.164.64 as of this writing ). No success. So then I tried a further example: int timeout = 2000; InetAddress[] addresses = InetAddress.getAllByName("www.google.com"); for (InetAddress address : addresses) { if ( address.isReachable(timeout)) { success = true; // just set a break point here } } I am relatively new to Java and Android so I suspect I am missing something, but I can't find anything that would indicate what that is.

    Read the article

  • InetAddress.getLocalHost() throws UnknownHostException

    - by jhwist
    Hi, I am testing our server-application (written Java) on different operating systems and thought that OpenSolaris (2008.11) would be the least troublesome due to the nice Java integration. Turns out I was wrong, as I end up with a UnknownHostException try { computerName = InetAddress.getLocalHost().getHostName(); if (computerName.indexOf(".") > -1) computerName = computerName.substring(0, computerName.indexOf(".")).toUpperCase(); } catch (UnknownHostException e) { e.printStackTrace(); } The output is: java.net.UnknownHostException: desvearth01: desvearth01 at java.net.InetAddress.getLocalHost(InetAddress.java:1353) However, nslookup desvearth01 returns the correct IP address, and nslookup localhost returns 127.0.0.1 as expected. Also, the same code works perfectly on FreeBSD. Is there anything special to OpenSolaris that I am not aware of? Any hints appreciated, thanks.

    Read the article

  • isReachable in Java doesn't appear to be working quite the way it's supposed to

    - by Rayne
    I'm using Clojure, but I can read Java, so this isn't a Clojure specific question. This doesn't even seem to be working from Java. I'm trying to implement a bit of a 'ping' function using isReachable. The code I'm using is this: (.isReachable (java.net.InetAddress/getByName "www.microsoft.com") 5000) Translated to Java by a good friend of mine: public class NetTest { public static void main (String[] args) throws Exception{ String host = "acidrayne.net"; InetAddress a = InetAddress.getByName(host); System.out.println(a.isReachable(10000)); } } Both of these return false. I suppose I must be doin' it wrong, but Google research is telling me differently. I'm confuzzled!

    Read the article

  • Problem with tomcat and getLocalHost exception

    - by xain
    I'm running a Linux server named S1 in a "cloud" server, and when tomcat 6.0.24 starts, I get the exception: org.apache.catalina.connector.Connector pause SEVERE: Protocol handler pause failed java.net.UnknownHostException: S1: S1 at java.net.InetAddress.getLocalHost(InetAddress.java:1353) at org.apache.jk.common.ChannelSocket.unLockSocket(ChannelSocket.java:485) Which then leads to: ERROR ehcache.Cache - Unable to set localhost. This prevents creation of a GUID. Cause was: Sjira1: S1 java.net.UnknownHostException: S1: S1 at java.net.InetAddress.getLocalHost(InetAddress.java:1353) at net.sf.ehcache.Cache.<clinit>(Cache.java:143) My hosts file is: 127.0.0.1 localhost localhost.localdomain (valid-ip-address) S1 S1.(valid domain name) ping S1 and S1.(valid domain name) return valid ip address nslookup S1.(valid domain name) returns valid ip address nslookup S1 throws ** server can't find S1: NXDOMAIN Any ideas about how to fix this ? Thanks

    Read the article

  • Problem with tomcat and getLocalHost exception

    - by xain
    I'm running a Linux server named S1 in a "cloud" server, and when tomcat 6.0.24 starts, I get the exception: org.apache.catalina.connector.Connector pause SEVERE: Protocol handler pause failed java.net.UnknownHostException: S1: S1 at java.net.InetAddress.getLocalHost(InetAddress.java:1353) at org.apache.jk.common.ChannelSocket.unLockSocket(ChannelSocket.java:485) Which then leads to: ERROR ehcache.Cache - Unable to set localhost. This prevents creation of a GUID. Cause was: Sjira1: S1 java.net.UnknownHostException: S1: S1 at java.net.InetAddress.getLocalHost(InetAddress.java:1353) at net.sf.ehcache.Cache.<clinit>(Cache.java:143) My hosts file is: 127.0.0.1 localhost localhost.localdomain (valid-ip-address) S1 S1.(valid domain name) ping S1 and S1.(valid domain name) return valid ip address nslookup S1.(valid domain name) returns valid ip address nslookup S1 throws ** server can't find S1: NXDOMAIN Any ideas about how to fix this ? Thanks

    Read the article

  • Android UnknownHost in asyncTask - loading web page

    - by Sneha
    I followed this tutorial for AsyncTask and getting the following error log: 03-23 11:44:42.936: WARN/System.err(315): java.net.UnknownHostException: www.google.co.in 03-23 11:44:42.936: WARN/System.err(315): at java.net.InetAddress.lookupHostByName(InetAddress.java:513) 03-23 11:44:42.936: WARN/System.err(315): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:278) 03-23 11:44:42.936: WARN/System.err(315): at java.net.InetAddress.getAllByName(InetAddress.java:242) 03-23 11:44:42.936: WARN/System.err(315): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136) 03-23 11:44:42.936: WARN/System.err(315): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 03-23 11:44:42.936: WARN/System.err(315): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 03-23 11:44:42.936: WARN/System.err(315): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348) 03-23 11:44:42.936: WARN/System.err(315): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 03-23 11:44:42.936: WARN/System.err(315): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 03-23 11:44:42.944: WARN/System.err(315): at org.apache.http.impl.client.AbstractHttpC lient.execute(AbstractHttpClient.java:465) 03-23 11:44:42.944: WARN/System.err(315): at com.test.async.AsyncTaskExampleActivity$DownloadWebPageTask.doInBackground (AsyncTaskExampleActivity.java:36) 03-23 11:44:42.944: WARN/System.err(315): at com.test.async.AsyncTaskExampleActivity$DownloadWebPageTask.doInBackground (AsyncTaskExampleActivity.java:1) 03-23 11:44:42.944: WARN/System.err(315): at android.os.AsyncTask$2.call(AsyncTask.java:185) 03-23 11:44:42.944: WARN/System.err(315): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 03-23 11:44:42.944: WARN/System.err(315): at java.util.concurrent.FutureTask.run (FutureTask.java:137) 03-23 11:44:42.944: WARN/System.err(315): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 03-23 11:44:42.944: WARN/System.err(315): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 03-23 11:44:42.944: WARN/System.err(315): at java.lang.Thread.run(Thread.java:1096) How do i fix it?? My Code: public class AsyncTaskExampleActivity extends Activity { private TextView textView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(R.id.TextView01); } private class DownloadWebPageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String response = ""; Log.i("", "in doInBackgroundddddddddd.........."); Log.i("", "in readWebpageeeeeeeeeeeee"); /* * try { InetAddress i = * InetAddress.getByName("http://google.co.in"); } catch * (UnknownHostException e1) { e1.printStackTrace(); } */ for (String url : urls) { Log.i("", "in for looooooop doInBackgroundddddddddd.........."); DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { Log .i("", "afetr for looooooop try doInBackgroundddddddddd.........."); HttpResponse execute = client.execute(httpGet); Log .i("", "afetr for looooooop try client ..execute doInBackgroundddddddddd.........."); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader( new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; Log .i("", "afetr while looooooop try client ..execute doInBackgroundddddddddd.........."); } } catch (Exception e) { e.printStackTrace(); } } Log .i("", "afetr lasttttttttttttt b4 response doInBackgroundddddddddd.........."); return response; } @Override protected void onPostExecute(String result) { Log.i("", "in onPostExecuteeee.........."); textView.setText(result); } } public void readWebpage(View view) { /* * System.setProperty("http.proxyHost", "10.132.116.10"); * System.setProperty("http.proxyPort", "3128"); */ DownloadWebPageTask task = new DownloadWebPageTask(); task.execute(new String[] { "http://google.co.in" }); Log.i("", "in readWebpageeeeeeeeeeeee after execute.........."); } } main.xml: <Button android:id="@+id/readWebpage" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="readWebpage" android:text="Load Webpage"> </Button> <TextView android:id="@+id/TextView01" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Example Text"> </TextView> Manifest: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.test.async" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".AsyncTaskExampleActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> Thanks Sneha

    Read the article

  • How to marshall non-string objects with JAXB and Spring

    - by lesula
    I was trying to follow this tutorial in order to create my own restful web-service using Spring framework. The client do a GET request to, let's say http://api.myapp/app/students and the server returns an xml version of the object classroom: @XmlRootElement(name = "class") public class Classroom { private String classId = null; private ArrayList<Student> students = null; public Classroom() { } public String getClassId() { return classId; } public void setClassId(String classId) { this.classId = classId; } @XmlElement(name="student") public ArrayList<Student> getStudents() { return students; } public void setStudents(ArrayList<Student> students) { this.students = students; } } The object Student is another bean containing only Strings. In my app-servlet.xml i copied this lines: <bean id="studentsView" class="org.springframework.web.servlet.view.xml.MarshallingView"> <constructor-arg ref="jaxbMarshaller" /> </bean> <!-- JAXB2 marshaller. Automagically turns beans into xml --> <bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller"> <property name="classesToBeBound"> <list> <value>com.spring.datasource.Classroom</value> <value>com.spring.datasource.Student</value> </list> </property> </bean> Now my question is: what if i wanted to insert some non-string objects as class variables? Let's say i want a tag containing the String version of an InetAddress, such as <inetAddress>192.168.1.1</inetAddress> How can i force JAXB to call the method inetAddress.toString() in such a way that it appears as a String in the xml? In the returned xml non-string objects are ignored!

    Read the article

  • Eclipse gives me a weird error when compiling...

    - by Legend
    I have this function which returns a datatype InetAddress[] public InetAddress [] lookupAllHostAddr(String host) throws UnknownHostException { Name name = null; try { name = new Name(host); } catch (TextParseException e) { throw new UnknownHostException(host); } Record [] records = null; if (preferV6) records = new Lookup(name, Type.AAAA).run(); if (records == null) records = new Lookup(name, Type.A).run(); if (records == null && !preferV6) records = new Lookup(name, Type.AAAA).run(); if (records == null) throw new UnknownHostException(host); InetAddress[] array = new InetAddress[records.length]; for (int i = 0; i < records.length; i++) { Record record = records[i]; if (records[i] instanceof ARecord) { ARecord a = (ARecord) records[i]; array[i] = a.getAddress(); } else { AAAARecord aaaa = (AAAARecord) records[i]; array[i] = aaaa.getAddress(); } } return array; } Eclipse complains that the return type should be byte[][] but when I change the return type to byte[][], it complains that the function is returning the wrong data type. I'm stuck in a loop. Does anyone know what is happening here?

    Read the article

  • Getting the 'external' IP address in Java

    - by Caylem
    Hi I'm not too sure how to go about getting the external IP address of the machine as a computer outside of a network would see it. My following IPAddress class only gets the local IP address of the machine. Any help would be appreciated. Thanks. public class IPAddress { private InetAddress thisIp; private String thisIpAddress; private void setIpAdd(){ try{ InetAddress thisIp = InetAddress.getLocalHost(); thisIpAddress = thisIp.getHostAddress().toString(); } catch(Exception e){} } protected String getIpAddress(){ setIpAdd(); return thisIpAddress; } }

    Read the article

  • Interconnecting Emulator Instances Android

    - by blah01
    Hi all I want to communicate two emulators via DatagramSocket in Android. Each of them is a Node in a P2P system. Thus each of them has a server Thread and client Thread (created per GUI event). This is how I create server public static final String SERVERIP = "10.0.2.15"; //... run() { InetAddress serverAddr = InetAddress.getByName(SERVERIP); DatagramSocket socket = new DatagramSocket(SERVERPORT,serverAddr); while(true) { byte[] buf = new byte[29]; DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); //... } } The port is given by the user during initializing application. The client part (requesting some data) InetAddress serverAddr = InetAddress.getByName("10.0.2.2"); //... Log.i("Requester", "Trying to connect to device port = "+target); DatagramSocket socketJ = new DatagramSocket(); byte[] bufJ = Adaptor.createStringMsg(Adaptor.createJoingMsg(id, Location.getX(), Location.getY())).getBytes(); DatagramPacket packetJ = new DatagramPacket(bufJ, bufJ.length, serverAddr, target); Log.i("Requester", "Sending: '" + new String(bufJ) + "'"); socketJ.send(packetJ); Log.i("Requester", "Done."); Some additional info. The Node1 (emulatorA) has a server on port 8000 and Node2 (emulatorB) has a server on port 8001. The target port for "client part" is read properly. What tried to do is to set the redirection as such: //emulatorA redir add tcp:8000:8000 //emulatorB redir add tcp:8001:8001 However I can not get any communication beetwen those 2 emulators. As far as I understood the android tutorial about it should work like this redir add tcp:localhostPort:emulatorPort. I'm stuck with it :/. Can anyone point me the mistake or give some good advice. For the record while I was testing communication on a single device (client faking other node) everything worked, so I don't think there is a bug in the code. Btw does any one knows how can I get 2 set of logs for those 2 emulators (logA, logB)? It would help me a lot.

    Read the article

  • Error on MulticastSocket.joinGroup()

    - by Pedro Ghilardi
    I'm trying to execute a simple example of Multicast sockets on Java. MulticastSocket s = new MulticastSocket(6789); InetAddress group = InetAddress.getByName("230.1.1.1"); s.joinGroup(group); This code generates the error: IP_ADD_MEMBERSHIP failed (out of hardware filters?) Any idea? Thanks

    Read the article

  • Remotely connecting two non-local computers with sockets

    - by Velizar Hristov
    This question seems like something very obvious to ask, and yet I spent more than an hour trying to find an answer. First I host and wait for someone to connect. Then, from another instance of the application, I try to connect with a socket - for the constructor, I use InetAddress, port. The port is always right, and everything works if I use "localhost" for the address. However, if I type my IP, I get an IOException. I even sent the application to someone else, gave him my IP, and it didn't work. The aim of the application is to connect two computers. It's in Java. Here is the relevant code. Server: ServerSocket serverSocket = new ServerSocket(port); Socket clientSocket = serverSocket.accept(); Client: InetAddress a = InetAddress.getByName(ip); Socket s = new Socket(a, port); I don't get past that. Obviously, the values of int port and String ip are taken from text fields. Edit: the purpose of my application is to connect two non-local computers.

    Read the article

  • Facebook android app keeps crashing even though there are no errors in my code. Why?

    - by user1554479
    If you import the facebook SDK library, the code works (ignore the deprecated methods for now lol) and there are no errors or warnings. However, when I run my facebook app on my Android 2.2 or 4.2 emulator, the app crashes either upon opening or after the log on screen. Why? Is it because I'm not implementing Async Task? If so, how does that work? Here's my code: package com.sara.facebookappl; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.StrictMode; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.facebook.android.DialogError; import com.facebook.android.Facebook; import com.facebook.android.Facebook.DialogListener; import com.facebook.android.FacebookError; import com.facebook.android.Util; public class MainActivity extends Activity implements OnClickListener, DialogListener { Facebook fb; ImageView button; SharedPreferences sp; TextView welcome; Button post; @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); post=(Button)findViewById(R.id.button1); String APP_ID = getString(R.string.APP_ID); fb= new Facebook(APP_ID); sp =getPreferences(MODE_PRIVATE); String access_token=sp.getString("access_token", null); long expires=sp.getLong("access_expires", 0); if (access_token !=null) { fb.setAccessToken(access_token); } if(expires !=0) { fb.setAccessExpires(expires); } button=(ImageView)findViewById(R.id.login); button.setOnClickListener((OnClickListener) this); updateButtonImage(); } @SuppressWarnings("deprecation") private void updateButtonImage() { // TODO Auto-generated method stub post.setVisibility(Button.VISIBLE); button.setImageResource(R.drawable.com_facebook_loginbutton_blue); //logout button if (fb.isSessionValid()) { button.setImageResource(R.drawable.com_facebook_loginbutton_blue); // ^logout button JSONObject obj=null; URL img_url =null; try { String jsonUser= fb.request("me"); obj = Util.parseJson(jsonUser); String id=obj.optString("id"); String name = obj.optString("name"); welcome.setText("Welcome, " + name); }catch(FacebookError e) { e.printStackTrace(); }catch (JSONException e) { e.printStackTrace(); }catch (MalformedURLException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } }else { post.setVisibility(Button.VISIBLE); button.setImageResource(R.drawable.com_facebook_loginbutton_blue); } } @SuppressWarnings("deprecation") public void buttonClicks(View v) { switch (v.getId()) { case R.id.button1: //post Bundle params= new Bundle(); params.putString("name", "User X"); params.putString("caption", "Rating"); params.putString("description", "User X Rated"); params.putString("link", "http://..."); fb.dialog(MainActivity.this, "feed", params, new Facebook.DialogListener() { @Override public void onFacebookError(FacebookError e) { // TODO Auto-generated method stub } @Override public void onError(DialogError e) { // TODO Auto-generated method stub } @Override public void onComplete(Bundle values) { // TODO Auto-generated method stub } @Override public void onCancel() { // TODO Auto-generated method stub } }); break; } } @SuppressWarnings("deprecation") public void onClick(View v) { if(fb.isSessionValid()) { try { fb.logout(getApplicationContext()); updateButtonImage(); //button will close our our session }catch(MalformedURLException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } }else{ //login into facebook fb.authorize(MainActivity.this, new String[] {"email"}, new Facebook.DialogListener() { @Override public void onFacebookError(FacebookError e) { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "fbError", Toast.LENGTH_SHORT).show(); } @Override public void onError(DialogError e) { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "onError", Toast.LENGTH_SHORT).show(); } @Override public void onComplete(Bundle values) { // TODO Auto-generated method stub Editor editor=sp.edit(); editor.putString("access_token", fb.getAccessToken()); editor.putLong("access_expires", fb.getAccessExpires()); editor.commit(); updateButtonImage(); } @Override public void onCancel() { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "onCancel", Toast.LENGTH_SHORT).show(); } }); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @SuppressWarnings("deprecation") @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); fb.authorizeCallback(requestCode, resultCode, data); } @Override public void onComplete(Bundle values) { // TODO Auto-generated method stub } @Override public void onFacebookError(FacebookError e) { // TODO Auto-generated method stub } @Override public void onError(DialogError e) { // TODO Auto-generated method stub } @Override public void onCancel() { // TODO Auto-generated method stub } } LogCat Errors: 12-16 04:56:59.070: E/AndroidRuntime(822): FATAL EXCEPTION: main 12-16 04:56:59.070: E/AndroidRuntime(822): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sara.facebookappl/com.sara.facebookappl.MainActivity}: android.os.NetworkOnMainThreadException 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.ActivityThread.access$600(ActivityThread.java:141) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.os.Handler.dispatchMessage(Handler.java:99) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.os.Looper.loop(Looper.java:137) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.ActivityThread.main(ActivityThread.java:5039) 12-16 04:56:59.070: E/AndroidRuntime(822): at java.lang.reflect.Method.invokeNative(Native Method) 12-16 04:56:59.070: E/AndroidRuntime(822): at java.lang.reflect.Method.invoke(Method.java:511) 12-16 04:56:59.070: E/AndroidRuntime(822): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 12-16 04:56:59.070: E/AndroidRuntime(822): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 12-16 04:56:59.070: E/AndroidRuntime(822): at dalvik.system.NativeStart.main(Native Method) 12-16 04:56:59.070: E/AndroidRuntime(822): Caused by: android.os.NetworkOnMainThreadException 12-16 04:56:59.070: E/AndroidRuntime(822): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 12-16 04:56:59.070: E/AndroidRuntime(822): at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 12-16 04:56:59.070: E/AndroidRuntime(822): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 12-16 04:56:59.070: E/AndroidRuntime(822): at java.net.InetAddress.getAllByName(InetAddress.java:214) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpConnection.(HttpConnection.java:70) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpConnection.(HttpConnection.java:50) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271) 12-16 04:56:59.070: E/AndroidRuntime(822): at com.facebook.android.Util.openUrl(Util.java:219) 12-16 04:56:59.070: E/AndroidRuntime(822): at com.facebook.android.Facebook.requestImpl(Facebook.java:806) 12-16 04:56:59.070: E/AndroidRuntime(822): at com.facebook.android.Facebook.request(Facebook.java:732) 12-16 04:56:59.070: E/AndroidRuntime(822): at com.sara.facebookappl.MainActivity.updateButtonImage(MainActivity.java:83) 12-16 04:56:59.070: E/AndroidRuntime(822): at com.sara.facebookappl.MainActivity.onCreate(MainActivity.java:63) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.Activity.performCreate(Activity.java:5104) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 12-16 04:56:59.070: E/AndroidRuntime(822): ... 11 more 12-16 04:56:59.090: D/dalvikvm(822): GC_CONCURRENT freed 150K, 9% free 2723K/2988K, paused 7ms+58ms, total 239ms

    Read the article

  • JBoss thrown error looking up local address when starting

    - by Jeeba
    Hello im installing a fresh Jboss 5.1 in a Centos 5.5 machine. I dont have Apache installed. So when I try to start jboss using the comand ./run.sh I get the following error 15:13:57,414 INFO [JMXKernel] Legacy JMX core initialized 15:14:03,856 ERROR [ServerInfo] Error looking up local address java.net.UnknownHostException: dhcppc1: dhcppc1 at java.net.InetAddress.getLocalHost(InetAddress.java:1354) at org.jboss.system.server.ServerInfo.getHostAddress(ServerInfo.java:364) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) .... After that i can run Jboss only from 127.0.0.1:8080 but using localhost:8080 doesnt work. I think its a centos configuration problem but im a total newbye managing ports and maybe firewalls, so what do you think could be the problem?

    Read the article

  • How does hadoop decide what its nodes hostnames are?

    - by Dan R
    Currently the urls generated by the jobtracker & namenode return either hostnames like bubbles.local or just bubbles. These end up not resolving unless the client machine has specified these in their /etc/hosts file. When I run the hostname command on these machines it returns a hostname complete with the domain (E.G bubbles.example.com) Running a small java test on these machines InetAddress addr = InetAddress.getLocalHost(); byte[] ipAddr = addr.getAddress(); String hostname = addr.getHostName(); System.out.println(hostname); Produces output just like the hostname command. Where else could hadoop be grabbing a hostname to use in its jobtracker / namenode UI? This is occurring in clusters with Hadoop 1.0.3 and 1.0.4-SNAPSHOT from early august. The machines are running CentOS release 5.8 (Final). The generated URLs I'm referring to are like this http://example:50075/browseDirectory.jsp?namenodeInfoPort=50070&dir=/ or http://example.local:50075/browseDirectory.jsp?namenodeInfoPort=50070&dir=/

    Read the article

  • Android never receives UDP packet

    - by Quandary
    The below code results in a timeout. It works fine on non-Android Java. What's the matter? //@Override public static void run() { //System.out.println ( "Local Machine IP : "+addrStr.toString ( ) ) ; HelloWorldActivity.tv.setText("Trace 1"); try { // Retrieve the ServerName InetAddress serverAddr; //= InetAddress.getByName(Server.SERVERIP); InetAddress ias[] = InetAddress.getAllByName(Server.SERVERNAME); serverAddr = ias[0]; Log.d("UDP", "C: Connecting..."); /* Create new UDP-Socket */ DatagramSocket socket = new DatagramSocket(); /* Prepare some data to be sent. */ String strQuery="ÿÿÿÿgetservers"+" "+Server.iProtocol+" "+"'all'"; Log.d("UDP", strQuery); //byte[] buf = ("ÿÿÿÿgetservers 68 'all'").getBytes(); byte[] buf = strQuery.getBytes(); /* Create UDP-packet with * data & destination(url+port) */ DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, Server.SERVERPORT); Log.d("UDP", "C: Sending: '" + new String(buf) + "'"); /* Send out the packet */ socket.setSoTimeout(5000); socket.send(packet); Log.d("UDP", "C: Sent."); Log.d("UDP", "C: Done."); // http://code.google.com/p/android/issues/detail?id=2917 byte[] buffer= new byte[1024*100]; DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length); //, serverAddr, Server.SERVERPORT); socket.receive(receivePacket); HelloWorldActivity.tv.setText("TTT"); String x = new String(receivePacket.getData()); Log.d("UDP", "C: Received: '" + x + "'"); HelloWorldActivity.tv.setText(x); } catch (Exception e) { HelloWorldActivity.tv.setText(e.getMessage()); Log.e("UDP", "C: Error", e); } } public class Server { /* //public static java.lang.string SERVERIP; public static String SERVERNAME = "monster.idsoftware.com"; public static String SERVERIP = "192.246.40.56"; public static int SERVERPORT = 27950; public static int PROTOCOL = 68; */ //public static String SERVERNAME="monster.idsoftware.com"; public static String SERVERNAME="dpmaster.deathmask.net"; public static String SERVERIP="192.246.40.56"; public static int SERVERPORT=27950; //public static int iProtocol= 68; // Quake3 public static int iProtocol=71; // OpenArena } Android manifest: <?xml version="1.0" encoding="utf-8"?> <use-permission id="android.permission.READ_CONTACTS" /> <use-permission android:name="android.permission.WRITE_SETTINGS" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.CALL_PHONE" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_GPS" /> <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" /> <uses-permission android:name="android.permission.ACCESS_CELL_ID" /> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <application android:icon="@drawable/icon" android:label="AAA New Application" > <activity android:name="HelloWorldActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application>

    Read the article

  • How to save image drawn on a JPanel?

    - by swift
    I have a panel with transparent background which i use to draw an image. now problem here is when i draw anything on panel and save the image as a JPEG file its saving the image with black background but i want it to be saved as same, as i draw on the panel. what should be done for this? plz guide me j Client.java public class Client extends Thread { static DatagramSocket datasocket; static DatagramSocket socket; Point point; Whiteboard board; Virtualboard virtualboard; JLayeredPane layerpane; BufferedImage image; public Client(DatagramSocket datasocket) { Client.datasocket=datasocket; } //This function is responsible to connect to the server public static void connect() { try { socket=new DatagramSocket (9000); //client connection socket port= 9000 datasocket=new DatagramSocket (9005); //client data socket port= 9002 ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); //this is to tell server that this is a connection request dos.writeChar('c'); dos.close(); byte[]data=baos.toByteArray(); //Server IP address InetAddress ip=InetAddress.getByName("10.123.97.154"); //create the UDP packet DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8000); socket.send(packet); Client client=new Client(datasocket); client.createFrame(); client.run(); } catch(Exception e) { e.printStackTrace(); } } //This function is to create the JFrame public void createFrame() { JFrame frame=new JFrame("Whiteboard"); frame.setVisible(true); frame.setBackground(Color.black); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(680,501); frame.addWindowListener(new WindowAdapter() { public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { close(); } }); layerpane=frame.getLayeredPane(); board= new Whiteboard(datasocket); image = new BufferedImage(590,463, BufferedImage.TYPE_INT_ARGB); board.setBounds(74,2,590,463); board.setImage(image); virtualboard=new Virtualboard(); virtualboard.setImage(image); virtualboard.setBounds(74,2,590,463); layerpane.add(virtualboard,new Integer(2));//Panel where remote user draws layerpane.add(board,new Integer(3)); layerpane.add(board.colourButtons(),new Integer(1)); layerpane.add(board.shapeButtons(),new Integer(0)); //frame.add(paper.addButtons(),BorderLayout.WEST); } /* * This function is overridden from the thread class * This function listens for incoming packets from the server * which contains the points drawn by the other client */ public void run () { while (true) { try { byte[] buffer = new byte[512]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); datasocket.receive(packet); InputStream in=new ByteArrayInputStream(packet.getData(), packet.getOffset(),packet.getLength()); DataInputStream din=new DataInputStream(in); int x=din.readInt(); int y=din.readInt(); String varname=din.readLine(); String var[]=varname.split("-",4); point=new Point(x,y); virtualboard.addPoint(point, var[0], var[1],var[2],var[3]); } catch (IOException ex) { ex.printStackTrace(); } } } //This function is to broadcast the newly drawn point to the server public void broadcast (Point p,String varname,String shape,String event, String color) { try { ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); dos.writeInt(p.x); dos.writeInt(p.y); dos.writeBytes(varname); dos.writeBytes("-"); dos.writeBytes(shape); dos.writeBytes("-"); dos.writeBytes(event); dos.writeBytes("-"); dos.writeBytes(color); dos.close(); byte[]data=baos.toByteArray(); InetAddress ip=InetAddress.getByName("10.123.97.154"); DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8002); datasocket.send(packet); } catch (Exception e) { e.printStackTrace(); } } //This function is to close the client's connection with the server public void close() { try { ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); //This is to tell server that this is request to remove the client dos.writeChar('r'); dos.close(); byte[]data=baos.toByteArray(); //Server IP address InetAddress ip=InetAddress.getByName("10.123.97.154"); DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8000); socket.send(packet); System.out.println("closed"); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { connect(); } } Whiteboard.java class Whiteboard extends JPanel implements MouseListener,MouseMotionListener,ActionListener,KeyListener { BufferedImage image; Boolean tooltip=false; int post; String shape; String selectedcolor="black"; Color color=Color.black; //Color color=Color.white; Point start; Point end; Point mp; Point tip; int keycode; String fillshape; Point fillstart=new Point(); Point fillend=new Point(); int noofside; Button r=new Button("rect"); Button rectangle=new Button("rect"); Button line=new Button("line"); Button roundrect=new Button("roundrect"); Button polygon=new Button("poly"); Button text=new Button("text"); JButton save=new JButton("Save"); Button elipse=new Button("elipse"); ImageIcon fillicon=new ImageIcon("images/fill.jpg"); JButton fill=new JButton(fillicon); ImageIcon erasericon=new ImageIcon("images/eraser.gif"); JButton erase=new JButton(erasericon); JButton[] colourbutton=new JButton[28]; String selected; Point label; String key=""; int ex,ey;//eraser DatagramSocket dataSocket; JButton button = new JButton("test"); Client client; Boolean first; int w,h; public Whiteboard(DatagramSocket dataSocket) { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } setLayout(null); setOpaque(false); setBackground(new Color(237,237,237)); this.dataSocket=dataSocket; client=new Client(dataSocket); addKeyListener(this); addMouseListener(this); addMouseMotionListener(this); setBorder(BorderFactory.createLineBorder(Color.black)); } public void paintComponent(Graphics g) { try { super.paintComponent(g); g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; if(color!=null) g2.setPaint(color); if(start!=null && end!=null) { if(selected==("elipse")) g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y)); else if(selected==("rect")) g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("rrect")) g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11); else if(selected==("line")) g2.drawLine(start.x,start.y,end.x,end.y); else if(selected==("poly")) { g2.drawLine(start.x,start.y,end.x,end.y); client.broadcast(start, "start", "poly", "drag", selectedcolor); client.broadcast(end, "end", "poly", "drag", selectedcolor); } } if(tooltip==true) { System.out.println(selected); if(selected=="text") { g2.drawString("|", tip.x, tip.y-5); g2.drawString("Click to add text", tip.x+10, tip.y+23); g2.drawString("__", label.x+post, label.y); } if(selected=="erase") { g2.setPaint(new Color(237,237,237)); g2.fillRect(tip.x-10,tip.y-10,10,10); g2.setPaint(color); g2.drawRect(tip.x-10,tip.y-10,10,10); } } } catch(Exception e) {} } //Function to draw the shape on image public void draw() { Graphics2D g2 = (Graphics2D) image.createGraphics(); Font font=new Font("Times New Roman",Font.PLAIN,14); g2.setFont(font); g2.setPaint(color); if(start!=null && end!=null) { if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); else if(selected=="elipse") g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("rrect")) g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11); else if(selected==("poly")) { g2.drawLine(start.x,start.y,end.x,end.y); client.broadcast(start, "start", "poly", "release", selectedcolor); client.broadcast(end, "end", "poly", "release", selectedcolor); } fillstart=start; fillend=end; fillshape=selected; } if(selected!="poly") { start=null; end=null; } if(label!=null) { if(selected==("text")) { g2.drawString(key,label.x,label.y); client.broadcast(label, key, "text", "release", selectedcolor); } } repaint(); g2.dispose(); } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.createGraphics(); Color erasecolor=new Color(237,237,237); pic.setPaint(erasecolor); if(start!=null) pic.fillRect(start.x-10, start.y-10, 10, 10); } //To set the size of the image public void setImage(BufferedImage image) { this.image = image; } //Function to add buttons into the panel, calling this function returns a panel public JPanel shapeButtons() { JPanel shape=new JPanel(); shape.setBackground(new Color(181, 197, 210)); shape.setLayout(new GridLayout(5,2,2,4)); shape.setBounds(0, 2, 74, 166); rectangle.addActionListener(this); rectangle.setToolTipText("Rectangle"); line.addActionListener( this); line.setToolTipText("Line"); erase.addActionListener(this); erase.setToolTipText("Eraser"); roundrect.addActionListener(this); roundrect.setToolTipText("Round edge Rectangle"); polygon.addActionListener(this); polygon.setToolTipText("Polygon"); text.addActionListener(this); text.setToolTipText("Text"); fill.addActionListener(this); fill.setToolTipText("Fill with colour"); elipse.addActionListener(this); elipse.setToolTipText("Elipse"); save.addActionListener(this); shape.add(elipse); shape.add(rectangle); shape.add(roundrect); shape.add(polygon); shape.add(line); shape.add(text); shape.add(fill); shape.add(erase); shape.add(save); return shape; } public JPanel colourButtons() { JPanel colourbox=new JPanel(); colourbox.setBackground(new Color(181, 197, 210)); colourbox.setLayout(new GridLayout(8,2,8,8)); colourbox.setBounds(0,323,70,140); //colourbox.add(empty); for(int i=0;i<16;i++) { colourbutton[i]=new JButton(); colourbox.add(colourbutton[i]); if(i==0) colourbutton[0].setBackground(Color.black); else if(i==1) colourbutton[1].setBackground(Color.white); else if(i==2) colourbutton[2].setBackground(Color.red); else if(i==3) colourbutton[3].setBackground(Color.orange); else if(i==4) colourbutton[4].setBackground(Color.blue); else if(i==5) colourbutton[5].setBackground(Color.green); else if(i==6) colourbutton[6].setBackground(Color.pink); else if(i==7) colourbutton[7].setBackground(Color.magenta); else if(i==8) colourbutton[8].setBackground(Color.cyan); else if(i==9) colourbutton[9].setBackground(Color.black); else if(i==10) colourbutton[10].setBackground(Color.yellow); else if(i==11) colourbutton[11].setBackground(new Color(131,168,43)); else if(i==12) colourbutton[12].setBackground(new Color(132,0,210)); else if(i==13) colourbutton[13].setBackground(new Color(193,17,92)); else if(i==14) colourbutton[14].setBackground(new Color(129,82,50)); else if(i==15) colourbutton[15].setBackground(new Color(64,128,128)); colourbutton[i].addActionListener(this); } return colourbox; } public void fill() { if(selected=="fill") { Graphics2D g2 = (Graphics2D) image.getGraphics(); g2.setPaint(color); System.out.println("Fill"); if(fillshape=="elipse") g2.fillOval(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y)); else if(fillshape=="rect") g2.fillRect(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y)); else if(fillshape==("rrect")) g2.fillRoundRect(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y),11,11); // else if(fillshape==("poly")) // g2.drawPolygon(x,y,2); } repaint(); } //To save the image drawn public void save() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos); JFileChooser fc = new JFileChooser(); fc.showSaveDialog(this); encoder.encode(image); byte[] jpgData = bos.toByteArray(); FileOutputStream fos = new FileOutputStream(fc.getSelectedFile()+".jpeg"); fos.write(jpgData); fos.close(); //add replce confirmation here } catch (IOException e) { System.out.println(e); } } public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent arg0) { } public void mousePressed(MouseEvent e) { if(selected=="line"||selected=="text") { start=e.getPoint(); client.broadcast(start,"start", selected,"press", selectedcolor); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") mp = e.getPoint(); else if(selected=="poly") { if(first==true) { start=e.getPoint(); //client.broadcast(start,"start", selected,"press", selectedcolor); } else if(first==false) { end=e.getPoint(); repaint(); //client.broadcast(end,"end", selected,"press", selectedcolor); } } else if(selected=="erase") { start=e.getPoint(); erase(); } } public void mouseReleased(MouseEvent e) { if(selected=="text") { System.out.println("Reset"); key=""; post=0; label=new Point(); label=e.getPoint(); grabFocus(); } if(start!=null && end!=null) { if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"release", selectedcolor); draw(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(end,"end", selected,"release", selectedcolor); draw(); } else if(selected=="poly") { draw(); first=false; start=end; end=null; } } } public void mouseDragged(MouseEvent e) { if(end==null) end = new Point(); if(start==null) start = new Point(); if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"drag", selectedcolor); } else if(selected=="erase") { start=e.getPoint(); erase(); client.broadcast(start,"start", selected,"drag", selectedcolor); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { start.x = Math.min(mp.x,e.getX()); start.y = Math.min(mp.y,e.getY()); end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(start,"start", selected,"drag", selectedcolor); client.broadcast(end,"end", selected,"drag", selectedcolor); } else if(selected=="poly") end=e.getPoint(); System.out.println(tooltip); if(tooltip==true) { if(selected=="erase") { Graphics2D g2=(Graphics2D) getGraphics(); tip=e.getPoint(); g2.drawRect(tip.x-10,tip.y-10,10,10); } } repaint(); } public void mouseMoved(MouseEvent e) { if(selected=="text" ||selected=="erase") { tip=new Point(); tip=e.getPoint(); tooltip=true; repaint(); } } public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; else if(e.getSource()==line) selected="line"; else if(e.getSource()==rectangle) selected="rect"; else if(e.getSource()==erase) { selected="erase"; tooltip=true; System.out.println(selected); erase(); } else if(e.getSource()==roundrect) selected="rrect"; else if(e.getSource()==polygon) { selected="poly"; first=true; start=null; } else if(e.getSource()==text) { selected="text"; tooltip=true; } else if(e.getSource()==fill) { selected="fill"; fill(); } else if(e.getSource()==save) save(); if(e.getSource()==colourbutton[0]) { color=Color.black; selectedcolor="black"; } else if(e.getSource()==colourbutton[1]) { color=Color.white; selectedcolor="white"; } else if(e.getSource()==colourbutton[2]) { color=Color.red; selectedcolor="red"; } else if(e.getSource()==colourbutton[3]) { color=Color.orange; selectedcolor="orange"; } else if(e.getSource()==colourbutton[4]) { selectedcolor="blue"; color=Color.blue; } else if(e.getSource()==colourbutton[5]) { selectedcolor="green"; color=Color.green; } else if(e.getSource()==colourbutton[6]) { selectedcolor="pink"; color=Color.pink; } else if(e.getSource()==colourbutton[7]) { selectedcolor="magenta"; color=Color.magenta; } else if(e.getSource()==colourbutton[8]) { selectedcolor="cyan"; color=Color.cyan; } } @Override public void keyPressed(KeyEvent e) { //System.out.println(e.getKeyChar()+" : "+e.getKeyCode()); if(label!=null) { if(e.getKeyCode()==10) //Check for Enter key { label.y=label.y+14; key=""; post=0; repaint(); } else if(e.getKeyCode()==8) //Backspace { try{ Graphics2D g2 = (Graphics2D) image.getGraphics(); g2.setPaint(new Color(237,237,237)); g2.fillRect(label.x+post-7, label.y-13, 14, 17); if(post>0) post=post-6; keycode=0; key=key.substring(0, key.length()-1); System.out.println(key.substring(0, key.length())); repaint(); Point broadcastlabel=new Point(); broadcastlabel.x=label.x+post-7; broadcastlabel.y=label.y-13; client.broadcast(broadcastlabel, key, "text", "backspace", selectedcolor); } catch(Exception ex) {} } //Block invalid keys else if(!(e.getKeyCode()>=16 && e.getKeyCode()<=20 || e.getKeyCode()>=112 && e.getKeyCode()<=123 || e.getKeyCode()>=33 && e.getKeyCode()<=40 || e.getKeyCode()>=144 && e.getKeyCode()<=145 || e.getKeyCode()>=524 && e.getKeyCode()<=525 ||e.getKeyCode()==27||e.getKeyCode()==155 ||e.getKeyCode()==127)) { key=key+e.getKeyChar(); post=post+6; draw(); } } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } } class Button extends JButton { String name; int i; public Button(String name) { this.name=name; try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } } public Button(int i) { this.i=i; } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g2.setStroke(new BasicStroke(1.2f)); if (name == "line") g.drawLine(5,5,30,30); if (name == "elipse") g.drawOval(5,7,25,20); if (name== "rect") g.drawRect(5,5,25,23); if (name== "roundrect") g.drawRoundRect(5,5,25,23,10,10); int a[]=new int[]{20,9,20,23,20}; int b[]=new int[]{9,23,25,20,9}; if (name== "poly") g.drawPolyline(a, b, 5); if (name== "text") g.drawString("Text",8, 24); } }

    Read the article

  • Why do I get a nullpointerexception at line ds.getPort in class L1?

    - by Fred
    import java.awt.; import java.awt.event.; import javax.swing.; import java.io.; import java.net.; import java.util.; public class Draw extends JFrame { /* * Socket stuff */ static String host; static int port; static int localport; DatagramSocket ds; Socket socket; Draw d; Paper p = new Paper(ds); public Draw(int localport, String host, int port) { d = this; this.localport = localport; this.host = host; this.port = port; try { ds = new DatagramSocket(localport); InetAddress ia = InetAddress.getByName(host); System.out.println("Attempting to connect DatagramSocket. Local port " + localport + " , foreign host " + host + ", foreign port " + port + "..."); ds.connect(ia, port); System.out.println("Success, ds.localport: " + ds.getLocalPort() + ", ds.port: " + ds.getPort() + ", address: " + ds.getInetAddress()); Reciever r = new Reciever(ds); r.start(); } catch (Exception e) { e.printStackTrace(); } setDefaultCloseOperation(EXIT_ON_CLOSE); getContentPane().add(p, BorderLayout.CENTER); setSize(640, 480); setVisible(true); } public static void main(String[] args) { int x = 0; for (String s : args){ if (x==0){ localport = Integer.parseInt(s); x++; } else if (x==1){ host = s; x++; } else if (x==2){ port = Integer.parseInt(s); } } Draw d = new Draw(localport, host, port); } } class Paper extends JPanel { DatagramSocket ds; private HashSet hs = new HashSet(); public Paper(DatagramSocket ds) { this.ds=ds; setBackground(Color.white); addMouseListener(new L1(ds)); addMouseMotionListener(new L2()); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.black); Iterator i = hs.iterator(); while(i.hasNext()) { Point p = (Point)i.next(); g.fillOval(p.x, p.y, 2, 2); } } private void addPoint(Point p) { hs.add(p); repaint(); } class L1 extends MouseAdapter { DatagramSocket ds; public L1(DatagramSocket ds){ this.ds=ds; } public void mousePressed(MouseEvent me) { addPoint(me.getPoint()); Point p = me.getPoint(); String message = Integer.toString(p.x) + " " + Integer.toString(p.y); System.out.println(message); try{ byte[] data = message.getBytes("UTF-8"); //InetAddress ia = InetAddress.getByName(ds.host); String convertedMessage = new String(data, "UTF-8"); System.out.println("The converted string is " + convertedMessage); DatagramPacket dp = new DatagramPacket(data, data.length); System.out.println(ds.getPort()); //System.out.println(message); //System.out.println(ds.toString()); //ds.send(dp); /*System.out.println("2Sending a packet containing data: " +data +" to " + ia + ":" + d.port + "...");*/ } catch (Exception e){ e.printStackTrace(); } } } class L2 extends MouseMotionAdapter { public void mouseDragged(MouseEvent me) { addPoint(me.getPoint()); Point p = me.getPoint(); String message = Integer.toString(p.x) + " " + Integer.toString(p.y); //System.out.println(message); } } } class Reciever extends Thread{ DatagramSocket ds; byte[] buffer; Reciever(DatagramSocket ds){ this.ds = ds; buffer = new byte[65507]; } public void run(){ try { DatagramPacket packet = new DatagramPacket(buffer, buffer.length); while(true){ try { ds.receive(packet); String s = new String(packet.getData()); System.out.println(s); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } }

    Read the article

  • Android HTTP Connection

    - by Ubersoldat
    Can anybody tell my why this doesn't work in the Android emulator? From the browser I have access and the server is internal. All I can think of is that I'm missing some configuration on my app so it can access the network layer. try { InetAddress server = Inet4Address.getByName("thehost"); //Doesn't work either //or InetAddress server2 = Inet4Address.getByAddress(new String("192.168.1.30").getBytes()); if(server.isReachable(5000)){ Log.d(TAG, "Ping!"); } Socket clientsocket = new Socket(server, 8080); } catch (UnknownHostException e) { Log.e(TAG, "Server Not Found"); } catch (IOException e) { Log.e(TAG, "Couldn't open socket"); } Throws an UnknownHostException Thanks

    Read the article

  • Formatting a byte array to string in java

    - by rgksugan
    I am using this code to find the MAC address of a machine.This code prints directly the MAC address, but i want to return it as a string.I am completely confused. please help. try { InetAddress add = InetAddress.getByName("10.123.96.102"); NetworkInterface ni1 = NetworkInterface.getByInetAddress(add); if (ni1 != null) { byte[] mac1 = ni1.getHardwareAddress(); if (mac1 != null) { for (int k = 0; k < mac1.length; k++) { System.out.format("%02X%s", mac1[k], (k < mac1.length - 1) ? "-" : ""); } } else { System.out.println("Address doesn't exist "); } System.out.println(); } else { System.out.println("address is not found."); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); }

    Read the article

  • how to retrive String from DatagramPacket

    - by sajith
    the following code prints [B@40545a60,[B@40545a60abc exp but i want to print abc,so that i can retrive the correct message from the receiving system public class Operation { InetAddress ip; DatagramSocket dsock; DatagramPacket pack1; byte[] bin,bout; WifyOperation(InetAddress Systemip) { ip=Systemip; try { dsock=new DatagramSocket(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } } void sendbyte() { String senddata="abc"+"123"; bout=senddata.getBytes(); pack1=new DatagramPacket(bout,bout.length,ip,3322); try { dsock.send(pack1); Log.d(pack1.getData().toString(),"abc exp"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } how i retrieve string instead of byte from the packet pack1

    Read the article

  • How to write an Android SocketServer to listen on wifi

    - by xioxox
    I've written a thread using java.net.SocketServer to listen on a particular port. It works fine in the android simulator (using port forwarding). I'm planning to connect over wifi to this port when the app is being used. However, the SocketServer documentation says that if you don't supply an InetAddress, the server listens on localhost. Am I correct that if I do not supply the address, I will not be able to get a connection over wifi? How can I get the InetAddress of the wifi connection to pass to the SocketServer?

    Read the article

  • IP Address not obtained in java

    - by nilesh
    This code used to return my local ip address as 192.xxx.x.xxx but now it is returning 127.0.0.1 . Please help me why the same code is returning different value. Is there something that I need to watch at linux OS. import java.util.*; import java.lang.*; import java.net.*; public class GetOwnIP { public static void main(String args[]) { try{ InetAddress ownIP=InetAddress.getLocalHost(); System.out.println("IP of my system is := "+ownIP.getHostAddress()); }catch (Exception e){ System.out.println("Exception caught ="+e.getMessage()); } } }

    Read the article

1 2 3  | Next Page >