Search Results

Search found 225 results on 9 pages for 'sendmessage'.

Page 9/9 | < Previous Page | 5 6 7 8 9 

  • Trying to send email in Java using gmail always results in username and password not accepted.

    - by Thaeos
    When I call the send method (after setting studentAddress), I get this: javax.mail.AuthenticationFailedException: 535-5.7.1 Username and Password not accepted. Learn more at 535 5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 y15sm906936wfd.10 I'm pretty sure the code is correct, and 100% positive that the username and password details I'm entering are correct. So is this something wrong with gmail or what? This is my code: import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class SendEmail { private String host = "smtp.gmail.com"; private String emailLogin = "[email protected]"; private String pass = "xxx"; private String studentAddress; private String to; private Properties props = System.getProperties(); public SendEmail() { props.put("mail.smtps.auth", "true"); props.put("mail.smtps.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", emailLogin); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); to = "[email protected]"; } public void setStudentAddress(String newAddress) { studentAddress = newAddress; } public void send() { Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(emailLogin)); InternetAddress[] studentAddressList = {new InternetAddress(studentAddress)}; message.setReplyTo(studentAddressList); message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Test Email"); message.setText("This is a test email!"); Transport transport = session.getTransport("smtps"); transport.connect(host, emailLogin, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (MessagingException me) { System.out.println("There has been an email error!"); me.printStackTrace(); } } } Any ideas...

    Read the article

  • How do I make a SignalR client something when it receives a message?

    - by Ben
    I want to do something when a client receives a message via a SignalR hub. I've put together a basic chat app, but want people to be able to "like" a chat comment. I'm thinking the way to do this is to find the chat message on the client's page and update it using javascript. In the meantime to "prove the concept" I just want to make an alert popup on the client machine to say another user likes the comment. Trouble is, I'm not sure where to put it. (Am struggling to find SignalR documentation to be honest.) can't get my head round what is calling what here. My ChatHub class is as follows: public class ChatHub : Hub { public void Send(string name, string message) { // Call the broadcastMessage method to update clients. Clients.All.broadcastMessage(name, message); } } And my JavaScript is: $(function () { // Declare a proxy to reference the hub. var chat = $.connection.chatHub; // Create a function that the hub can call to broadcast messages. chat.client.broadcastMessage = function (name, message) { // Html encode display name and message. var encodedName = $('<div />').text(name).html(); var encodedMsg = $('<div />').text(message).html(); // Add the message to the page. var divContent = $('#discussion').html(); $('#discussion').html('<div class="container">' + '<div class="content">' + '<p class="username">' + encodedName + '</p>' + '<p class="message">' + encodedMsg + '</p>' + '</div>' + '<div class="slideout">' + '<div class="clickme" onclick="slideMenu(this)"></div>' + '<div class="slidebutton"><img id="imgid" onclick="likeButtonClick(this)" src="Images/like.png" /></div>' + '<div class="slidebutton"><img onclick="commentButtonClick(this)" src="Images/comment.png" /></div>' + '<div class="slidebutton" style="margin-right:0px"><img onclick="redcardButtonClick(this)" src="Images/redcard.png" /></div>' + '</div>' + '</div>' + divContent); }; // Set initial focus to message input box. $('#message').focus(); // Start the connection. $.connection.hub.start().done(function () { $('#sendmessage').click(function () { // Call the Send method on the hub. chat.server.send($('#lblUser').html(), $('#message').val()); // Clear text box and reset focus for next comment. $('#message').val('').focus(); }); });

    Read the article

  • Whats wrong with this code.Runtime error

    - by javacode
    Hi I am writing this application in eclipse I added all the jar files.I am pasting the code and error.Please let me know what changes I should make to run the application properly. import javax.mail.*; import javax.mail.internet.*; import java.util.*; public class SendMail { public static void main(String [] args) { SendMail sm=new SendMail(); try{ sm.postMail(new String[]{"[email protected]"},"hi","hello","[email protected]"); } catch(MessagingException e) { e.printStackTrace(); } } public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException { boolean debug = false; //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.starttls.enable","true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.setProperty("mail.smtp.port", "25"); // create some properties and get the default Session Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject(subject); msg.setContent(message, "text/plain"); Transport.send(msg); } } Error: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. 13sm646598ewy.13 at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1829) at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1368) at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:886) at javax.mail.Transport.send0(Transport.java:191) at javax.mail.Transport.send(Transport.java:120) at SendMail.postMail(SendMail.java:54) at SendMail.main(SendMail.java:10)

    Read the article

  • send sms in asp.net by gsm modem

    - by danar jabbar
    I devloped an asp.net application to send sms from gsm modem to destination base on URL from the browser I used a library that developed by codeproject http://www.codeproject.com/articles/20420/how-to-send-and-receive-sms-using-gsm-modem but I get problem when I request form two browsers at same time and I want to make the my code detect that the modem is use by another process at the time here is my code: DeviceConnection deviceConnection = new DeviceConnection(); protected void Page_Load(object sender, EventArgs e) { try { if (Request.QueryString["destination"] != null && Request.QueryString["text"] != null) { deviceConnection.setBaudRate(9600); deviceConnection.setPort(12); deviceConnection.setTimeout(200); SendSms sendSms = new SendSms(deviceConnection); if (deviceConnection.getConnectionStatus()) { sendSms.strReciverNo = Request.QueryString["destination"]; sendSms.strTextMessage = Request.QueryString["text"]; if (sendSms.sendSms()) { Response.Write("Mesage successfuly sent to " + Request.QueryString["destination"]); } else { Response.Write("Message was not sent"); } } } } catch (Exception ex) { Console.WriteLine("Index "+ex.StackTrace); } } This is SendSms class: class SendSms { DeviceConnection deviceConnection; public SendSms(DeviceConnection deviceConnection) { this.deviceConnection = deviceConnection; } private string reciverNo; private string textMessage; private delegate void SetTextCallback(string text); public string strReciverNo { set { this.reciverNo = value; } get { return this.reciverNo; } } public string strTextMessage { set { this.textMessage = value; } get { return this.textMessage; } } public bool sendSms() { try { CommSetting.Comm_Port = deviceConnection.getPort();//GsmCommMain.DefaultPortNumber; CommSetting.Comm_BaudRate = deviceConnection.getBaudRate(); CommSetting.Comm_TimeOut = deviceConnection.getTimeout();//GsmCommMain.DefaultTimeout; CommSetting.comm = new GsmCommMain(deviceConnection.getPort() , deviceConnection.getBaudRate(), deviceConnection.getTimeout()); // CommSetting.comm.PhoneConnected += new EventHandler(comm_PhoneConnected); if (!CommSetting.comm.IsOpen()) { CommSetting.comm.Open(); } SmsSubmitPdu smsSubmitPdu = new SmsSubmitPdu(strTextMessage, strReciverNo, ""); smsSubmitPdu.RequestStatusReport = true; CommSetting.comm.SendMessage(smsSubmitPdu); CommSetting.comm.Close(); return true; } catch (Exception exception) { Console.WriteLine("sendSms " + exception.StackTrace); CommSetting.comm.Close(); return false; } } public void recive(object sender, EventArgs e) { Console.WriteLine("Message received successfuly"); } } }

    Read the article

  • Send Mail through Jsp page.

    - by sourabhtaletiya
    hi friends ,i have tried alot to send mail via jsp page but i am not succeded. A error is coming javax.servlet.ServletException: 530 5.7.0 Must issue a STARTTLS command first. x1sm5029316wbx.19 <html> <head> <title>JSP JavaMail Example </title> </head> <body> <%@ page import="java.util.*" %> <%@ page import="javax.mail.*" %> <%@ page import="javax.mail.internet.*" %> <%@ page import="javax.activation.*" %> <% java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable","true"); props.put("mail.smtp.starttls.required","true"); String host = "smtp.gmail.com"; String to = request.getParameter("to"); String from = request.getParameter("from"); String subject = request.getParameter("subject"); String messageText = request.getParameter("body"); boolean sessionDebug = false; props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.port", "25"); props.put("mail.smtp.auth", "true"); props.put("mail.debug", "true"); props.put("mail.smtp.socketFactory.port","25"); props.put("mail.smtp.starttls.enable","true"); Session mailSession = Session.getDefaultInstance(props, null); mailSession.setDebug(sessionDebug); Message msg = new MimeMessage(mailSession); props.put("mail.smtp.starttls.enable","true"); msg.setFrom(new InternetAddress(from)); InternetAddress[] address = {new InternetAddress(to)}; msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setText(messageText); props.put("mail.smtp.starttls.enable","true"); Transport tr = mailSession.getTransport("smtp"); tr.connect(host, "sourabh.web7", "june251989"); msg.saveChanges(); // don't forget this props.put("mail.smtp.starttls.enable","true"); tr.sendMessage(msg, msg.getAllRecipients()); tr.close(); // Transport.send(msg); /* out.println("Mail was sent to " + to); out.println(" from " + from); out.println(" using host " + host + ".");*/ %> </table> </body> </html>

    Read the article

  • Spring.Net Message Selectors with compound statements don't seem to be working

    - by Jonathan Beerhalter
    I'm using Spring.NET to connect to ActiveMQ and do some fairly simple pub sub routing. Everything works fine when my selector is a simple expression like Car='Honda' but if I try a compound expression like Car='Honda' AND Make='Pilot' I never get any matches on my subscription. Here's the code to generate the subscription, does anyone see where I might be doing something wrong? public bool AddSubscription(string topicName, Dictionary<string,string> selectorList, GDException exp) { try { ActiveMQTopic topic = new ActiveMQTopic(topicName); string selectorString = ""; if (selectorList.Keys.Count == 0) { // Select all items for this topic selectorString = "2>1"; } else { foreach (string key in selectorList.Keys) { selectorString += key + " = '" + selectorList[key] + "'" + " AND "; } selectorString = selectorString.Remove(selectorString.Length - 5, 5); } IMessageConsumer consumer = this._subSession.CreateConsumer(topic, selectorString, false); if (consumer != null) { _consumers.Add(consumer); consumer.Listener += new MessageListener(HandleRecieveMessage); return true; } else { exp.SetValues("Error adding subscription, null consumer returned"); return false; } } catch (Exception ex) { exp.SetValues(ex); return false; } } And then the code to send the message, which seems simple enough to me public void SendMessage(GDPubSubMessage messageToSend) { if (!this.isDisposed) { if (_producers.ContainsKey(messageToSend.Topic)) { IBytesMessage bytesMessage = this._pubSession.CreateBytesMessage(messageToSend.Payload); foreach (string key in messageToSend.MessageProperties.Keys) { bytesMessage.Properties.SetString(key, messageToSend.MessageProperties[key]); } _producers[messageToSend.Topic].Send(bytesMessage, false, (byte)255, TimeSpan.FromSeconds(1)); } else { ActiveMQTopic topic = new ActiveMQTopic(messageToSend.Topic); _producers.Add(messageToSend.Topic, this._pubSession.CreateProducer(topic)); IBytesMessage bytesMessage = this._pubSession.CreateBytesMessage(messageToSend.Payload); foreach (string key in messageToSend.MessageProperties.Keys) { bytesMessage.Properties.SetString(key, messageToSend.MessageProperties[key]); } _producers[messageToSend.Topic].Send(bytesMessage); } } else { throw new ObjectDisposedException(this.GetType().FullName); } } 07/102009: Update Ok, found the problem bytesMessage.Properties.SetString(key, messageToSend.MessageProperties[key]); This justs sets a single property, so my messages are only being tagged with a single property, hence the combo subscription never gets hit. Anyone know how to add more properties? You'd think bytesMessage.Properties would have a Add method, but it doesn't.

    Read the article

  • Several client waiting for the same event

    - by ff8mania
    I'm developing a communication API to be used by a lot of generic clients to communicate with a proprietary system. This proprietary system exposes an API, and I use a particular classes to send and wait messages from this system: obviously the system alert me that a message is ready using an event. The event is named OnMessageArrived. My idea is to expose a simple SendSyncMessage(message) method that helps the user/client to simply send a message and the method returns the response. The client: using ( Communicator c = new Communicator() ) { response = c.SendSync(message); } The communicator class is done in this way: public class Communicator : IDisposable { // Proprietary system object ExternalSystem c; String currentRespone; Guid currentGUID; private readonly ManualResetEvent _manualResetEvent; private ManualResetEvent _manualResetEvent2; String systemName = "system"; String ServerName = "server"; public Communicator() { _manualResetEvent = new ManualResetEvent(false); //This methods are from the proprietary system API c = SystemInstance.CreateInstance(); c.Connect(systemName , ServerName); } private void ConnectionStarter( object data ) { c.OnMessageArrivedEvent += c_OnMessageArrivedEvent; _manualResetEvent.WaitOne(); c.OnMessageArrivedEvent-= c_OnMessageArrivedEvent; } public String SendSync( String Message ) { Thread _internalThread = new Thread(ConnectionStarter); _internalThread.Start(c); _manualResetEvent2 = new ManualResetEvent(false); String toRet; int messageID; currentGUID = Guid.NewGuid(); c.SendMessage(Message, "Request", currentGUID.ToString()); _manualResetEvent2.WaitOne(); toRet = currentRespone; return toRet; } void c_OnMessageArrivedEvent( int Id, string root, string guid, int TimeOut, out int ReturnCode ) { if ( !guid.Equals(currentGUID.ToString()) ) { _manualResetEvent2.Set(); ReturnCode = 0; return; } object newMessage; c.FetchMessage(Id, 7, out newMessage); currentRespone = newMessage.ToString(); ReturnCode = 0; _manualResetEvent2.Set(); } } I'm really noob in using waithandle, but my idea was to create an instance that sends the message and waits for an event. As soon as the event arrived, checks if the message is the one I expect (checking the unique guid), otherwise continues to wait for the next event. This because could be (and usually is in this way) a lot of clients working concurrently, and I want them to work parallel. As I implemented my stuff, at the moment if I run client 1, client 2 and client 3, client 2 starts sending message as soon as client 1 has finished, and client 3 as client 2 has finished: not what I'm trying to do. Can you help me to fix my code and get my target? Thanks!

    Read the article

  • Android Thumbnail Loading Problem

    - by y ramesh rao
    I'm using a thumbnail loader in my project the one mentioned below. The problem is that the it loads all the thumbnails properly except the ones who's size is of about 40K. When our back end is giving that sort of thumbnails are not generated and sometimes this eventually leads to a Crash too. What m I supposed to do with this ? public class ThumbnailManager { private final Map<String, Bitmap> drawableMap; public static Context context; private Resources res; private int thumbnail_size; public ThumbnailManager() { drawableMap = new HashMap<String, Bitmap >(); res = new Resources(context.getAssets(), null, null); thumbnail_size = res.getInteger(R.ThumbnailManager.THUMBNAIL_SIZE); } public Bitmap fetchBitmap(String urlString) { if(drawableMap.containsKey(urlString)) { return (drawableMap.get(urlString)); } //Log.d(getClass().getSimpleName(), " Image URL :: "+ urlString); try { InputStream is = fetch(urlString); android.util.Log.v("ThumbnailManager", "ThumbnailManager " + urlString); drawableMap.put(urlString, BitmapFactory.decodeStream(is));//Bitmap.createScaledBitmap(BitmapFactory.decodeStream(is), thumbnail_size, thumbnail_size, false)); return drawableMap.get(urlString); } catch(Exception e) { android.util.Log.v("EXCEPTION", "EXCEPTION" + urlString); return null; } } public void fetchBitmapOnThread(final String urlString, final ImageView imageView) { if(drawableMap.containsKey(urlString)) { imageView.setImageBitmap(drawableMap.get(urlString)); return; } if(urlString.compareTo("AUDIO") == 0) { Bitmap audioThumb = BitmapFactory.decodeResource(context.getResources(), R.drawable.timeline_audio_thumb); drawableMap.put(urlString, Bitmap.createScaledBitmap(audioThumb, thumbnail_size, thumbnail_size, false)); imageView.setImageBitmap(drawableMap.get(urlString)); return; } final Handler handler = new Handler() { public void handleMessage(Message message) { imageView.setImageBitmap((Bitmap) message.obj); } }; Thread thread = new Thread() { public void run() { Bitmap urlBitmap = fetchBitmap(urlString); Message message = handler.obtainMessage(1, urlBitmap); handler.sendMessage(message); } }; thread.start(); } public InputStream fetch(String urlString) throws IOException, MalformedURLException { final URL url = new URL(urlString); final URLConnection conn = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(true); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); return(conn.getInputStream()); } }

    Read the article

  • ImageView place at center on click in gallery view

    - by TGMCians
    i used gallery view in which i place multiple imageview dynamically but on click imageview place at center and second question how to start first imageview from left of screen. I do not want to change the place until user scroll horizontally by finger . Is there any way to achieve this. Please help for this.. private class ImageAdapter extends BaseAdapter{ public ImageAdapter() { //To set blank at bottom and make visible TextView textView = (TextView)findViewById(R.id.textView2); textView.setVisibility(View.VISIBLE); //To set the visibility visible of gallery myGallery.setVisibility(View.VISIBLE); } public int getCount() { return ProductItemArray.Image_URL.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } public View getView(int position, View arg1, ViewGroup arg2) { ImageView bottomImageView = new ImageView(context); if(Helper.isTablet(context)) bottomImageView.setLayoutParams(new Gallery.LayoutParams(VirtualMirrorActivity.convertDpToPixel(100, context), VirtualMirrorActivity.convertDpToPixel(100, context))); else bottomImageView.setLayoutParams(new Gallery.LayoutParams(VirtualMirrorActivity.convertDpToPixel(80, context), VirtualMirrorActivity.convertDpToPixel(80, context))); UrlImageViewHelper.setUrlDrawable(bottomImageView, ProductItemArray.Image_URL[position]); bottomImageView.setBackgroundResource(R.layout.border); return bottomImageView; } } myGallery.setAdapter(new ImageAdapter()); myGallery.setSelection(1); myGallery.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, long arg3) { linearLayout.removeView(frameImageView); Thread newThread = new Thread(new Runnable() { public void run() { URL url_1 = null; try { isAlreadyExistInWishlist = false; VMProductListPaging.productUrl = ProductItemArray.Image_small_URL[position]; VMProductListPaging.productId = ProductItemArray.productId[position]; VMProductListPaging.productName = ProductItemArray.product_Name[position]; url_1 = new URL(ProductItemArray.Image_small_URL[position]); bmp = BitmapFactory.decodeStream(url_1.openConnection().getInputStream()); isExecuted = true; bitmapHandler.sendMessage(bitmapHandler.obtainMessage()); } catch (Exception e) { //Toast.makeText(context,"Sorry!! This link appears to be broken",Toast.LENGTH_LONG).show(); } } }); newThread.start(); } }); Layout.xml <Gallery android:id="@+id/galleryView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:spacing="5dp" android:layout_below="@+id/sendPhoto" android:layout_marginTop="10dp" android:visibility="gone"/>

    Read the article

  • HTML format using Java mail in android

    - by TheDevMan
    I am trying to implement an HTML format mail using the Java mail in android. I would like to get results like this: When I look at the html format sent from lookout in my GMAIL. I don't see any link, but just has this format: [image: Lookout_logo] [image: Signal_flare_icon] Your battery level is really low, so we located your device with Signal Flare. I was trying the following: Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", "true"); // added this line props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); javax.mail.Session session = javax.mail.Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses for( int i=0; i < to.length; i++ ) { // changed from a while loop toAddress[i] = new InternetAddress(to[i]); } message.setRecipients(Message.RecipientType.BCC, toAddress); message.setSubject(sub); //message.setText(body); body = "<!DOCTYPE html><html><body><img src=\"http://en.wikipedia.org/wiki/Krka_National_Park#mediaviewer/File:Krk_waterfalls.jpg\">"; message.setContent(body, "text/html; charset=utf-8"); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); When I look at the html format sent with the above code. I get the following: <!DOCTYPE html><html><body><img src="http://en.wikipedia.org/wiki/Krka_National_Park#mediaviewer/File:Krk_waterfalls.jpg> How to make sure the user will not be able to see any html code or URL link like the mail sent by LOOKOUT? Thanks!

    Read the article

  • Update UI in the main activity through handler in a thread (Android)

    - by Hrk
    Hello, I try to make several connection in a class and update the multiple progressbar in the main screen. But I've got the following error trying to use thread in android : Code: 05-06 13:13:11.092: ERROR/ConnectionManager(22854): ERROR:Can't create handler inside thread that has not called Looper.prepare() Here is a small part of my code in the main Activity public class Act_Main extends ListActivity { private ConnectionManager cm; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set up the window layout requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.main); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title); } public void startConnection() { //open DB connection db = new DBAdapter(getApplicationContext()); db.open(); cm = new ConnectionManager(handler, db); showDialog(DIALOG_PROGRESS_LOGIN); } @Override public void onStart() { super.onStart(); startConnection(); } protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_PROGRESS_LOGIN: progressDialog = new ProgressDialog(Act_Main.this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage("Connecting.\nPlease wait..."); progressThreadLogin = new ProgressThreadLogin(); progressThreadLogin.start(); return progressDialog; case DIALOG_PROGRESS_NETWORK: [b]progressDialog = new ProgressDialog(Act_Main.this);[/b] progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage("Loading entire network.\nPlease wait..."); progressThreadNetwork = new ProgressThreadNetwork(); progressThreadNetwork.start(); return progressDialog; default: return null; } } // Define the Handler that receives messages from the thread and update the progress final Handler handler = new Handler() { public void handleMessage(Message msg) { int total = msg.getData().getInt("total"); int step = msg.getData().getInt("step"); Log.d(TAG, "handleMessage:PROCESSBAR:"+total); progressDialog.setProgress(total); if (total >= 100) { switch (step) { case UPDATE_NETWORK: dismissDialog(DIALOG_PROGRESS_LOGIN); showDialog(DIALOG_PROGRESS_NETWORK); cm.getNetwork(); break; .... default: break; } } } }; private class ProgressThreadLogin extends Thread { ProgressThreadLogin() { } public void run() { cm.login(); } } private class ProgressThreadNetwork extends Thread { ProgressThreadNetwork() { } public void run() { cm.getNetwork(); } } } And my connectionManager class: public class ConnectionManager { public ConnectionManager(Handler handler, DBAdapter db) { this.handler = handler; this.db = db; } public void updateProgressBar(int step, int value) { if (value == 0) total = total+1; else total = value ; Message msg = handler.obtainMessage(); Bundle b = new Bundle(); b.putInt("total", total); b.putInt("step", step); msg.setData(b); handler.handleMessage(msg); } public void login() { //DO MY LOGIN TASK updateProgressBar(Act_Main.UPDATE_NETWORK, 100); } } The crash errors occurs on the first line of "case DIALOG_PROGRESS_NETWORK:". My first progressbar is hidden but the second one is not displayed. I think I've done somthing wrong using the threads and handlers but I dont' know why. I was first using handler.sendMessage in place of handler.handleMessage but when I had several task in my connectionManager, the progressbar was updated only at the end of all tasks. Thank you in advance for your help

    Read the article

  • Weblogic JMS System Error

    - by Jeune
    We're getting a JMS error which we don't have a lot to go with: org.springframework.jms.UncategorizedJmsException: Uncategorized exception occured during JMS processing; nested exception is weblogic.jms.common.JMSException:[JMSClientExceptions:055039] A system error has occurred. The error is java.lang.NullPointerException; nested exception is java.lang.NullPointerException at com.pg.ecom.jms.service.ProducerServices.SendMessageSync(ProducerServices.java:131) at com.pg.ecom.jms.service.ProducerServices.SendMessageSync(ProducerServices.java:115) at com.pg.ecom.jms.producer.FormsCRRProducer.sendMessage(FormsCRRProducer.java:56) at com.pg.ecom.cpgt.processruleagent.managerbean.forms.GenerateFormsManagerBean.useNewGetTemplateData(GenerateFormsManagerBean.java:522) at com.pg.ecom.cpgt.processruleagent.managerbean.forms.GenerateFormsManagerBean.doService(GenerateFormsManagerBean.java:114) at com.pg.ecom.fw.processcontainer.AbstractManagerBean.doServiceWrapper(AbstractManagerBean.java:175) at com.pg.ecom.fw.processcontainer.AbstractManagerBean.doServiceRequest(AbstractManagerBean.java:151) at com.pg.ecom.fw.processcontainer.AbstractServlet.doManagerBeanServiceAndPresentation(AbstractServlet.java:1911) at com.pg.ecom.cpgt.processunit.servlet.CportalParamServlet.doService(CportalParamServlet.java:107) at com.pg.ecom.fw.processcontainer.AbstractServlet.service(AbstractServlet.java:983) at javax.servlet.http.HttpServlet.service(HttpServlet.java:856) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227) at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283) at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:42) at com.pg.ecom.cpgt.processunit.filter.UploadMultipartFilter.doFilter(UploadMultipartFilter.java:28) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:42) at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3229) at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321) at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121) at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2002) at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:1908) at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1362) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209) at weblogic.work.ExecuteThread.run(ExecuteThread.java:181) The only lead I have is line 127 in the code which is indicated by this error: Caused by: weblogic.jms.common.JMSException: [JMSClientExceptions:055039]A system error has occurred. The error is java.lang.Nul lPointerException at weblogic.jms.client.JMSSession.handleException(JMSSession.java:2853) at weblogic.jms.client.JMSConsumer.receive(JMSConsumer.java:629) at weblogic.jms.client.JMSConsumer.receive(JMSConsumer.java:488) at weblogic.jms.client.WLConsumerImpl.receive(WLConsumerImpl.java:155) at org.springframework.jms.core.JmsTemplate.doReceive(JmsTemplate.java:734) at org.springframework.jms.core.JmsTemplate.doReceive(JmsTemplate.java:706) at org.springframework.jms.core.JmsTemplate$9.doInJms(JmsTemplate.java:681) at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:447) at org.springframework.jms.core.JmsTemplate.receiveSelected(JmsTemplate.java:679) at org.springframework.jms.core.JmsTemplate.receiveSelectedAndConvert(JmsTemplate.java:784) at com.pg.ecom.jms.service.ProducerServices.SendMessageSync(ProducerServices.java:127) ... 25 more This is line 127: try { Thread.yield(); //line 127 below status=(StatusMessageBean)getJmsTemplate.receiveSelectedAndConvert(statusDestination, "JMSCorrelationID='"+ producerMsg.getProcessID() +"'"); Thread.yield(); } catch (Exception e) { Thread.yield(); loggingInterface.doErrorLogging(e.fillInStackTrace()); } According to the BEA documentation, we should contact BEA about error 055039 but I would like to try asking here first before bringing this to them? Some more errors: Caused by: java.lang.NullPointerException at weblogic.jms.common.JMSVariableBinder$JMSCorrelationIDVariable.get(JMSVariableBinder.java:127) at weblogic.utils.expressions.Expression.evaluateExpr(Expression.java:271) at weblogic.utils.expressions.Expression.evaluateExpr(Expression.java:298) at weblogic.utils.expressions.Expression.evaluateBoolean(Expression.java:209) at weblogic.utils.expressions.Expression.evaluate(Expression.java:167) at weblogic.jms.common.JMSSQLFilter$Exp.evaluate(JMSSQLFilter.java:304) at weblogic.messaging.common.SQLFilter.match(SQLFilter.java:158) at weblogic.messaging.kernel.internal.MessageList.findNextVisible(MessageList.java:274) at weblogic.messaging.kernel.internal.QueueImpl.nextFromIteratorOrGroup(QueueImpl.java:441) at weblogic.messaging.kernel.internal.QueueImpl.nextMatchFromIteratorOrGroup(QueueImpl.java:350) at weblogic.messaging.kernel.internal.QueueImpl.get(QueueImpl.java:233) at weblogic.messaging.kernel.internal.QueueImpl.addReader(QueueImpl.java:1069) at weblogic.messaging.kernel.internal.ReceiveRequestImpl.start(ReceiveRequestImpl.java:178) at weblogic.messaging.kernel.internal.ReceiveRequestImpl.<init>(ReceiveRequestImpl.java:86) at weblogic.messaging.kernel.internal.QueueImpl.receive(QueueImpl.java:820) at weblogic.jms.backend.BEConsumerImpl.blockingReceiveStart(BEConsumerImpl.java:1172) at weblogic.jms.backend.BEConsumerImpl.receive(BEConsumerImpl.java:1383) at weblogic.jms.backend.BEConsumerImpl.invoke(BEConsumerImpl.java:1088) at weblogic.messaging.dispatcher.Request.wrappedFiniteStateMachine(Request.java:759) at weblogic.messaging.dispatcher.DispatcherImpl.dispatchAsyncInternal(DispatcherImpl.java:129) at weblogic.messaging.dispatcher.DispatcherImpl.dispatchAsync(DispatcherImpl.java:112) at weblogic.messaging.dispatcher.Request.dispatchAsync(Request.java:1046) at weblogic.jms.dispatcher.Request.dispatchAsync(Request.java:72) at weblogic.jms.frontend.FEConsumer.receive(FEConsumer.java:557) at weblogic.jms.frontend.FEConsumer.invoke(FEConsumer.java:806) at weblogic.messaging.dispatcher.Request.wrappedFiniteStateMachine(Request.java:759) at weblogic.messaging.dispatcher.DispatcherServerRef.invoke(DispatcherServerRef.java:276) at weblogic.messaging.dispatcher.DispatcherServerRef.handleRequest(DispatcherServerRef.java:141) at weblogic.messaging.dispatcher.DispatcherServerRef.access$000(DispatcherServerRef.java:36) at weblogic.messaging.dispatcher.DispatcherServerRef$2.run(DispatcherServerRef.java:112) ... 2 more Any ideas?

    Read the article

  • Problem with Java Mail : No provider for smtp

    - by user359198
    Hello all. I am using JavaMail to do a simple application that sends an email when it finds some files in a directory. I managed to get it worked from Eclipse. I Run the application and it sent the email with no errors. But, when I created the jar, and executed it, it fails in the email sending part. It gives this exception. javax.mail.NoSuchProviderException: No provider for smtp at javax.mail.Session.getProvider(Session.java:460) at javax.mail.Session.getTransport(Session.java:655) at javax.mail.Session.getTransport(Session.java:636) at main.java.util.MailManager.sendMail(MailManager.java:69) at main.java.DownloadsMail.composeAndSendMail(DownloadsMail.java:16) at main.java.DownloadsController.checkDownloads(DownloadsController.java:51) at main.java.MainDownloadsController.run(MainDownloadsController.java:26) at java.lang.Thread.run(Unknown Source) I am using the library in this method: public static boolean sendMail(String subject, String text){ noExceptionsThrown = true; try { loadProperties(); } catch (IOException e1) { System.out.println("Problem encountered while loading properties"); e1.printStackTrace(); noExceptionsThrown = false; } Properties mailProps = new Properties(); String host = "mail.smtp.host"; mailProps.setProperty(host, connectionProps.getProperty(host)); String tls = "mail.smtp.starttls.enable"; mailProps.setProperty(tls, connectionProps.getProperty(tls)); String port = "mail.smtp.port"; mailProps.setProperty(port, connectionProps.getProperty(port)); String user = "mail.smtp.user"; mailProps.setProperty(user, connectionProps.getProperty(user)); String auth = "mail.smtp.auth"; mailProps.setProperty(auth, connectionProps.getProperty(auth)); Session session = Session.getDefaultInstance(mailProps); //session.setDebug(true); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(messageProps.getProperty("from"))); message.addRecipient(Message.RecipientType.TO, new InternetAddress( messageProps.getProperty("to"))); message.setSubject(subject); message.setText(text); Transport t = session.getTransport("smtp"); try { t.connect(connectionProps.getProperty("user"), passwordProps .getProperty("password")); t.sendMessage(message, message.getAllRecipients()); } catch (Exception e) { System.out.println("Error encountered while sending the email"); e.printStackTrace(); noExceptionsThrown = false; } finally { t.close(); } } catch (Exception e) { System.out.println("Error encountered while creating the message"); e.printStackTrace(); noExceptionsThrown = false; } return noExceptionsThrown; } I am loading these values from properties files. mail.smtp.host=smtp.gmail.com mail.smtp.starttls.enable=true mail.smtp.port=587 mail.smtp.auth=true I have tried to change the host by ssl://smtp.gmail.com, the port by 465 (just for trying something different), but it doesn't work either. Anyway, if it works fine from Eclipse with the original parameters, I guess that the values are correct, but the problem is creating the jar. I don't know very much about the possible results or changes when creating a jar. Could the JavaMail libraries someway go wrong when the jar is created? Do you have any ideas? Thank you very much for your help.

    Read the article

  • JavaMail - javax.mail.MessagingException

    - by legendofawesomeness
    I am trying to write a simple mail sender class that would receive a bunch of arguments and using those will send an email out using our Exchange 2010 server. While authentication etc. seem to work fine, I am getting the following exception when the code is actually trying to send the email (I think). I have ensured that the authentication is working and I get a transport back from the session, but still it fails. Could anyone shed some like on what I am doing wrong or missing? Thanks. Exception: javax.mail.MessagingException: [EOF] at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:1481) at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1512) at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1054) at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:634) at javax.mail.Transport.send0(Transport.java:189) at javax.mail.Transport.send(Transport.java:140) at com.ri.common.mail.util.MailSender.sendHTMLEmail(MailSender.java:75) at com.ri.common.mail.util.MailSender.main(MailSender.java:106) Relevant code: import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class MailSender { public static void sendHTMLEmail( String fromEmailId, String toEmailId, String host, String hostUserName, String hostPassword, String mailSubject, String mailBody ) { // Get system properties. Properties props = System.getProperties(); // Setup mail server props.put( "mail.transport.protocol", "smtp" ); props.put( "mail.smtp.host", host ); props.put( "mail.smtp.auth", "true" ); final String hostUName = hostUserName; final String hPassword = hostPassword; Authenticator authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( hostUName, hPassword ); } }; // Get the default Session object. Session session = Session.getDefaultInstance( props, authenticator ); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage( session ); // Set From: header field of the header. message.setFrom( new InternetAddress( fromEmailId ) ); // Set To: header field of the header. message.addRecipient( Message.RecipientType.TO, new InternetAddress( toEmailId ) ); // Set Subject: header field message.setSubject( mailSubject ); // Send the actual HTML message, as big as you like message.setContent( mailBody, "text/html" ); // Send message Transport.send( message, message.getAllRecipients() ); System.out.println( "Sent message successfully...." ); } catch( Exception mex ) { mex.printStackTrace(); } } public static void main( String[] args ) { String to = "[email protected]"; String from = "[email protected]"; String host = "correctHostForExch2010"; String user = "correctUser"; String password = "CorrectPassword"; String subject = "Test Email"; String body = "Hi there. This is a test email!"; MailSender.sendHTMLEmail( from, to, host, user, password, subject, body ); } } EDIT: I turned on debugging and it says MAIL FROM:<[email protected]> 530 5.7.1 Client was not authenticated DEBUG SMTP: got response code 530, with response: 530 5.7.1 Client was not authenticated. Why would that be when the session authentication succeded?

    Read the article

  • How to implement wait(); to wait for a notifyAll(); from enter button?

    - by Dakota Miller
    Sorry for the confusion I posted the Worng Logcat info. I updated the question. I want to click Start to start a thread then when enter is clicked i want the thad to continue and get the message and handle the message in the thread then output it to the main thread and update the text view. How would i start a thread to wait for enter to be pressed and get the bundle for the Handler? Here is my Code: public class MainActivity extends Activity implements OnClickListener { Handler mHandler; Button enter; Button start; TextView display; String dateString; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); enter = (Button) findViewById(R.id.enter); start = (Button) findViewById(R.id.start); display = (TextView) findViewById(R.id.Display); enter.setOnClickListener(this); start.setOnClickListener(this); mHandler = new Handler() { <=============================This is Line 31 public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); Bundle bundle = msg.getData(); String string = bundle.getString("outKey"); display.setText(string); } }; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.enter: Message msgin = Message.obtain(); Bundle bundlein = new Bundle(); String in = "It Works!"; bundlein.putString("inKey", in); msgin.setData(bundlein); notifyAll(); break; case R.id.start: new myThread().hello.start(); break; } } public class myThread extends Thread { Thread hello = new Thread() { @Override public void run() { // TODO Auto-generated method stub super.run(); Looper.prepare(); try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Handler Mhandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); Bundle bundle = msg.getData(); dateString = bundle.getString("inKey"); } }; Looper.loop(); Message msg = Message.obtain(); Bundle bundle = new Bundle(); bundle.putString("outKey", dateString); msg.setData(bundle); mHandler.sendMessage(msg); } }; } } Here is the logcat info: 06-27 00:00:24.832: E/AndroidRuntime(18513): FATAL EXCEPTION: Thread-1210 06-27 00:00:24.832: E/AndroidRuntime(18513): java.lang.IllegalMonitorStateException: object not locked by thread before wait() 06-27 00:00:24.832: E/AndroidRuntime(18513): at java.lang.Object.wait(Native Method) 06-27 00:00:24.832: E/AndroidRuntime(18513): at java.lang.Object.wait(Object.java:364) 06-27 00:00:24.832: E/AndroidRuntime(18513): at com .example.learninghandlers.MainActivity$myThread$1.run(MainActivity.java:77)

    Read the article

  • why is my intent not useful?

    - by user1634887
    This is my first to ask here. I write the code for a Broadcast A start another Broadcast B. But the Broadcast B didn't get the intent's value. Broadcast A:get the sms contain message and start B public void onReceive(Context context, Intent intent) { Object[] pdus=(Object[])intent.getExtras().get("pdus"); for(Object pdu:pdus) { byte[] date=(byte[])pdu; SmsMessage message=SmsMessage.createFromPdu(date); String sender=message.getOriginatingAddress(); String body=message.getMessageBody(); if(sender.equals(AppUtil.herPhone)&&body.regionMatches(0, AppUtil.herSmsText, 0, 18)) { Toast.makeText(context, body, Toast.LENGTH_LONG).show(); String [] bodyArray=body.split(" "); String longitude=bodyArray[1]; String latitude=bodyArray[2]; **Intent uiIntent=new Intent(); Bundle bundle=new Bundle(); bundle.putString("longitude", longitude); bundle.putString("latitude", latitude); uiIntent.putExtras(bundle); uiIntent.setAction("android.janmac.location"); context.sendBroadcast(uiIntent);** abortBroadcast(); } } } Boardcast B: it nest in an Activity. register: button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { AppUtil.SendMessage(MainActivity.this); uiReceiver=new UIReceiver(); IntentFilter filter=new IntentFilter(); filter.addAction("android.janmac.location"); registerReceiver(uiReceiver, filter); } }); extend: private class UIReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.v("location","uireceiver????!"); **Bundle bundle=new Bundle(); bundle=intent.getExtras(); herLongitude=Double.valueOf(bundle.getString("longitude")); herLatitude=Double.valueOf(bundle.getString("latitude"));** } } but the bundle couldn't get any values. here is log: 08-30 11:17:40.494: D/AndroidRuntime(2359): Shutting down VM 08-30 11:17:40.514: W/dalvikvm(2359): threadid=1: thread exiting with uncaught exception (group=0x40018560) 08-30 11:17:40.544: E/AndroidRuntime(2359): FATAL EXCEPTION: main 08-30 11:17:40.544: E/AndroidRuntime(2359): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.janmac.location (has extras) } in com.example.locationclient.MainActivity$UIReceiver@40513690 08-30 11:17:40.544: E/AndroidRuntime(2359): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:722) 08-30 11:17:40.544: E/AndroidRuntime(2359): at android.os.Handler.handleCallback(Handler.java:587) 08-30 11:17:40.544: E/AndroidRuntime(2359): at android.os.Handler.dispatchMessage(Handler.java:92) 08-30 11:17:40.544: E/AndroidRuntime(2359): at android.os.Looper.loop(Looper.java:130) 08-30 11:17:40.544: E/AndroidRuntime(2359): at android.app.ActivityThread.main(ActivityThread.java:3835) 08-30 11:17:40.544: E/AndroidRuntime(2359): at java.lang.reflect.Method.invokeNative(Native Method) 08-30 11:17:40.544: E/AndroidRuntime(2359): at java.lang.reflect.Method.invoke(Method.java:507) 08-30 11:17:40.544: E/AndroidRuntime(2359): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864) 08-30 11:17:40.544: E/AndroidRuntime(2359): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622) 08-30 11:17:40.544: E/AndroidRuntime(2359): at dalvik.system.NativeStart.main(Native Method) 08-30 11:17:40.544: E/AndroidRuntime(2359): Caused by: java.lang.NumberFormatException 08-30 11:17:40.544: E/AndroidRuntime(2359): at org.apache.harmony.luni.util.FloatingPointParser.parseDblImpl(Native Method) 08-30 11:17:40.544: E/AndroidRuntime(2359): at org.apache.harmony.luni.util.FloatingPointParser.parseDouble(FloatingPointParser.java:283) 08-30 11:17:40.544: E/AndroidRuntime(2359): at java.lang.Double.parseDouble(Double.java:318) 08-30 11:17:40.544: E/AndroidRuntime(2359): at java.lang.Double.valueOf(Double.java:356) 08-30 11:17:40.544: E/AndroidRuntime(2359): at com.example.locationclient.MainActivity$UIReceiver.onReceive(MainActivity.java:231) 08-30 11:17:40.544: E/AndroidRuntime(2359): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:709) 08-30 11:17:40.544: E/AndroidRuntime(2359): ... 9 more enter code here

    Read the article

  • Windows Azure AppFabric: ServiceBus Queue WPF Sample

    - by xamlnotes
    The latest version of the AppFabric ServiceBus now has support for queues and topics. Today I will show you a bit about using queues and also talk about some of the best practices in using them. If you are just getting started, you can check out this site for more info on Windows Azure. One of the 1st things I thought if when Azure was announced back when was how we handle fault tolerance. Web sites hosted in Azure are no much of an issue unless they are using SQL Azure and then you must account for potential fault or latency issues. Today I want to talk a bit about ServiceBus and how to handle fault tolerance.  And theres stuff like connecting to the servicebus and so on you have to take care of. To demonstrate some of the things you can do, let me walk through this sample WPF app that I am posting for you to download. To start off, the application is going to need things like the servicenamespace, issuer details and so forth to make everything work.  To facilitate this I created settings in the wpf app for all of these items. Then I mapped a static class to them and set the values when the program loads like so: StaticElements.ServiceNamespace = Convert.ToString(Properties.Settings.Default["ServiceNamespace"]); StaticElements.IssuerName = Convert.ToString(Properties.Settings.Default["IssuerName"]); StaticElements.IssuerKey = Convert.ToString(Properties.Settings.Default["IssuerKey"]); StaticElements.QueueName = Convert.ToString(Properties.Settings.Default["QueueName"]);   Now I can get to each of these elements plus some other common values or instances directly from the StaticElements class. Now, lets look at the application.  The application looks like this when it starts:   The blue graphic represents the queue we are going to use.  The next figure shows the form after items were added and the queue stats were updated . You can see how the queue has grown: To add an item to the queue, click the Add Order button which displays the following dialog: After you fill in the form and press OK, the order is published to the ServiceBus queue and the form closes. The application also allows you to read the queued items by clicking the Process Orders button. As you can see below, the form shows the queued items in a list and the  queue has disappeared as its now empty. In real practice we normally would use a Windows Service or some other automated process to subscribe to the queue and pull items from it. I created a class named ServiceBusQueueHelper that has the core queue features we need. There are three public methods: * GetOrCreateQueue – Gets an instance of the queue description if the queue exists. if not, it creates the queue and returns a description instance. * SendMessageToQueue = This method takes an order instance and sends it to the queue. The call to the queue is wrapped in the ExecuteAction method from the Transient Fault Tolerance Framework and handles all the retry logic for the queue send process. * GetOrderFromQueue – Grabs an order from the queue and returns a typed order from the queue. It also marks the message complete so the queue can remove it.   Now lets turn to the WPF window code (MainWindow.xaml.cs). The constructor contains the 4 lines shown about to setup the static variables and to perform other initialization tasks. The next few lines setup certain features we need for the ServiceBus: TokenProvider credentials = TokenProvider.CreateSharedSecretTokenProvider(StaticElements.IssuerName, StaticElements.IssuerKey); Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", StaticElements.ServiceNamespace, string.Empty); StaticElements.CurrentNamespaceManager = new NamespaceManager(serviceUri, credentials); StaticElements.CurrentMessagingFactory = MessagingFactory.Create(serviceUri, credentials); The next two lines update the queue name label and also set the timer to 20 seconds.             QueueNameLabel.Content = StaticElements.QueueName;             _timer.Interval = TimeSpan.FromSeconds(20);             Next I call the UpdateQueueStats to initialize the UI for the queue:             UpdateQueueStats();             _timer.Tick += new EventHandler(delegate(object s, EventArgs a)                         {                      UpdateQueueStats();                  });             _timer.Start();         } The UpdateQueueStats method shown below. You can see that it uses the GetOrCreateQueue method mentioned earlier to grab the queue description, then it can get the MessageCount property.         private void UpdateQueueStats()         {             _queueDescription = _serviceBusQueueHelper.GetOrCreateQueue();             QueueCountLabel.Content = "(" + _queueDescription.MessageCount + ")";             long count = _queueDescription.MessageCount;             long queueWidth = count * 20;             QueueRectangle.Width = queueWidth;             QueueTickCount += 1;             TickCountlabel.Content = QueueTickCount.ToString();         }   The ReadQueueItemsButton_Click event handler calls the GetOrderFromQueue method and adds the order to the listbox. If you look at the SendQueueMessageController, you can see the SendMessage method that sends an order to the queue. Its pretty simple as it just creates a new CustomerOrderEntity instance,fills it and then passes it to the SendMessageToQueue. As you can see, all of our interaction with the queue is done through the helper class (ServiceBusQueueHelper). Now lets dig into the helper class. First, before you create anything like this, download the Transient Fault Handling Framework. Microsoft provides this free and they also provide the C# source. Theres a great article that shows how to use this framework with ServiceBus. I included the entire ServiceBusQueueHelper class in List 1. Notice the using statements for TransientFaultHandling: using Microsoft.AzureCAT.Samples.TransientFaultHandling; using Microsoft.AzureCAT.Samples.TransientFaultHandling.ServiceBus; The SendMessageToQueue in Listing 1 shows how to use the async send features of ServiceBus with them wrapped in the Transient Fault Handling Framework.  It is not much different than plain old ServiceBus calls but it sure makes it easy to have the fault tolerance added almost for free. The GetOrderFromQueue uses the standard synchronous methods to access the queue. The best practices article walks through using the async approach for a receive operation also.  Notice that this method makes a call to Receive to get the message then makes a call to GetBody to get a new strongly typed instance of CustomerOrderEntity to return. Listing 1 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.AzureCAT.Samples.TransientFaultHandling; using Microsoft.AzureCAT.Samples.TransientFaultHandling.ServiceBus; using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging; using System.Xml.Serialization; using System.Diagnostics; namespace WPFServicebusPublishSubscribeSample {     class ServiceBusQueueHelper     {         RetryPolicy currentPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(RetryPolicy.DefaultClientRetryCount);         QueueClient currentQueueClient;         public QueueDescription GetOrCreateQueue()         {                        QueueDescription queue = null;             bool createNew = false;             try             {                 // First, let's see if a queue with the specified name already exists.                 queue = currentPolicy.ExecuteAction<QueueDescription>(() => { return StaticElements.CurrentNamespaceManager.GetQueue(StaticElements.QueueName); });                 createNew = (queue == null);             }             catch (MessagingEntityNotFoundException)             {                 // Looks like the queue does not exist. We should create a new one.                 createNew = true;             }             // If a queue with the specified name doesn't exist, it will be auto-created.             if (createNew)             {                 try                 {                     var newqueue = new QueueDescription(StaticElements.QueueName);                     queue = currentPolicy.ExecuteAction<QueueDescription>(() => { return StaticElements.CurrentNamespaceManager.CreateQueue(newqueue); });                 }                 catch (MessagingEntityAlreadyExistsException)                 {                     // A queue under the same name was already created by someone else,                     // perhaps by another instance. Let's just use it.                     queue = currentPolicy.ExecuteAction<QueueDescription>(() => { return StaticElements.CurrentNamespaceManager.GetQueue(StaticElements.QueueName); });                 }             }             currentQueueClient = StaticElements.CurrentMessagingFactory.CreateQueueClient(StaticElements.QueueName);             return queue;         }         public void SendMessageToQueue(CustomerOrderEntity Order)         {             BrokeredMessage msg = null;             GetOrCreateQueue();             // Use a retry policy to execute the Send action in an asynchronous and reliable fashion.             currentPolicy.ExecuteAction             (                 (cb) =>                 {                     // A new BrokeredMessage instance must be created each time we send it. Reusing the original BrokeredMessage instance may not                     // work as the state of its BodyStream cannot be guaranteed to be readable from the beginning.                     msg = new BrokeredMessage(Order);                     // Send the event asynchronously.                     currentQueueClient.BeginSend(msg, cb, null);                 },                 (ar) =>                 {                     try                     {                         // Complete the asynchronous operation.                         // This may throw an exception that will be handled internally by the retry policy.                         currentQueueClient.EndSend(ar);                     }                     finally                     {                         // Ensure that any resources allocated by a BrokeredMessage instance are released.                         if (msg != null)                         {                             msg.Dispose();                             msg = null;                         }                     }                 },                 (ex) =>                 {                     // Always dispose the BrokeredMessage instance even if the send                     // operation has completed unsuccessfully.                     if (msg != null)                     {                         msg.Dispose();                         msg = null;                     }                     // Always log exceptions.                     Trace.TraceError(ex.Message);                 }             );         }                 public CustomerOrderEntity GetOrderFromQueue()         {             CustomerOrderEntity Order = new CustomerOrderEntity();             QueueClient myQueueClient = StaticElements.CurrentMessagingFactory.CreateQueueClient(StaticElements.QueueName, ReceiveMode.PeekLock);             BrokeredMessage message;             ServiceBusQueueHelper serviceBusQueueHelper = new ServiceBusQueueHelper();             QueueDescription queueDescription;             queueDescription = serviceBusQueueHelper.GetOrCreateQueue();             if (queueDescription.MessageCount > 0)             {                 message = myQueueClient.Receive(TimeSpan.FromSeconds(90));                 if (message != null)                 {                     try                     {                         Order = message.GetBody<CustomerOrderEntity>();                         message.Complete();                     }                     catch (Exception ex)                     {                         throw ex;                     }                 }                 else                 {                     throw new Exception("Did not receive the messages");                 }             }             return Order;         }     } } I will post a link to the download demo in a separate post soon.

    Read the article

  • How to handle screen orientation change when progress dialog and background thread active?

    - by Heikki Toivonen
    My program does some network activity in a background thread. Before starting, it pops up a progress dialog. The dialog is dismissed on the handler. This all works fine, except when screen orientation changes while the dialog is up (and the background thread is going). At this point the app either crashes, or deadlocks, or gets into a weird stage where the app does not work at all until all the threads have been killed. How can I handle the screen orientation change gracefully? The sample code below matches roughly what my real program does: public class MyAct extends Activity implements Runnable { public ProgressDialog mProgress; // UI has a button that when pressed calls send public void send() { mProgress = ProgressDialog.show(this, "Please wait", "Please wait", true, true); Thread thread = new Thread(this); thread.start(); } public void run() { Thread.sleep(10000); Message msg = new Message(); mHandler.sendMessage(msg); } private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { mProgress.dismiss(); } }; } Stack: E/WindowManager( 244): Activity MyAct has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@433b7150 that was originally added here E/WindowManager( 244): android.view.WindowLeaked: Activity MyAct has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@433b7150 that was originally added here E/WindowManager( 244): at android.view.ViewRoot.<init>(ViewRoot.java:178) E/WindowManager( 244): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:147) E/WindowManager( 244): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:90) E/WindowManager( 244): at android.view.Window$LocalWindowManager.addView(Window.java:393) E/WindowManager( 244): at android.app.Dialog.show(Dialog.java:212) E/WindowManager( 244): at android.app.ProgressDialog.show(ProgressDialog.java:103) E/WindowManager( 244): at android.app.ProgressDialog.show(ProgressDialog.java:91) E/WindowManager( 244): at MyAct.send(MyAct.java:294) E/WindowManager( 244): at MyAct$4.onClick(MyAct.java:174) E/WindowManager( 244): at android.view.View.performClick(View.java:2129) E/WindowManager( 244): at android.view.View.onTouchEvent(View.java:3543) E/WindowManager( 244): at android.widget.TextView.onTouchEvent(TextView.java:4664) E/WindowManager( 244): at android.view.View.dispatchTouchEvent(View.java:3198) E/WindowManager( 244): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:857) E/WindowManager( 244): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:857) E/WindowManager( 244): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:857) E/WindowManager( 244): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:857) E/WindowManager( 244): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:857) E/WindowManager( 244): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1593) E/WindowManager( 244): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1089) E/WindowManager( 244): at android.app.Activity.dispatchTouchEvent(Activity.java:1871) E/WindowManager( 244): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1577) E/WindowManager( 244): at android.view.ViewRoot.handleMessage(ViewRoot.java:1140) E/WindowManager( 244): at android.os.Handler.dispatchMessage(Handler.java:88) E/WindowManager( 244): at android.os.Looper.loop(Looper.java:123) E/WindowManager( 244): at android.app.ActivityThread.main(ActivityThread.java:3739) E/WindowManager( 244): at java.lang.reflect.Method.invokeNative(Native Method) E/WindowManager( 244): at java.lang.reflect.Method.invoke(Method.java:515) E/WindowManager( 244): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739) E/WindowManager( 244): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:497) E/WindowManager( 244): at dalvik.system.NativeStart.main(Native Method) and: W/dalvikvm( 244): threadid=3: thread exiting with uncaught exception (group=0x4000fe68) E/AndroidRuntime( 244): Uncaught handler: thread main exiting due to uncaught exception E/AndroidRuntime( 244): java.lang.IllegalArgumentException: View not attached to window manager E/AndroidRuntime( 244): at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:331) E/AndroidRuntime( 244): at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:200) E/AndroidRuntime( 244): at android.view.Window$LocalWindowManager.removeView(Window.java:401) E/AndroidRuntime( 244): at android.app.Dialog.dismissDialog(Dialog.java:249) E/AndroidRuntime( 244): at android.app.Dialog.access$000(Dialog.java:59) E/AndroidRuntime( 244): at android.app.Dialog$1.run(Dialog.java:93) E/AndroidRuntime( 244): at android.app.Dialog.dismiss(Dialog.java:233) E/AndroidRuntime( 244): at MyAct$1.handleMessage(MyAct.java:321) E/AndroidRuntime( 244): at android.os.Handler.dispatchMessage(Handler.java:88) E/AndroidRuntime( 244): at android.os.Looper.loop(Looper.java:123) E/AndroidRuntime( 244): at android.app.ActivityThread.main(ActivityThread.java:3739) E/AndroidRuntime( 244): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime( 244): at java.lang.reflect.Method.invoke(Method.java:515) E/AndroidRuntime( 244): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739) E/AndroidRuntime( 244): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:497) E/AndroidRuntime( 244): at dalvik.system.NativeStart.main(Native Method) I/Process ( 46): Sending signal. PID: 244 SIG: 3 I/dalvikvm( 244): threadid=7: reacting to signal 3 I/dalvikvm( 244): Wrote stack trace to '/data/anr/traces.txt' I/Process ( 244): Sending signal. PID: 244 SIG: 9 I/ActivityManager( 46): Process MyAct (pid 244) has died. I have tried to dismiss the progress dialog in onSaveInstanceState, but that just prevents an immediate crash. The background thread is still going, and the UI is in partially drawn state. Need to kill the whole app before it starts working again.

    Read the article

  • mfc tab control switch tabs

    - by MRM
    I created a simple tab control that has 2 tabs (each tab is a different dialog). The thing is that i don't have any idea how to switch between tabs (when the user presses Titlu Tab1 to show the dialog i made for the first tab, and when it presses Titlu Tab2 to show my other dialog). I added a handler for changing items, but i don't know how should i acces some kind of index or child for tabs. Tab1.h and Tab2.h are headers for dialogs that show only static texts with the name of the each tab. There may be an obvious answer to my question, but i am a real newbie in c++ and MFC. This is my header: // CTabControlDlg.h : header file // #pragma once #include "afxcmn.h" #include "Tab1.h" #include "Tab2.h" // CCTabControlDlg dialog class CCTabControlDlg : public CDialog { // Construction public: CCTabControlDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data enum { IDD = IDD_CTABCONTROL_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: HICON m_hIcon; // Generated message map functions virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: CTabCtrl m_tabcontrol1; CTab1 m_tab1; CTab2 m_tab2; afx_msg void OnTcnSelchangeTabcontrol(NMHDR *pNMHDR, LRESULT *pResult); }; And this is the .cpp: // CTabControlDlg.cpp : implementation file // #include "stdafx.h" #include "CTabControl.h" #include "CTabControlDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CCTabControlDlg dialog CCTabControlDlg::CCTabControlDlg(CWnd* pParent /*=NULL*/) : CDialog(CCTabControlDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CCTabControlDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_TABCONTROL, m_tabcontrol1); } BEGIN_MESSAGE_MAP(CCTabControlDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_NOTIFY(TCN_SELCHANGE, IDC_TABCONTROL, &CCTabControlDlg::OnTcnSelchangeTabcontrol) END_MESSAGE_MAP() // CCTabControlDlg message handlers BOOL CCTabControlDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CTabCtrl* pTabCtrl = (CTabCtrl*)GetDlgItem(IDC_TABCONTROL); m_tab1.Create(IDD_TAB1, pTabCtrl); TCITEM item1; item1.mask = TCIF_TEXT | TCIF_PARAM; item1.lParam = (LPARAM)& m_tab1; item1.pszText = _T("Titlu Tab1"); pTabCtrl->InsertItem(0, &item1); //Pozitionarea dialogului CRect rcItem; pTabCtrl->GetItemRect(0, &rcItem); m_tab1.SetWindowPos(NULL, rcItem.left, rcItem.bottom + 1, 0, 0, SWP_NOSIZE | SWP_NOZORDER ); m_tab1.ShowWindow(SW_SHOW); // al doilea tab m_tab2.Create(IDD_TAB2, pTabCtrl); TCITEM item2; item2.mask = TCIF_TEXT | TCIF_PARAM; item2.lParam = (LPARAM)& m_tab1; item2.pszText = _T("Titlu Tab2"); pTabCtrl->InsertItem(0, &item2); //Pozitionarea dialogului //CRect rcItem; pTabCtrl->GetItemRect(0, &rcItem); m_tab2.SetWindowPos(NULL, rcItem.left, rcItem.bottom + 1, 0, 0, SWP_NOSIZE | SWP_NOZORDER ); m_tab2.ShowWindow(SW_SHOW); return TRUE; // return TRUE unless you set the focus to a control } void CCTabControlDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CCTabControlDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CCTabControlDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CCTabControlDlg::OnTcnSelchangeTabcontrol(NMHDR *pNMHDR, LRESULT *pResult) { // TODO: Add your control notification handler code here *pResult = 0; }

    Read the article

  • o display an image

    - by Vimal Basdeo
    I want to display an image from the web to a panel in another Jframe at the click of a button but whenever I click the button first the image loads and during this time the current form potentially freezes and once the image has loaded the form is displayed with the image.. How can I avoid the situation where my form freezes since it is very irritating My codes :: My current class private void btn_TrackbusActionPerformed(java.awt.event.ActionEvent evt) { try { sendMessage("Query,map,$,start,211,Arsenal,!"); System.out.println(receiveMessage()); } catch (UnknownHostException ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } client_trackedbus nextform=new client_trackedbus(planform,connection,packet_receive,packet_send); this.setVisible(false); this.dispose(); nextform.setVisible(true); // TODO add your handling code here: } My next class that displays the image public class client_trackedbus extends javax.swing.JFrame { client_planform planform=null; DatagramSocket connection=null; DatagramPacket packet_receive=null; DatagramPacket packet_send=null; JLabel label=null; /** Creates new form client_trackedbus */ public client_trackedbus(client_planform planform,DatagramSocket connection,DatagramPacket packet_receive,DatagramPacket packet_send) { initComponents(); this.planform=planform; this.connection=connection; this.packet_receive=packet_receive; this.packet_send=packet_send; try { displayMap("http://www.huddletogether.com/projects/lightbox2/images/image-2.jpg", jPanel1, new JLabel()); } catch (MalformedURLException ex) { Logger.getLogger(client_trackedbus.class.getName()).log(Level.SEVERE, null, ex); } } private void displayMap(String url,JPanel panel,JLabel label) throws MalformedURLException{ URL imageurl=new URL(url); Image image=(Toolkit.getDefaultToolkit().createImage(imageurl)); ImageIcon icon = new ImageIcon(image); label.setIcon(icon); panel.add(label); // System.out.println(panel.getSize().width); this.getContentPane().add(panel); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); btn_Exit = new javax.swing.JButton(); btn_Plan = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Public Transport Journey Planner"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 368, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 172, Short.MAX_VALUE) ); jLabel1.setFont(new java.awt.Font("Arial", 1, 18)); jLabel1.setText("Your tracked bus"); btn_Exit.setText("Exit"); btn_Exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_ExitActionPerformed(evt); } }); btn_Plan.setText("Plan journey"); btn_Plan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_PlanActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(104, 104, 104) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(65, 65, 65) .addComponent(btn_Plan) .addGap(65, 65, 65) .addComponent(btn_Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(20, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(35, 35, 35) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_Exit) .addComponent(btn_Plan)) .addContainerGap(12, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void btn_ExitActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: Exitform(); } private void btn_PlanActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: this.setVisible(false); this.dispose(); this.planform.setVisible(true); } private void Exitform(){ this.setVisible(false); this.dispose(); } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { // new client_trackedbus().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btn_Exit; private javax.swing.JButton btn_Plan; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; // End of variables declaration }

    Read the article

  • ActiveMQ AJax Client

    - by Lily
    I try to write a simple Ajax client to send and receive messages. It's successfully deployed but I have never received msg from the client. I am beating myself to think out what I am missing, but still can't make it work. Here is my code: I creat a dynamic web application named: ActiveMQAjaxService and put activemq-web.jar and all neccessary dependencies in the WEB-INF/lib folder. In this way, AjaxServlet and MessageServlet will be deployed I start activemq server in command line: ./activemq = activemq successfully created and display: Listening for connections at: tcp://lilyubuntu:61616 INFO | Connector openwire Started INFO | ActiveMQ JMS Message Broker (localhost, ID:lilyubuntu-56855-1272317001405-0:0) started INFO | Logging to org.slf4j.impl.JCLLoggerAdapter(org.mortbay.log) via org.mortbay.log.Slf4jLog INFO | jetty-6.1.9 INFO | ActiveMQ WebConsole initialized. INFO | Initializing Spring FrameworkServlet 'dispatcher' INFO | ActiveMQ Console at http://0.0.0.0:8161/admin INFO | Initializing Spring root WebApplicationContext INFO | Connector vm://localhost Started INFO | Camel Console at http://0.0.0.0:8161/camel INFO | ActiveMQ Web Demos at http://0.0.0.0:8161/demo INFO | RESTful file access application at http://0.0.0.0:8161/fileserver INFO | Started [email protected]:8161 3) index.xml, which is the html to test the client: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script type="text/javascript" src="amq/amq.js"></script> <script type="text/javascript">amq.uri='amq';</script> <title>Hello Ajax ActiveMQ</title> </head> <body> <p>Hello World!</p> <script type="text/javascript"> amq.sendMessage("topic://myDetector", "message"); var myHandler = { rcvMessage: function(message) { alert("received "+message); } }; function myPoll(first) { if (first) { amq.addListener('myDetector', 'topic://myDetector', myHandler.rcvMessage); } } amq.addPollHandler(myPoll); 4) Web.xml: ActiveMQ Web Demos Apache ActiveMQ Web Demos org.apache.activemq.brokerURL vm://localhost (I also tried tcp://localhost:61616) The URL of the Message Broker to connect to org.apache.activemq.embeddedBroker true Whether we should include an embedded broker or not <!-- the subscription REST servlet --> <servlet> <servlet-name>AjaxServlet</servlet-name> <servlet-class>org.apache.activemq.web.AjaxServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>MessageServlet</servlet-name> <servlet-class>org.apache.activemq.web.MessageServlet</servlet-class> <load-on-startup>1</load-on-startup> <!-- Uncomment this parameter if you plan to use multiple consumers over REST <init-param> <param-name>destinationOptions</param-name> <param-value>consumer.prefetchSize=1</param-value> </init-param> --> </servlet> <!-- the queue browse servlet --> <filter> <filter-name>session</filter-name> <filter-class>org.apache.activemq.web.SessionFilter</filter-class> </filter> <filter-mapping> <filter-name>session</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> After all of these, I deploy the web-app, and it's successfully deployed, but when I try it out in http://localhost:8080/ActiveMQAjaxService/index.html , nothing happens. I can run the demo portfolioPublisher demo successfully at http://localhost:8161/demo/portfolio/portfolio.html, and see the numbers updated all the time. But for my simple web-app, nothing really works. Any suggestion/hint is welcomed. Thanks so much Lily

    Read the article

  • How do I prevent my form from freezing when it is loading an image from the web at the click of a button?

    - by Vimal Basdeo
    I want to display an image from the web to a panel in another Jframe at the click of a button but whenever I click the button first the image loads and during this time the current form potentially freezes and once the image has loaded the form is displayed with the image.. How can I avoid the situation where my form freezes since it is very irritating My codes :: My current class private void btn_TrackbusActionPerformed(java.awt.event.ActionEvent evt) { try { sendMessage("Query,map,$,start,211,Arsenal,!"); System.out.println(receiveMessage()); } catch (UnknownHostException ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } client_trackedbus nextform=new client_trackedbus(planform,connection,packet_receive,packet_send); this.setVisible(false); this.dispose(); nextform.setVisible(true); // TODO add your handling code here: } My next class that displays the image public class client_trackedbus extends javax.swing.JFrame { client_planform planform=null; DatagramSocket connection=null; DatagramPacket packet_receive=null; DatagramPacket packet_send=null; JLabel label=null; /** Creates new form client_trackedbus */ public client_trackedbus(client_planform planform,DatagramSocket connection,DatagramPacket packet_receive,DatagramPacket packet_send) { initComponents(); this.planform=planform; this.connection=connection; this.packet_receive=packet_receive; this.packet_send=packet_send; try { displayMap("http://www.huddletogether.com/projects/lightbox2/images/image-2.jpg", jPanel1, new JLabel()); } catch (MalformedURLException ex) { Logger.getLogger(client_trackedbus.class.getName()).log(Level.SEVERE, null, ex); } } private void displayMap(String url,JPanel panel,JLabel label) throws MalformedURLException{ URL imageurl=new URL(url); Image image=(Toolkit.getDefaultToolkit().createImage(imageurl)); ImageIcon icon = new ImageIcon(image); label.setIcon(icon); panel.add(label); // System.out.println(panel.getSize().width); this.getContentPane().add(panel); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); btn_Exit = new javax.swing.JButton(); btn_Plan = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Public Transport Journey Planner"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 368, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 172, Short.MAX_VALUE) ); jLabel1.setFont(new java.awt.Font("Arial", 1, 18)); jLabel1.setText("Your tracked bus"); btn_Exit.setText("Exit"); btn_Exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_ExitActionPerformed(evt); } }); btn_Plan.setText("Plan journey"); btn_Plan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_PlanActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(104, 104, 104) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(65, 65, 65) .addComponent(btn_Plan) .addGap(65, 65, 65) .addComponent(btn_Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(20, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(35, 35, 35) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_Exit) .addComponent(btn_Plan)) .addContainerGap(12, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void btn_ExitActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: Exitform(); } private void btn_PlanActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: this.setVisible(false); this.dispose(); this.planform.setVisible(true); } private void Exitform(){ this.setVisible(false); this.dispose(); } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { // new client_trackedbus().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btn_Exit; private javax.swing.JButton btn_Plan; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; // End of variables declaration }

    Read the article

  • connecting clients to server with emulator on different computers

    - by prolink007
    I am writing an application that communicates using sockets. I have a server running on one android emulator on a computer, then i have 2 other clients running on android emulators on 2 other computers. I am trying to get the 2 clients to connect to the server. This works when i run the server and clients on the same computer, but when i attempt to do this on the same wifi network and on separate computers it gives me the following error. The client and server code is posted below. A lot is stripped out just to show the important stuff. Also, after the server starts i telnet into the server and run these commands redir add tcp:5000:6000 (i have also tried without doing the redir but it still says the same thing). Then i start the clients and get the error. Thanks for the help! Both the 5000 port and 6000 port are open on my router. And i have windows firewall disabled on the computer hosting the server. 11-27 18:54:02.274: W/ActivityManager(60): Activity idle timeout for HistoryRecord{44cf0a30 school.cpe434.ClassAidClient/school.cpe434.ClassAid.ClassAidClient4Activity} 11-27 18:57:02.424: W/System.err(205): java.net.SocketException: The operation timed out 11-27 18:57:02.454: W/System.err(205): at org.apache.harmony.luni.platform.OSNetworkSystem.connectSocketImpl(Native Method) 11-27 18:57:02.454: W/System.err(205): at org.apache.harmony.luni.platform.OSNetworkSystem.connect(OSNetworkSystem.java:114) 11-27 18:57:02.465: W/System.err(205): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:245) 11-27 18:57:02.465: W/System.err(205): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:220) 11-27 18:57:02.465: W/System.err(205): at java.net.Socket.startupSocket(Socket.java:780) 11-27 18:57:02.465: W/System.err(205): at java.net.Socket.<init>(Socket.java:314) 11-27 18:57:02.465: W/System.err(205): at school.cpe434.ClassAid.ClassAidClient4Activity.onCreate(ClassAidClient4Activity.java:102) 11-27 18:57:02.474: W/System.err(205): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 11-27 18:57:02.474: W/System.err(205): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459) 11-27 18:57:02.474: W/System.err(205): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512) 11-27 18:57:02.474: W/System.err(205): at android.app.ActivityThread.access$2200(ActivityThread.java:119) 11-27 18:57:02.474: W/System.err(205): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863) 11-27 18:57:02.474: W/System.err(205): at android.os.Handler.dispatchMessage(Handler.java:99) 11-27 18:57:02.474: W/System.err(205): at android.os.Looper.loop(Looper.java:123) 11-27 18:57:02.486: W/System.err(205): at android.app.ActivityThread.main(ActivityThread.java:4363) 11-27 18:57:02.486: W/System.err(205): at java.lang.reflect.Method.invokeNative(Native Method) 11-27 18:57:02.486: W/System.err(205): at java.lang.reflect.Method.invoke(Method.java:521) 11-27 18:57:02.486: W/System.err(205): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 11-27 18:57:02.486: W/System.err(205): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 11-27 18:57:02.486: W/System.err(205): at dalvik.system.NativeStart.main(Native Method) The server code public class ClassAidServer4Activity extends Activity { ServerSocket ss = null; String mClientMsg = ""; String mClientExtraMsg = ""; Thread myCommsThread = null; public static final int SERVERPORT = 6000; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv = (TextView) findViewById(R.id.textView1); tv.setText("Nothing from client yet"); this.myCommsThread = new Thread(new CommsThread()); this.myCommsThread.start(); } class CommsThread implements Runnable { public void run() { // Socket s = null; try { ss = new ServerSocket(SERVERPORT ); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } while(true) { try { Socket socket = ss.accept(); connectedDeviceCount++; Thread lThread = new Thread(new ListeningThread(socket)); lThread.start(); } catch (IOException e) { e.printStackTrace(); } } } } class ListeningThread implements Runnable { private Socket s = null; public ListeningThread(Socket socket) { // TODO Auto-generated constructor stub this.s = socket; } @Override public void run() { // TODO Auto-generated method stub while (!Thread.currentThread().isInterrupted()) { Message m = new Message(); // m.what = QUESTION_ID; try { if (s == null) s = ss.accept(); BufferedReader input = new BufferedReader( new InputStreamReader(s.getInputStream())); String st = null; st = input.readLine(); String[] temp = parseReadMessage(st); mClientMsg = temp[1]; if(temp.length > 2) { mClientExtraMsg = temp[2]; } m.what = Integer.parseInt(temp[0]); myUpdateHandler.sendMessage(m); } catch (IOException e) { e.printStackTrace(); } } } } } The client code public class ClassAidClient4Activity extends Activity { //telnet localhost 5554 //redir add tcp:5000:6000 private Socket socket; private String serverIpAddress = "192.168.1.102"; private static final int REDIRECTED_SERVERPORT = 5000; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { InetAddress serverAddr = InetAddress.getByName(serverIpAddress); socket = new Socket(serverAddr, REDIRECTED_SERVERPORT); } catch (UnknownHostException e1) { mQuestionAdapter.add("UnknownHostException"); e1.printStackTrace(); } catch (IOException e1) { mQuestionAdapter.add("IOException"); e1.printStackTrace(); } } }

    Read the article

  • JavaMail not sending Subject or From under jetty:run-war

    - by Jason Thrasher
    Has anyone seen JavaMail not sending proper MimeMessages to an SMTP server, depending on how the JVM in started? At the end of the day, I can't send JavaMail SMTP messages with Subject: or From: fields, and it appears other headers are missing, only when running the app as a war. The web project is built with Maven and I'm testing sending JavaMail using a browser and a simple mail.jsp to debug and see different behavior when launching the app with: 1) mvn jetty:run (mail sends fine, with proper Subject and From fields) 2) mvn jetty:run-war (mail sends fine, but missing Subject, From, and other fields) I've meticulously run diff on the (verbose) Maven debug output (-X), and there are zero differences in the runtime dependencies between the two. I've also compared System properties, and they are identical. Something else is happening the jetty:run-war case that changes the way JavaMail behaves. What other stones need turning? Curiously, I've tried a debugger in both situations and found that the javax.mail.internet.MimeMessage instance is getting created differently. The webapp is using Spring to send email picked off of an Apache ActiveMQ queue. When running the app as mvn jetty:run the MimeMessage.contentStream variable is used for message content. When running as mvn jetty:run-war, the MimeMessage.content variable is used for the message contents, and the content = ASCIIUtility.getBytes(is); call removes all of the header data from the parsed content. Since this seemed very odd, and debugging Spring/ActiveMQ is a deep dive, I created a simplified test without any of that infrastructure: just a JSP using mail-1.4.2.jar, yet the same headers are missing. Also of note, these headers are missing when running the WAR file under Tomcat 5.5.27. Tomcat behaves just like Jetty when running the WAR, with the same missing headers. With JavaMail debugging turned on, I clearly see different output. GOOD CASE: In the jetty:run (non-WAR) the log output is: DEBUG: JavaMail version 1.4.2 DEBUG: successfully loaded resource: /META-INF/javamail.default.providers DEBUG: Tables of loaded providers DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]} DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]} DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc] DEBUG SMTP: useEhlo true, useAuth true DEBUG SMTP: trying to connect to host "mail.authsmtp.com", port 465, isSSL false 220 mail.authsmtp.com ESMTP Sendmail 8.14.2/8.14.2/Kp; Thu, 18 Jun 2009 01:35:24 +0100 (BST) DEBUG SMTP: connected to host "mail.authsmtp.com", port: 465 EHLO jmac.local 250-mail.authsmtp.com Hello sul-pubs-3a.Stanford.EDU [171.66.201.2], pleased to meet you 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-8BITMIME 250-SIZE 52428800 250-AUTH CRAM-MD5 DIGEST-MD5 LOGIN PLAIN 250-DELIVERBY 250 HELP DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg "" DEBUG SMTP: Found extension "PIPELINING", arg "" DEBUG SMTP: Found extension "8BITMIME", arg "" DEBUG SMTP: Found extension "SIZE", arg "52428800" DEBUG SMTP: Found extension "AUTH", arg "CRAM-MD5 DIGEST-MD5 LOGIN PLAIN" DEBUG SMTP: Found extension "DELIVERBY", arg "" DEBUG SMTP: Found extension "HELP", arg "" DEBUG SMTP: Attempt to authenticate DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 AUTH LOGIN 334 VXNlcm5hjbt7 YWM0MDkwhi== 334 UGFzc3dvjbt7 YXV0aHNtdHAydog3 235 2.0.0 OK Authenticated DEBUG SMTP: use8bit false MAIL FROM:<[email protected]> 250 2.1.0 <[email protected]>... Sender ok RCPT TO:<[email protected]> 250 2.1.5 <[email protected]>... Recipient ok DEBUG SMTP: Verified Addresses DEBUG SMTP: Jason Thrasher <[email protected]> DATA 354 Enter mail, end with "." on a line by itself From: Webmaster <[email protected]> To: Jason Thrasher <[email protected]> Message-ID: <[email protected]> Subject: non-Spring: Hello World MIME-Version: 1.0 Content-Type: text/plain;charset=UTF-8 Content-Transfer-Encoding: 7bit Hello World: message body here . 250 2.0.0 n5I0ZOkD085654 Message accepted for delivery QUIT 221 2.0.0 mail.authsmtp.com closing connection BAD CASE: The log output when running as a WAR, with missing headers, is quite different: Loading javamail.default.providers from jar:file:/Users/jason/.m2/repository/javax/mail/mail/1.4.2/mail-1.4.2.jar!/META-INF/javamail.default.providers DEBUG: loading new provider protocol=imap, className=com.sun.mail.imap.IMAPStore, vendor=Sun Microsystems, Inc, version=null DEBUG: loading new provider protocol=imaps, className=com.sun.mail.imap.IMAPSSLStore, vendor=Sun Microsystems, Inc, version=null DEBUG: loading new provider protocol=smtp, className=com.sun.mail.smtp.SMTPTransport, vendor=Sun Microsystems, Inc, version=null DEBUG: loading new provider protocol=smtps, className=com.sun.mail.smtp.SMTPSSLTransport, vendor=Sun Microsystems, Inc, version=null DEBUG: loading new provider protocol=pop3, className=com.sun.mail.pop3.POP3Store, vendor=Sun Microsystems, Inc, version=null DEBUG: loading new provider protocol=pop3s, className=com.sun.mail.pop3.POP3SSLStore, vendor=Sun Microsystems, Inc, version=null Loading javamail.default.providers from jar:file:/Users/jason/Documents/dev/subscribeatron/software/trunk/web/struts/target/work/webapp/WEB-INF/lib/mail-1.4.2.jar!/META-INF/javamail.default.providers DEBUG: loading new provider protocol=imap, className=com.sun.mail.imap.IMAPStore, vendor=Sun Microsystems, Inc, version=null DEBUG: loading new provider protocol=imaps, className=com.sun.mail.imap.IMAPSSLStore, vendor=Sun Microsystems, Inc, version=null DEBUG: loading new provider protocol=smtp, className=com.sun.mail.smtp.SMTPTransport, vendor=Sun Microsystems, Inc, version=null DEBUG: loading new provider protocol=smtps, className=com.sun.mail.smtp.SMTPSSLTransport, vendor=Sun Microsystems, Inc, version=null DEBUG: loading new provider protocol=pop3, className=com.sun.mail.pop3.POP3Store, vendor=Sun Microsystems, Inc, version=null DEBUG: loading new provider protocol=pop3s, className=com.sun.mail.pop3.POP3SSLStore, vendor=Sun Microsystems, Inc, version=null DEBUG: getProvider() returning provider protocol=smtp; type=javax.mail.Provider$Type@98203f; class=com.sun.mail.smtp.SMTPTransport; vendor=Sun Microsystems, Inc DEBUG SMTP: useEhlo true, useAuth false DEBUG SMTP: trying to connect to host "mail.authsmtp.com", port 465, isSSL false 220 mail.authsmtp.com ESMTP Sendmail 8.14.2/8.14.2/Kp; Thu, 18 Jun 2009 01:51:46 +0100 (BST) DEBUG SMTP: connected to host "mail.authsmtp.com", port: 465 EHLO jmac.local 250-mail.authsmtp.com Hello sul-pubs-3a.Stanford.EDU [171.66.201.2], pleased to meet you 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-8BITMIME 250-SIZE 52428800 250-AUTH CRAM-MD5 DIGEST-MD5 LOGIN PLAIN 250-DELIVERBY 250 HELP DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg "" DEBUG SMTP: Found extension "PIPELINING", arg "" DEBUG SMTP: Found extension "8BITMIME", arg "" DEBUG SMTP: Found extension "SIZE", arg "52428800" DEBUG SMTP: Found extension "AUTH", arg "CRAM-MD5 DIGEST-MD5 LOGIN PLAIN" DEBUG SMTP: Found extension "DELIVERBY", arg "" DEBUG SMTP: Found extension "HELP", arg "" DEBUG SMTP: Attempt to authenticate DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 AUTH LOGIN 334 VXNlcm5hjbt7 YWM0MDkwhi== 334 UGFzc3dvjbt7 YXV0aHNtdHAydog3 235 2.0.0 OK Authenticated DEBUG SMTP: use8bit false MAIL FROM:<[email protected]> 250 2.1.0 <[email protected]>... Sender ok RCPT TO:<[email protected]> 250 2.1.5 <[email protected]>... Recipient ok DEBUG SMTP: Verified Addresses DEBUG SMTP: Jason Thrasher <[email protected]> DATA 354 Enter mail, end with "." on a line by itself Hello World: message body here . 250 2.0.0 n5I0pkSc090137 Message accepted for delivery QUIT 221 2.0.0 mail.authsmtp.com closing connection Here's the actual mail.jsp that I'm testing war/non-war with. <%@page import="java.util.*"%> <%@page import="javax.mail.internet.*"%> <%@page import="javax.mail.*"%> <% InternetAddress from = new InternetAddress("[email protected]", "Webmaster"); InternetAddress to = new InternetAddress("[email protected]", "Jason Thrasher"); String subject = "non-Spring: Hello World"; String content = "Hello World: message body here"; final Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", "mail.authsmtp.com"); props.setProperty("mail.port", "465"); props.setProperty("mail.username", "myusername"); props.setProperty("mail.password", "secret"); props.setProperty("mail.debug", "true"); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); Session mailSession = Session.getDefaultInstance(props); Message message = new MimeMessage(mailSession); message.setFrom(from); message.setRecipient(Message.RecipientType.TO, to); message.setSubject(subject); message.setContent(content, "text/plain;charset=UTF-8"); Transport trans = mailSession.getTransport(); trans.connect(props.getProperty("mail.host"), Integer .parseInt(props.getProperty("mail.port")), props .getProperty("mail.username"), props .getProperty("mail.password")); trans.sendMessage(message, message .getRecipients(Message.RecipientType.TO)); trans.close(); %> email was sent SOLUTION: Yes, the problem was transitive dependencies of Apache CXF 2. I had to exclude geronimo-javamail_1.4_spec from the build, and just rely on javax's mail-1.4.jar. <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>2.2.6</version> <exclusions> <exclusion> <groupId>org.apache.geronimo.specs</groupId> <artifactId>geronimo-javamail_1.4_spec</artifactId> </exclusion> </exclusions> </dependency> Thanks for all of the answers.

    Read the article

  • Web Sockets: Browser won't receive the message, complains about it not starting with 0x00 (byte)

    - by giggsey
    Here is my code: import java.net.*; import java.io.*; import java.util.*; import org.jibble.pircbot.*; public class WebSocket { public static int port = 12345; public static ArrayList<WebSocketClient> clients = new ArrayList<WebSocketClient>(); public static ArrayList<Boolean> handshakes = new ArrayList<Boolean>(); public static ArrayList<String> nicknames = new ArrayList<String>(); public static ArrayList<String> channels = new ArrayList<String>(); public static int indexNum; public static void main(String args[]) { try { ServerSocket ss = new ServerSocket(WebSocket.port); WebSocket.console("Created socket on port " + WebSocket.port); while (true) { Socket s = ss.accept(); WebSocket.console("New Client connecting..."); WebSocket.handshakes.add(WebSocket.indexNum,false); WebSocket.nicknames.add(WebSocket.indexNum,""); WebSocket.channels.add(WebSocket.indexNum,""); WebSocketClient p = new WebSocketClient(s,WebSocket.indexNum); Thread t = new Thread( p); WebSocket.clients.add(WebSocket.indexNum,p); indexNum++; t.start(); } } catch (Exception e) { WebSocket.console("ERROR - " + e.toString()); } } public static void console(String msg) { Date date = new Date(); System.out.println("[" + date.toString() + "] " + msg); } } class WebSocketClient implements Runnable { private Socket s; private int iAm; private String socket_res = ""; private String socket_host = ""; private String socket_origin = ""; protected String nick = ""; protected String ircChan = ""; WebSocketClient(Socket socket, int mynum) { s = socket; iAm = mynum; } public void run() { String client = s.getInetAddress().toString(); WebSocket.console("Connection from " + client); IRCclient irc = new IRCclient(iAm); Thread t = new Thread( irc ); try { Scanner in = new Scanner(s.getInputStream()); PrintWriter out = new PrintWriter(s.getOutputStream(),true); while (true) { if (! in.hasNextLine()) continue; String input = in.nextLine().trim(); if (input.isEmpty()) continue; // Lets work out what's wrong with our input if (input.length() > 3 && input.charAt(0) == 65533) { input = input.substring(2); } WebSocket.console("< " + input); // Lets work out if they authenticate... if (WebSocket.handshakes.get(iAm) == false) { checkForHandShake(input); continue; } // Lets check for NICK: if (input.length() > 6 && input.substring(0,6).equals("NICK: ")) { nick = input.substring(6); Random generator = new Random(); int rand = generator.nextInt(); WebSocket.console("I am known as " + nick); WebSocket.nicknames.set(iAm, "bo-" + nick + rand); } if (input.length() > 9 && input.substring(0,9).equals("CHANNEL: ")) { ircChan = "bo-" + input.substring(9); WebSocket.console("We will be joining " + ircChan); WebSocket.channels.set(iAm, ircChan); } if (! ircChan.isEmpty() && ! nick.isEmpty() && irc.started == false) { irc.chan = ircChan; irc.nick = WebSocket.nicknames.get(iAm); t.start(); continue; } else { irc.msg(input); } } } catch (Exception e) { WebSocket.console(e.toString()); e.printStackTrace(); } t.stop(); WebSocket.channels.remove(iAm); WebSocket.clients.remove(iAm); WebSocket.handshakes.remove(iAm); WebSocket.nicknames.remove(iAm); WebSocket.console("Closing connection from " + client); } private void checkForHandShake(String input) { // Check for HTML5 Socket getHeaders(input); if (! socket_res.isEmpty() && ! socket_host.isEmpty() && ! socket_origin.isEmpty()) { send("HTTP/1.1 101 Web Socket Protocol Handshake\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "WebSocket-Origin: " + socket_origin + "\r\n" + "WebSocket-Location: ws://" + socket_host + "/\r\n\r\n",false); WebSocket.handshakes.set(iAm,true); } return; } private void getHeaders(String input) { if (input.length() >= 8 && input.substring(0,8).equals("Origin: ")) { socket_origin = input.substring(8); return; } if (input.length() >= 6 && input.substring(0,6).equals("Host: ")) { socket_host = input.substring(6); return; } if (input.length() >= 7 && input.substring(0,7).equals("Cookie:")) { socket_res = "."; } /*input = input.substring(4); socket_res = input.substring(0,input.indexOf(" HTTP")); input = input.substring(input.indexOf("Host:") + 6); socket_host = input.substring(0,input.indexOf("\r\n")); input = input.substring(input.indexOf("Origin:") + 8); socket_origin = input.substring(0,input.indexOf("\r\n"));*/ return; } protected void send(String msg, boolean newline) { byte c0 = 0x00; byte c255 = (byte) 0xff; try { PrintWriter out = new PrintWriter(s.getOutputStream(),true); WebSocket.console("> " + msg); if (newline == true) msg = msg + "\n"; out.print(msg + c255); out.flush(); } catch (Exception e) { WebSocket.console(e.toString()); } } protected void send(String msg) { try { WebSocket.console(">> " + msg); byte[] message = msg.getBytes(); byte[] newmsg = new byte[message.length + 2]; newmsg[0] = (byte)0x00; for (int i = 1; i <= message.length; i++) { newmsg[i] = message[i - 1]; } newmsg[message.length + 1] = (byte)0xff; // This prints correctly..., apparently... System.out.println(Arrays.toString(newmsg)); OutputStream socketOutputStream = s.getOutputStream(); socketOutputStream.write(newmsg); } catch (Exception e) { WebSocket.console(e.toString()); } } protected void send(String msg, boolean one, boolean two) { try { WebSocket.console(">> " + msg); byte[] message = msg.getBytes(); byte[] newmsg = new byte[message.length+1]; for (int i = 0; i < message.length; i++) { newmsg[i] = message[i]; } newmsg[message.length] = (byte)0xff; // This prints correctly..., apparently... System.out.println(Arrays.toString(newmsg)); OutputStream socketOutputStream = s.getOutputStream(); socketOutputStream.write(newmsg); } catch (Exception e) { e.printStackTrace(); } } } class IRCclient implements Runnable { protected String nick; protected String chan; protected int iAm; boolean started = false; IRCUser irc; IRCclient(int me) { iAm = me; irc = new IRCUser(iAm); } public void run() { WebSocket.console("Connecting to IRC..."); started = true; irc.setNick(nick); irc.setVerbose(false); irc.connectToIRC(chan); } void msg(String input) { irc.sendMessage("#" + chan, input); } } class IRCUser extends PircBot { int iAm; IRCUser(int me) { iAm = me; } public void setNick(String nick) { this.setName(nick); } public void connectToIRC(String chan) { try { this.connect("irc.appliedirc.com"); this.joinChannel("#" + chan); } catch (Exception e) { WebSocket.console(e.toString()); } } public void onMessage(String channel, String sender,String login, String hostname, String message) { // Lets send this message to me WebSocket.clients.get(iAm).send(message); } } Whenever I try to send the message to the browser (via Web Sockets), it complains that it doesn't start with 0x00 (which is a byte). Any ideas? Edit 19/02 - Added the entire code. I know it's real messy and not neat, but I want to get it functioning first. Spend last two days trying to fix.

    Read the article

< Previous Page | 5 6 7 8 9