Close Button in the caption bar of a GWT DialogBox

3

The following code demonstrates how a 'close button' can be placed in the caption bar of a DialogBox . Note that the example uses a HTML object as the close button , it can be replaced by an Image to make it more eye-candy.

/** *PUBLIC SOFTWARE * *This source code has been placed in the public domain. You can use, modify, and distribute *the source code and executable programs based on the source code. * *However, note the following: * *DISCLAIMER OF WARRANTY * * This source code is provided "as is" and without warranties as to performance * or merchantability. The author and/or distributors of this source code may * have made statements about this source code. Any such statements do not constitute * warranties and shall not be relied on by the user in deciding whether to use * this source code.This source code is provided without any express or implied * warranties whatsoever. Because of the diversity of conditions and hardware * under which this source code may be used, no warranty of fitness for a * particular purpose is offered. The user is advised to test the source code * thoroughly before relying on it. The user must assume the entire risk of * using the source code. * */ import com.google.gwt.user.client.Element; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Event.NativePreviewEvent; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; /** * @author amal * @version 1.0 */ public class MyDialog extends DialogBox { HTML close = new HTML("[X]"); HTML title =new HTML(""); HorizontalPanel captionPanel = new HorizontalPanel(); public MyDialog(boolean autoHide, boolean modal) { super(autoHide, modal); Element td = getCellElement(0, 1); DOM.removeChild(td, (Element) td.getFirstChildElement()); DOM.appendChild(td, captionPanel.getElement()); captionPanel.setStyleName("Caption");//width-100% captionPanel.add(title); close.addStyleName("CloseButton");//float:right captionPanel.add(close); super.setGlassEnabled(true); super.setAnimationEnabled(true); } public MyDialog(boolean autoHide) { this(autoHide, true); } public MyDialog() { this(false); } @Override public String getHTML() { return this.title.getHTML(); } @Override public String getText() { return this.title.getText(); } @Override public void setHTML(String html) { this.title.setHTML(html); } @Override public void setText(String text) { this.title.setText(text); } @Override protected void onPreviewNativeEvent(NativePreviewEvent event) { NativeEvent nativeEvent = event.getNativeEvent(); if (!event.isCanceled() && (event.getTypeInt() == Event.ONCLICK) && isCloseEvent(nativeEvent)) { this.hide(); } super.onPreviewNativeEvent(event); } private boolean isCloseEvent(NativeEvent event) { return event.getEventTarget().equals(close.getElement());//compares equality of the underlying DOM elements } }

Read more »
Labels:

Closing a GWT DialogBox on 'Esc' keypress

0

To have a DialogBox do something on a keyboard event , its onPreviewNativeEvent should be overridden . A DialogBox can be made to hide itself on the 'Esc' key event by overriding it's OnPreviewNativeEvent method as follows

@Override protected void onPreviewNativeEvent(NativePreviewEvent event) { if (!event.isCanceled() && event.getTypeInt() == Event.ONKEYDOWN && event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ESCAPE) { this.hide(); } super.onPreviewNativeEvent(event); }

Read more »
Labels:

Serializing and De-serializing a Java object to XML

0

A Java object can be serialized as XML using the XMLEncoder

try { XMLEncoder enc= new XMLEncoder(new BufferedOutputStream( new FileOutputStream("<output xml file>"))); enc.writeObject(instance);//instance is the bean object to be serialized enc.close(); } catch (FileNotFoundException e) { }


De-serializing the XML file can be done as follows using the XMLDecoder


try { XMLDecoder dec= new XMLDecoder(new BufferedInputStream( new FileInputStream("<input xml file>"))); MyClass o = (MyClass)dec.readObject(); dec.close(); } catch (FileNotFoundException e) { }

Read more »
Labels: ,

Loading a class using the URLClassLoader

0

The URLClassLoader can be used dynamically load classes from a directory , not necessarily on the classpath. The following code demonstrates how 


File file = new File("<directory path>"); try { URL url = file.toURL(); ClassLoader loader= new URLClassLoader(new URL[]{url}); Class class= loader.loadClass("<class name>"); } catch (MalformedURLException e) { } catch (ClassNotFoundException e) { }

Read more »
Labels: ,

Javascript equality(==) and identity(===) operators

0

The identity operator(===) compares the type and value of the operands , while the equality operator(==) compares just the values .

So , given var i=1

i=='1' will return true , while i==='1' will return false .

Quote from  Javascript : The good parts


JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. 
My advice is to never use the evil twins. Instead, always use === and !==.

Read more »
Labels: ,

Using readResolve method to create a Serializable Singleton

0

The readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller. The following code demonstrates how to create a serializable singleton , using the method.



public class Singleton implements Serializable {  static Singleton instance= new Singleton (); private Singleton ()  {  } protected Object readResolve()   {   return instance;  } }

Read more »
Labels: ,

Integer constant pool

0

Java uses a caching mechanism for Integer , similar to the String Pool . It caches the Integer values from -128 to 127 , meaning '==' comparisons for values in this range returns true .

Integer a=127; Integer b=127; System.out.println(a==b);//prints true a=128; b=128; System.out.println(a==b);//prints false

Read more »
Labels: ,

Creating and Firing events with GWT

0

The following code demonstrates how to programmatically create an event using GWT.

Document doc=Document.get(); NativeEvent clickEvent=doc.createClickEvent(0, 0,0, 0,0, false, false, false,false); NativeEvent changeEvent=doc.createChangeEvent(); NativeEvent keyDownEvent=doc.createKeyDownEvent(false, false, false,false,KeyCodes.KEY_ENTER); .........

The events created can be programmatically fired using the DomEvent.fireNativeEvent method .

Read more »
Labels: ,

Invoking a method by name using Reflection

1

It is possible to use reflection to invoke a method using its name , which is known only at runtime . The following code demonstrates the usage of the invoke method . Note that reflection may be used to override the java access checks , allowing the caller to invoke methods that are declared private .


/** *PUBLIC SOFTWARE * *This source code has been placed in the public domain. You can use, modify, and distribute *the source code and executable programs based on the source code. * *However, note the following: * *DISCLAIMER OF WARRANTY * * This source code is provided "as is" and without warranties as to performance * or merchantability. The author and/or distributors of this source code may * have made statements about this source code. Any such statements do not constitute * warranties and shall not be relied on by the user in deciding whether to use * this source code.This source code is provided without any express or implied * warranties whatsoever. Because of the diversity of conditions and hardware * under which this source code may be used, no warranty of fitness for a * particular purpose is offered. The user is advised to test the source code * thoroughly before relying on it. The user must assume the entire risk of * using the source code. * */ import java.lang.reflect.*; /** * * @author amal * version 1.0 */ public class InvokeTest { public static void main(String[] args) throws Exception { Class c = Class.forName("X"); Object instance = c.newInstance(); Method m = c.getDeclaredMethod("A",new Class[]{}); m.invoke(instance, new Object[]{}); m = c.getDeclaredMethod("A",new Class[]{int.class});//or INTEGER.TYPE m.invoke(instance, new Object[]{1}); m = c.getDeclaredMethod("A",new Class[]{String.class}); m.invoke(instance, new Object[]{"arg"}); m = c.getDeclaredMethod("A",new Class[]{String.class,String.class}); m.setAccessible(true);//supress the java access check m.invoke(instance, new Object[]{"arg1","arg2"}); } } class X { void A() { System.out.println("In method A , with no arguments"); } void A(int i) { System.out.println("In method A , with an integer argument "+i); } void A(String s) { System.out.println("In method A , with a string argument "+s); } private void A(String s,String t) { System.out.println("In the private method A , with two string arguments "+s+" , "+t); } }

Read more »
Labels: ,

Simple Profanity Filter

0

A simple Java program demonstrating the use of CDYNE's FREE Profanity Filter API . Note that the code just demonstrates the setting up of a simple profanity filter , the API includes much more functionalities . Check out the CDYNE Wiki for how to implement a profanity filter suited to your needs .



/** *PUBLIC SOFTWARE * *This source code has been placed in the public domain. You can use, modify, and distribute *the source code and executable programs based on the source code. * *However, note the following: * *DISCLAIMER OF WARRANTY * * This source code is provided "as is" and without warranties as to performance * or merchantability. The author and/or distributors of this source code may * have made statements about this source code. Any such statements do not constitute * warranties and shall not be relied on by the user in deciding whether to use * this source code.This source code is provided without any express or implied * warranties whatsoever. Because of the diversity of conditions and hardware * under which this source code may be used, no warranty of fitness for a * particular purpose is offered. The user is advised to test the source code * thoroughly before relying on it. The user must assume the entire risk of * using the source code. * */ import java.io.*; import java.net.*; /** * * @author amal * version 1.0 */ public class CDYNEFilterDemo { public static void main(String[] args) { BufferedReader in = null; try { String text = "test profanity bullshit"; URL url = new URL("http://ws.cdyne.com/ProfanityWS/Profanity.asmx/SimpleProfanityFilter?Text="+URLEncoder.encode(text,"UTF-8")); in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != in) { in.close(); } } catch (IOException e) { // ignore } } } }

Read more »
Labels: ,

Strings in Java - Immutablility , Interning and the String pool

0


Immutability

Strings in Java are immutable .An immutable object is one whose state cannot be modified once it is created . In Java , Strings are immutable . An interesting side-effect of the immutability of Strings is that methods like toLowerCase() in the String class doesn't affect the state of the original String , rather returns a new String.

Interning & The String pool

String interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. In Java , strings are interned using a String literal pool .

Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object is created and placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption.

A side-effect of String interning in Java can be demonstrated by this code snippet.

String s1="aaaaa"; String s2="aaaaa"; System.out.println(s1==s2);

The above code snippet prints true because the two Strings are interned , and refers to the same pool instance.

Literal Strings , including those that can be computed by constant expressions at compile time are interned .
Strings explicitly created by the constructor or by concatenation at runtime are not interned.

The intern() method

The docs state When the intern method is invoked, if the pool already contains a
string equal to the String\ object as determined by
the method, then the string from the pool is
returned. Otherwise, the String object is added to the
pool and a reference to the String object is returned.
The below code snippet demonstrates the behaviour of the intern() method.


String s1 = "Zone817"; String s2 = new StringBuffer("Zone").append("817").toString(); String s3 = s2.intern(); System.out.println(s1 == s2);//prints false System.out.println(s1 == s3);//prints true

Read more »
Labels: ,

Mimicking a browser user-agent in a request

0

The following code demonstrates how to 'forge' the user-agent string in a request , making the request seem like it originated from a browser.


/** *PUBLIC SOFTWARE * *This source code has been placed in the public domain. You can use, modify, and distribute *the source code and executable programs based on the source code. * *However, note the following: * *DISCLAIMER OF WARRANTY * * This source code is provided "as is" and without warranties as to performance * or merchantability. The author and/or distributors of this source code may * have made statements about this source code. Any such statements do not constitute * warranties and shall not be relied on by the user in deciding whether to use * this source code.This source code is provided without any express or implied * warranties whatsoever. Because of the diversity of conditions and hardware * under which this source code may be used, no warranty of fitness for a * particular purpose is offered. The user is advised to test the source code * thoroughly before relying on it. The user must assume the entire risk of * using the source code. * */ import java.io.*; import java.net.*; /** * * @author amal * version 1.0 */ public class UrlConB { public static void main(String[] args) { InputStreamReader in = null; try { String query = "web"; Socket s = new Socket("bing.com", 80); PrintStream p = new PrintStream(s.getOutputStream()); p.print("GET /search?q=" + query + " HTTP/1.0\r\n"); p.print("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/6.0\r\n"); p.print("Connection: close\r\n\r\n"); in = new InputStreamReader(s.getInputStream()); BufferedReader buffer = new BufferedReader(in); String line; while ((line = buffer.readLine()) != null) { System.out.println(line); } in.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != in) in.close(); } catch (IOException e) { // ignore } } } }

Read more »
Labels: , ,

Connecting to an Url using a Java program - Connecting through a proxy

0

The following code demonstartes how to connect to an url through a proxy . The code uses the default system proxy.


In case you want to use a different proxy than the default system proxy , you need to set the http.proxyHost and http.proxyPort
properties from your code using setProperty method of the System class ,
or you can provide the values as command line arguments when starting your java program , like
java -Dhttp.proxyHost=hostname -Dhttp.proxyPort=portNumber foo
, where foo is the name of the class . You may also create an instance of the Proxy class ,
and pass it to the openConnection() method of the URL class.



/** *PUBLIC SOFTWARE * *This source code has been placed in the public domain. You can use, modify, and distribute *the source code and executable programs based on the source code. * *However, note the following: * *DISCLAIMER OF WARRANTY * * This source code is provided "as is" and without warranties as to performance * or merchantability. The author and/or distributors of this source code may * have made statements about this source code. Any such statements do not constitute * warranties and shall not be relied on by the user in deciding whether to use * this source code.This source code is provided without any express or implied * warranties whatsoever. Because of the diversity of conditions and hardware * under which this source code may be used, no warranty of fitness for a * particular purpose is offered. The user is advised to test the source code * thoroughly before relying on it. The user must assume the entire risk of * using the source code. * */ import java.io.*; import java.net.*; import com.sun.org.apache.xml.internal.security.utils.Base64; /** * * @author amal * version 1.0 */ public class UrlConA { public static void main(String[] args) { System.setProperty("java.net.useSystemProxies", "true"); BufferedReader in = null; try { URL url = new URL("http://www.w3schools.com"); URLConnection uc = url.openConnection(); String encoded = new String(Base64.encode(new String( "username:password").getBytes())); uc.setRequestProperty("Proxy-Authorization", "Basic " + encoded); uc.connect(); in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != in) { in.close(); } } catch (IOException e) { // ignore } } } }

Read more »
Labels: , ,

Connecting to an Url using a Java program

0

The following code demonstrates how to read from a url using java.





/** *PUBLIC SOFTWARE * *This source code has been placed in the public domain. You can use, modify, and distribute *the source code and executable programs based on the source code. * *However, note the following: * *DISCLAIMER OF WARRANTY * * This source code is provided "as is" and without warranties as to performance * or merchantability. The author and/or distributors of this source code may * have made statements about this source code. Any such statements do not constitute * warranties and shall not be relied on by the user in deciding whether to use * this source code.This source code is provided without any express or implied * warranties whatsoever. Because of the diversity of conditions and hardware * under which this source code may be used, no warranty of fitness for a * particular purpose is offered. The user is advised to test the source code * thoroughly before relying on it. The user must assume the entire risk of * using the source code. * */ import java.io.*; import java.net.*; /** * * @author amal * version 1.0 */ public class UrlCon { public static void main(String[] args) { BufferedReader in = null; try { URL url = new URL("http://www.bing.com/"); in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != in) { in.close(); } } catch (IOException e) { // ignore } } } }

Read more »
Labels: ,

Example code for sending mail with attachments using Java

0

The following code demonstrates how to send a mail with JavaMail . The example code uses the mail.jar file , which is included in the JavaMail download .

/** *PUBLIC SOFTWARE * *This source code has been placed in the public domain. You can use, modify, and distribute *the source code and executable programs based on the source code. * *However, note the following: * *DISCLAIMER OF WARRANTY * * This source code is provided "as is" and without warranties as to performance * or merchantability. The author and/or distributors of this source code may * have made statements about this source code. Any such statements do not constitute * warranties and shall not be relied on by the user in deciding whether to use * this source code.This source code is provided without any express or implied * warranties whatsoever. Because of the diversity of conditions and hardware * under which this source code may be used, no warranty of fitness for a * particular purpose is offered. The user is advised to test the source code * thoroughly before relying on it. The user must assume the entire risk of * using the source code. * */ import java.util.*; import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; /** * * @author amal * version 1.0 */ public class Mailer { public static void main(String[] args) throws Exception{ Properties properties = new Properties(); properties.setProperty("mail.transport.protocol", "smtp"); properties.setProperty("mail.host", "mailServer"); properties.setProperty("mail.user", "emailUser"); properties.setProperty("mail.password", "emailPassword"); Session sess = Session.getDefaultInstance(properties, null); Transport transport = sess.getTransport(); MimeMessage message = new MimeMessage(sess); message.setSubject("Mail Subject"); MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent("Mail Content", "text/html"); MimeBodyPart attachmentPart = new MimeBodyPart(); FileDataSource fileDS =new FileDataSource("FileToBeAttached"); attachmentPart.setDataHandler(new DataHandler(fileDS)); attachmentPart.setFileName(fileDS.getName()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(textPart); multipart.addBodyPart(attachmentPart); message.setContent(multipart); message.addRecipient(Message.RecipientType.TO, new InternetAddress("recepient@domain.com")); transport.connect(); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); } }

Read more »
Labels: ,
© Zone817. Powered by Blogger.