Java

Java related posts

Rest vs SOAP

0

Are there any analogy between SOAP vs Rest based web services and Entity Beans vs hibernate? I big telecom company is investing heavily on SOAP based web services as they guided by Oracle. I still could not identify any case  where they are using WS-security, WS-transaction or similar features that are not exist in rest based web services. Oracle and similar companies pushing companies toward SOAP but open source is fading away from SOAP and choosing REST.

VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)

Best eclipse shortcut

0

I have been using eclipse for years. I were using several shortcuts to speed up things. But I have learned my favorite shortcut, CTRL+3 just a few months ago. It is something like one shortcut to learn them all. How could I miss this for years?

VN:F [1.9.13_1145]
Rating: 6.0/10 (1 vote cast)

Android’s ListView vs Java’s JList

0

I have several years of swing experience but I have recently started to play with android API. I have noticed one significant difference in terms of how Flyweight pattern is implemented. In JList you generally create an instance of a ListCellRenderer and return a swing component from getListCellRendererComponent method. Android has also a very similar mechanism. You extend BaseAdapter and return a View from getView method. In java how many different swing component instances you will return is directly determined by your getListCellRendererComponent. But in Android, framework manages a cache of View components and makes an instance available to you as a parameter to your getView method. And you have to return a new instance for every different row in current view pane. To achieve this you by checking whether convertView parameter supplied to your getView implementation is null, if it is null you create a new instance, if not you reuse supplied converView instance. If you return the same instance (as in the swing) android’s getView method will not work correctly. Swing’s implementation seems more lightweight in terms of memory. Same things could be said for editable state of rows. Same comparison is also valid for JTable of Swing and GridView of Android.

VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)

New Features of JDK 7 Explained

0

For an in company JDK 7 orientation I have prepared a presentation which summaries new features of JDK 7. I would like to make it public for everyone who needs it.

New Features of JDK 7 is available on slideshare.

You can also download pdf of it from here.

New Features Of JDK 7 — Presentation Transcript
1. Java Reloaded JDK 7 by Deniz Oğuz
2. Objective Learn what is included in JDK 7 and remember to use Google when required
3. JDK Release History Version Release Date JDK 1.0 1996-01-23 JDK 1.1 1997-02-18 JDK 1.1.4 1997-09-12 JDK 1.1.5 1997-12-03 JDK 1.1.6 1998-04-24 JDK 1.1.7 1998-09-28 • Normal release cycle was 2 years, J2SE is 3 JDK 1.1.8 1999-04-08 J2SE 1.2 1998-12-04 years late. It should have bean released at the J2SE 1.2.1 1999-03-30 end of 2008. J2SE 1.2.2 1999-07-08 J2SE 1.3 2000-05-08 • Some of the most wanted features are J2SE 1.3.1 2001-05-17 postponed to J2SE 8. J2SE 1.4.0 2002-02-13 J2SE 1.4.1 2002-09-16 J2SE 1.4.2 2003-06-26 J2SE 5.0 2004-09-29 J2SE 6 2006-12-11 Future Releases J2SE 7 2011-07-28 J2SE 8 Expected in late 2012
4. How to Try JDK 7 Features?1. Download JDK 7 build from jdk7.java.net  (download zipped version and extract to a folder)2. Download Netbeans 7  (download SE version, 80 MB)3. In the IDE, choose Tools > Java Platforms from the main menu4. Click Add Platform and specify the directory that contains the JDK5. Ensure JDK 1.7 is chosen in the Platforms list and click Close6. On Project Properties Libraries section Select JDK 1.7 as Java     Platform7. On Project Properties Sources section Select JDK 7 as Source/Binary Format
5. New Javadoc Format
6. Project Coin String in switch statement Binary literals Underscore in literals Diamond operator Improved exception handling Try with resource Simplified vararg methods invocation
7. String in Switch Statement Before JDK 7 only byte, short, char, int were allowed in switch statements JDK 7 allows Strings to be used in switch statements Why isn’t long supported in switch statements? Console console = System.console(); String day= console.readLine(); switch (day) { case “monday” : console.writer().write(“1″);break; case “tuesday” : console.writer().write(“2″);break; case “wednesday” : console.writer().write(“3″);break; case “thursday” : console.writer().write(“4″);break; case “friday” : console.writer().write(“5″);break; case “saturday” : console.writer().write(“6″);break; case “sunday” : console.writer().write(“7″);break; default:console.writer().write(“?”); } console.flush();
8. Binary Literals It is now easier to specify numbers in binary form  int mask = 0b00000000000000000000000011111111;  int mask = Integer.parseInt(“00000000000000000000000011111111”, 2);  int mask = 255;
9. Underscores in Numbers int money = 100_000_000; long creditCNumber = 3434_3423_4343_4232L; int mask = 0b0000_0000_0000_0000_0000_0000_1111_1111;
10. Diamond Operator Before JDK 7: Map<Integer, Track> trackStore = new ConcurrentHashMap<Integer, Track>(); With JDK 7: Map<Integer, Track> trackStore = new ConcurrentHashMap<>();
11. Multi Catch and Final Rethrow Problem : You want to handle multiple exceptions with the same code block.try { InputStream inStream = readStream(settingFile); Setting setting = parseFile(inStream); } catch (IOException ex) {     log.warn(“Can not access file”, settingFile); } catch (FileNotFoundException ex) { log.warn(“Can not access file”, settingFile); } catch (ParseException ex) { log.warn(“{} has incorrect format:{}”, settingFile, ex.getMessage()); }try { InputStream inStream = readStream(settingFile); Setting setting = parseFile(inStream); } catch (IOException | FileNotFoundException ex) { log.warn(“Can not access file”, settingFile); } catch (ParseException ex) { log.warn(“{} has incorrect format:{}”, settingFile, ex.getMessage()); }
12. Multi Catch and Final Re-throw Cont. Problem : You want to handle multiple exceptions with the same code block.public Setting readSettings(Strin settingFile) throws ParseException, IOException,FileNotFoundException { try { InputStream inStream = readStream(settingFile); Setting setting = parseFile(inStream); } catch (Throwable ex) { log.warn(“Can not read settings”, settingFile); throw ex; } ……………..}
13. Try With Resourceprivate static String readConfiguration(String file) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String line = null; StringBuilder content = new StringBuilder(1000); while ((line = reader.readLine()) != null) { content.append(line); } return content.toString(); } catch (IOException ex){ throw new ConfigurationException(“Can not read configuration file:{}”, file); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
14. Try With Resource Cont’private static String readConfigurationNew(String file) { try (BufferedReader reader = new BufferedReader(new FileReader(file));) { String line = null; StringBuilder content = new StringBuilder(1000); while ((line = reader.readLine()) != null) { content.append(line); } return content.toString(); } catch (IOException ex){ throw new ConfigurationException(“Can not read configuration file:{}”, file); } }
15. Try With Resource and Autocloseable A new interface AutoCloseable is introduced Existing Closeable interface is changed to extend AutoCloseable interface A new method addSuppressed(Exception) is added to Throwable Exceptions throwed from close method of AutoCloseable are suppressed in favor of exceptions throwed from try-catch block See JavaDoc of Autocloseable for more detail
16. Autocloseable and Suppressed ExceptionExceptions from try-catch body suppresses exceptions thrown from AutoCloseable.close public ABCResource implements AutoCloseable { @Override public void close() throws ABCException { dosomething(); if (errorCondition) { throw new ABCException(“Not supported yet.”); } } } public ClientClass { public void useABCResource() { try (ABCResource resource = new ABCResource();) { dosomething(); if (errorCondition) { throw new ClientException(“Not supported yet.”); } } } }
17. Better Support for Other Languages in JVM  Statically Typed vs Dynamically Typed  Compile time type checking vs runtime type checking  Java, C, Scala are examples of statically typed languages  Java Script, Ruby are examples of dynamically typed languages  Strongly Typed vs Weakly Typed  Automatic type conversion as necessary vs fixed type  Java Script is weakly typed language  Java is a strongly typed languagepublic void printTotal(a, b) { print a + b;}public void printTotal(int a, int b) { print a + b;}
18. Dynamic Typing was Difficult to Implement on JVM• New bytecode is introduced • invokeinterface • invokestatic • invokevirtual • invokespecial • invokedynamic (Only bytecode in JVM that is not used by Java PL)• Execution environment of the programming language provides a bootstrapmethod for resolving method invocations
19. Fork/Join Framework Uses work-stealing algorithm Task is broken into smaller parts recursively A new ExecutorService implementation ForkJoinPool is added ForkJoinTask and its subclasses RecursiveAction and RecursiveTask are added
20. General Usage Pattern of Fork/JoinResult compute(Problem problem) { if (problem is small) directly solve problem else { split problem into independent parts fork new subtasks to solve each part join all subtasks compose result from subresults }else { RecursiveTask left = new ComputationTask(array, low, mid); RecursiveTask right = new ComputationTask(array, mid, high); right.fork(); return left.compute() + right.join();}main { RecursiveTask computationTask = new ComputationTask(array, 0, array.length); ForkJoinPool mainPool = new ForkJoinPool(); Long result = mainPool.invoke(computationTask);}
21. Work Stealing Less thread contention Improved data locality Execute large tasks early
22. TransferQueue Allows producers to wait until message is processed by a consumer even if the queue is not    full. transfer(E e)  Transfers the element to a consumer, waiting if necessary to do so. tryTransfer(E e)  Transfers the element to a waiting consumer immediately, if possible. tryTransfer(E e, long timeout, TimeUnit unit)  Transfers the element to a consumer if it is possible to do so before the timeout elapses. getWaitingConsumerCount()  Returns an estimate of the number of consumers waiting to receive elements via BlockingQueue.take() or timed poll hasWaitingConsumer()  Returns true if there is at least one consumer waiting to receive an element via BlockingQueue.take () or timed poll.
23. ThreadLocalRandom A random number generator isolated to current thread Aim is to reduce contention in multi threaded environments Usage:  ThreadLocalRandom.current().nextInt(min, max);  ThreadLocalRandom.current().nextLong(min, max);  ThreadLocalRandom.current().nextDouble(min, max);
24. ConcurrentLinkedDeque Unbound concurrent deque based on linked nodes Concurrent insertion, removal, and access operations execute safely across multiple threads Iterators are weakly consistent and do not throw ConcurrentModificationException size() method is NOT constant in time Bulk operations are not guaranteed to perform atomically
25. Phaser An reusable synchronization barrier Similar to CyclicBarrier or CountDownLatch but with more advance features :  Allows number of registered parties to change after Phaser creation  Each generation increment phase number of phaser  There are blocking and non blocking versions of operations Extremely flexible and complex, use Javadoc when you need to use this class
26. SCTP Support Feature SCTP TCP UDPConnection-oriented  Full duplex   Reliable data transfer  Partial-reliable data transfer optionalOrdered data delivery  Unordered data delivery  Flow control  Congestion control  ECN capable  Selective ACKs  optionalPreservation of message boundaries  Path MTU discovery  Application PDU fragmentation  Application PDU bundling  Multistreaming Multihoming Protection against SYN flooding attacks  n/aAllows half-closed connections  n/aReachability check  Psuedo-header for checksum (uses vtags)  Time wait state for vtags for 4-tuple n/a • Not all operating systems support SCTP
27. The Need for Java NIO.2 Methods works inconsistently  Delete method sometimes can not delete  Rename method sometimes can not rename No Exception is thrown from failed method Accessing metadata of files is limited Does not scale well  Listing a directory may take a long time (especially over network directories) A change notification facility is not provided Developers wanted to create their own file system implementations  For example an in-memory file system
28. Pluggable FileSystems java.nio.file.FileSystems is factory for file systems. Implement java.nio.file.spi.FileSystemProvider to provide your own file systems  A filesystem provider for Zip and Jar files are included in JDK 7  You can implement a filesystem to open a ISO image as a file system, or implement a RAM disk etc…… java.nio.file.FileSystems.getDefault() is used most of the time Multiple/Alternate views of same underlying files  Hides some files for security, read-only view, etc.
29. java.nio.file.Path and java.nio.file.Files Use java.nio.file.Path and java.nio.file.Files instead of java.io.File  Use java.io.File.toPath and java.nio.file.Path.toFile methods to integrate with legacy code java.nio.file.Paths contains factory methods for java.nio.file.Path  static Path getPath(String first, String… more)  static Path getPath(URI uri) Once you obtained Path object use java.nio.file.Files static methods to process  copy, createLink, createTempFile, delete, exist, getPosixFilePermissions, getAttribute, isHidden, isExecutable, isSymbolicLink, newByteChannel ……
30. Asynchronous I/O Allows application to continue on something while waiting for I/O Asynchronous I/O operations will usually take one of two forms:  Future<V> operation(…)  void operation(… A attachment, CompletionHandler<V,? super A> handler) See classes AsynchronousXXXXChannel that extends AsynchronousChannel Path path = Paths.get(“/home/deniz/dropbox/Getting Started.pdf”); AsynchronousFileChannel ch = AsynchronousFileChannel.open(path); ByteBuffer buf = ByteBuffer.allocate(1024); Future<Integer> result = ch.read(buf, 0); //read does not block while (!result.isDone()) { System.out.println(“lets do something else while waiting”); } System.out.println(“Bytes read = ” + result.get()); //Future.get will block ch.close();
31. Watch Service WatchService allows you to monitor a watchable object for changes and events. It implements Reactor pattern. Just like Selector does for Channels. Use Watchable.register to register with java.nio.file.WatchService to listen changes WatchKey register(WatchService watcher, WatchEvent.Kind<?>… events)  WatchEvent.Kind is an interface, actual applicable alternatives depends on Watchable Example Watchable objects  Path, FileSystem Path path = Paths.get(“C:/Users/Deniz/Dropbox/”); WatchService watcher = path.getFileSystem().newWatchService(); while (true) { path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE); WatchKey key = watcher.take(); // block for event for (WatchEvent event : key.pollEvents()) { Path pathOfNewFile = (Path) event.context(); // path of new file System.out.println(“File is created:” + pathOfNewFile.toString()); } key.cancel(); }
32. FileVisitorPath start = …Files.walkFileTree(start, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE;   } public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { // directory iteration failed throw e; } }});
33. FileTypeDetector Files.walkFileTree(Paths.get(“C:/Users/Deniz/Downloads”), new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String fileType = Files.probeContentType(file); System.out.println(file.toString() + “:” + fileType); return FileVisitResult.CONTINUE; } });Output:C:UsersDenizDownloadsWirofon-Client-0.2.10-rc01.exe:application/x-msdownloadC:UsersDenizDownloadsPlan B-She Said.mp3:audio/mpegC:UsersDenizDownloadsROM or Kernel-Update.pdf:application/pdf
34. Xrender Pipeline Will replace OpenGL pipeline on Unix, Linux platforms  Due to poor OpenGL drivers OpenGL pipeline has several problems  A lot of drivers has optimized Xrender implementations  Xrender is more suited 2D applications than OpenGL  Xrender applications are native X11 applications  Other GUI libraries are also using Xrender for 2D effects  QT4, GTK+, KDE4 Use -Dsun.java2d.xrender=true to enable it
35. Translucent Windows Java SE 6u10 introduced com.sun.awt.AWTUtilities to support translucent and shaped windows  AWTUtilities is removed in JDK7  Simple translucencysetUndecorated(true);setOpacity (opacityValue); //opacity value is between 0.0 – 1.0 Per-Pixel translucencyColor colorA = new Color (255, 0, 0, 0); // Transparent redColor colorB = new Color (255, 0, 0, 255); // Solid redsetBackground(new Color (0, 0, 0, 0)); // activate per-pixel  Transparent and shaped windows // translucency.protected void paintComponent (Graphics g) { Graphics2D g2d = (Graphics2D) g; GradientPaint gp = new GradientPaint ( 0.0f, 0.0f, colorA, 0.0f, getHeight (), colorB, true); g2d.setPaint (gp); g2d.fillRect (0, 0, getWidth (), getHeight ());}
36. Shaped Windows  Shaped windows  Only the parts that belong to the given Shape remain visible and clickable  A shaped window can also be translucent if you wantsetUndecorated(true);setShape(new Ellipse2D.Float (0, 0, getWidth (), getHeight ()));For code samples see: Exploring JDK 7, Part 2: Translucent and Shaped Windows
37. JLayer and LayerUI Similar to GlassPane but it is a layer around any JComponent not only JRootPane You can mask mouse events in installUI methodLayerUI<JFormattedTextField> layerUI = new ValidationLayerUI();……JFormattedTextField dateField = new JFormattedTextField(dateFormat);JFormattedTextField numberField = new JFormattedTextField(numberFormat);……JPanel datePanel = new JPanel();……datePanel.add(new JLayer<JFormattedTextField>(dateField, layerUI));datePanel.add(new JLayer<JFormattedTextField>(numberField , layerUI));……class ValidationLayerUI extends LayerUI<JFormattedTextField> { public void paint (Graphics g, JComponent c) { super.paint (g, c); JLayer jlayer = (JLayer) c; JFormattedTextField ftf = (JFormattedTextField)jlayer.getView(); if (!ftf.isEditValid()) { //paint an error indicator using Graphics } }}//See http://download.oracle.com/javase/tutorial/uiswing/misc/jlayer.html for details
38. java.util.Objects Static utility methods for simplifying common operations on objects requireNonNull(T obj, String message)  Checks that the specified object reference is not null and throws a customized NullPointerException if it is int compare(T a, T b, Comparator<? super T> c)  Perform null and equals checks before invoking c.compare(a,b) boolean deepEquals(Object a, Object b) boolean equals(Object a, Object b)  Perform null checks and Arrays.deepEquals if necessary String toString(Object o, String nullDefault)  Perform null check and return nullDefault if o is null There are other similar methods, check javadoc
39. ThreadLocal  These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variableimport java.util.concurrent.atomic.AtomicInteger;public class UniqueThreadIdGenerator { private static final AtomicInteger uniqueId = new AtomicInteger(0); private static final ThreadLocal<Integer> uniqueNum = new ThreadLocal<Integer> () { @Override protected Integer initialValue() { return uniqueId.getAndIncrement(); } }; public static int getCurrentThreadId() { return uniqueId.get(); }} // UniqueThreadIdGenerator
40. Locale Category Locale.setDefault(Category, Locale) Locale Locale.getDefault(Category) Category.DISPLAY  Category used to represent the default locale for displaying user interfaces Category.FORMAT  Category used to represent the default locale for formatting dates, numbers, and/or currencies What about default locale Locale.getDefault() ?  It stays as a different locale (not display or format)     But Locale.setDefault(Locale) sets 3 different locales now:display, format and default locales  Default locale depends on OS environment variables or value of –D flags. Set it to English for your health and change newly provided locales (display/format)
41. References Exploring JDK 7, Part 2: Translucent and Shaped Windows What’s New in NIO.2 (pdf) JDK 7 Features The Java NIO.2 File System in JDK 7 Xrender Proposal Java 2D Enhancements in Java SE 7 How to Decorate Components with the JLayer Class StackOverflow
New Features Of JDK 7 — Presentation Transcript
1. Java Reloaded JDK 7 by Deniz Oğuz
2. Objective Learn what is included in JDK 7 and remember to use Google when required
3. JDK Release History Version Release Date JDK 1.0 1996-01-23 JDK 1.1 1997-02-18 JDK 1.1.4 1997-09-12 JDK 1.1.5 1997-12-03 JDK 1.1.6 1998-04-24 JDK 1.1.7 1998-09-28 • Normal release cycle was 2 years, J2SE is 3 JDK 1.1.8 1999-04-08 J2SE 1.2 1998-12-04 years late. It should have bean released at the J2SE 1.2.1 1999-03-30 end of 2008. J2SE 1.2.2 1999-07-08 J2SE 1.3 2000-05-08 • Some of the most wanted features are J2SE 1.3.1 2001-05-17 postponed to J2SE 8. J2SE 1.4.0 2002-02-13 J2SE 1.4.1 2002-09-16 J2SE 1.4.2 2003-06-26 J2SE 5.0 2004-09-29 J2SE 6 2006-12-11 Future Releases J2SE 7 2011-07-28 J2SE 8 Expected in late 2012
4. How to Try JDK 7 Features?1. Download JDK 7 build from jdk7.java.net  (download zipped version and extract to a folder)2. Download Netbeans 7  (download SE version, 80 MB)3. In the IDE, choose Tools > Java Platforms from the main menu4. Click Add Platform and specify the directory that contains the JDK5. Ensure JDK 1.7 is chosen in the Platforms list and click Close6. On Project Properties Libraries section Select JDK 1.7 as Java     Platform7. On Project Properties Sources section Select JDK 7 as Source/Binary Format
5. New Javadoc Format
6. Project Coin String in switch statement Binary literals Underscore in literals Diamond operator Improved exception handling Try with resource Simplified vararg methods invocation
7. String in Switch Statement Before JDK 7 only byte, short, char, int were allowed in switch statements JDK 7 allows Strings to be used in switch statements Why isn’t long supported in switch statements? Console console = System.console(); String day= console.readLine(); switch (day) { case “monday” : console.writer().write(“1″);break; case “tuesday” : console.writer().write(“2″);break; case “wednesday” : console.writer().write(“3″);break; case “thursday” : console.writer().write(“4″);break; case “friday” : console.writer().write(“5″);break; case “saturday” : console.writer().write(“6″);break; case “sunday” : console.writer().write(“7″);break; default:console.writer().write(“?”); } console.flush();
8. Binary Literals It is now easier to specify numbers in binary form  int mask = 0b00000000000000000000000011111111;  int mask = Integer.parseInt(“00000000000000000000000011111111”, 2);  int mask = 255;
9. Underscores in Numbers int money = 100_000_000; long creditCNumber = 3434_3423_4343_4232L; int mask = 0b0000_0000_0000_0000_0000_0000_1111_1111;
10. Diamond Operator Before JDK 7: Map<Integer, Track> trackStore = new ConcurrentHashMap<Integer, Track>(); With JDK 7: Map<Integer, Track> trackStore = new ConcurrentHashMap<>();
11. Multi Catch and Final Rethrow Problem : You want to handle multiple exceptions with the same code block.try { InputStream inStream = readStream(settingFile); Setting setting = parseFile(inStream); } catch (IOException ex) {     log.warn(“Can not access file”, settingFile); } catch (FileNotFoundException ex) { log.warn(“Can not access file”, settingFile); } catch (ParseException ex) { log.warn(“{} has incorrect format:{}”, settingFile, ex.getMessage()); }try { InputStream inStream = readStream(settingFile); Setting setting = parseFile(inStream); } catch (IOException | FileNotFoundException ex) { log.warn(“Can not access file”, settingFile); } catch (ParseException ex) { log.warn(“{} has incorrect format:{}”, settingFile, ex.getMessage()); }
12. Multi Catch and Final Re-throw Cont. Problem : You want to handle multiple exceptions with the same code block.public Setting readSettings(Strin settingFile) throws ParseException, IOException,FileNotFoundException { try { InputStream inStream = readStream(settingFile); Setting setting = parseFile(inStream); } catch (Throwable ex) { log.warn(“Can not read settings”, settingFile); throw ex; } ……………..}
13. Try With Resourceprivate static String readConfiguration(String file) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String line = null; StringBuilder content = new StringBuilder(1000); while ((line = reader.readLine()) != null) { content.append(line); } return content.toString(); } catch (IOException ex){ throw new ConfigurationException(“Can not read configuration file:{}”, file); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
14. Try With Resource Cont’private static String readConfigurationNew(String file) { try (BufferedReader reader = new BufferedReader(new FileReader(file));) { String line = null; StringBuilder content = new StringBuilder(1000); while ((line = reader.readLine()) != null) { content.append(line); } return content.toString(); } catch (IOException ex){ throw new ConfigurationException(“Can not read configuration file:{}”, file); } }
15. Try With Resource and Autocloseable A new interface AutoCloseable is introduced Existing Closeable interface is changed to extend AutoCloseable interface A new method addSuppressed(Exception) is added to Throwable Exceptions throwed from close method of AutoCloseable are suppressed in favor of exceptions throwed from try-catch block See JavaDoc of Autocloseable for more detail
16. Autocloseable and Suppressed ExceptionExceptions from try-catch body suppresses exceptions thrown from AutoCloseable.close public ABCResource implements AutoCloseable { @Override public void close() throws ABCException { dosomething(); if (errorCondition) { throw new ABCException(“Not supported yet.”); } } } public ClientClass { public void useABCResource() { try (ABCResource resource = new ABCResource();) { dosomething(); if (errorCondition) { throw new ClientException(“Not supported yet.”); } } } }
17. Better Support for Other Languages in JVM  Statically Typed vs Dynamically Typed  Compile time type checking vs runtime type checking  Java, C, Scala are examples of statically typed languages  Java Script, Ruby are examples of dynamically typed languages  Strongly Typed vs Weakly Typed  Automatic type conversion as necessary vs fixed type  Java Script is weakly typed language  Java is a strongly typed languagepublic void printTotal(a, b) { print a + b;}public void printTotal(int a, int b) { print a + b;}
18. Dynamic Typing was Difficult to Implement on JVM• New bytecode is introduced • invokeinterface • invokestatic • invokevirtual • invokespecial • invokedynamic (Only bytecode in JVM that is not used by Java PL)• Execution environment of the programming language provides a bootstrapmethod for resolving method invocations
19. Fork/Join Framework Uses work-stealing algorithm Task is broken into smaller parts recursively A new ExecutorService implementation ForkJoinPool is added ForkJoinTask and its subclasses RecursiveAction and RecursiveTask are added
20. General Usage Pattern of Fork/JoinResult compute(Problem problem) { if (problem is small) directly solve problem else { split problem into independent parts fork new subtasks to solve each part join all subtasks compose result from subresults }else { RecursiveTask left = new ComputationTask(array, low, mid); RecursiveTask right = new ComputationTask(array, mid, high); right.fork(); return left.compute() + right.join();}main { RecursiveTask computationTask = new ComputationTask(array, 0, array.length); ForkJoinPool mainPool = new ForkJoinPool(); Long result = mainPool.invoke(computationTask);}
21. Work Stealing Less thread contention Improved data locality Execute large tasks early
22. TransferQueue Allows producers to wait until message is processed by a consumer even if the queue is not    full. transfer(E e)  Transfers the element to a consumer, waiting if necessary to do so. tryTransfer(E e)  Transfers the element to a waiting consumer immediately, if possible. tryTransfer(E e, long timeout, TimeUnit unit)  Transfers the element to a consumer if it is possible to do so before the timeout elapses. getWaitingConsumerCount()  Returns an estimate of the number of consumers waiting to receive elements via BlockingQueue.take() or timed poll hasWaitingConsumer()  Returns true if there is at least one consumer waiting to receive an element via BlockingQueue.take () or timed poll.
23. ThreadLocalRandom A random number generator isolated to current thread Aim is to reduce contention in multi threaded environments Usage:  ThreadLocalRandom.current().nextInt(min, max);  ThreadLocalRandom.current().nextLong(min, max);  ThreadLocalRandom.current().nextDouble(min, max);
24. ConcurrentLinkedDeque Unbound concurrent deque based on linked nodes Concurrent insertion, removal, and access operations execute safely across multiple threads Iterators are weakly consistent and do not throw ConcurrentModificationException size() method is NOT constant in time Bulk operations are not guaranteed to perform atomically
25. Phaser An reusable synchronization barrier Similar to CyclicBarrier or CountDownLatch but with more advance features :  Allows number of registered parties to change after Phaser creation  Each generation increment phase number of phaser  There are blocking and non blocking versions of operations Extremely flexible and complex, use Javadoc when you need to use this class
26. SCTP Support Feature SCTP TCP UDPConnection-oriented  Full duplex   Reliable data transfer  Partial-reliable data transfer optionalOrdered data delivery  Unordered data delivery  Flow control  Congestion control  ECN capable  Selective ACKs  optionalPreservation of message boundaries  Path MTU discovery  Application PDU fragmentation  Application PDU bundling  Multistreaming Multihoming Protection against SYN flooding attacks  n/aAllows half-closed connections  n/aReachability check  Psuedo-header for checksum (uses vtags)  Time wait state for vtags for 4-tuple n/a • Not all operating systems support SCTP
27. The Need for Java NIO.2 Methods works inconsistently  Delete method sometimes can not delete  Rename method sometimes can not rename No Exception is thrown from failed method Accessing metadata of files is limited Does not scale well  Listing a directory may take a long time (especially over network directories) A change notification facility is not provided Developers wanted to create their own file system implementations  For example an in-memory file system
28. Pluggable FileSystems java.nio.file.FileSystems is factory for file systems. Implement java.nio.file.spi.FileSystemProvider to provide your own file systems  A filesystem provider for Zip and Jar files are included in JDK 7  You can implement a filesystem to open a ISO image as a file system, or implement a RAM disk etc…… java.nio.file.FileSystems.getDefault() is used most of the time Multiple/Alternate views of same underlying files  Hides some files for security, read-only view, etc.
29. java.nio.file.Path and java.nio.file.Files Use java.nio.file.Path and java.nio.file.Files instead of java.io.File  Use java.io.File.toPath and java.nio.file.Path.toFile methods to integrate with legacy code java.nio.file.Paths contains factory methods for java.nio.file.Path  static Path getPath(String first, String… more)  static Path getPath(URI uri) Once you obtained Path object use java.nio.file.Files static methods to process  copy, createLink, createTempFile, delete, exist, getPosixFilePermissions, getAttribute, isHidden, isExecutable, isSymbolicLink, newByteChannel ……
30. Asynchronous I/O Allows application to continue on something while waiting for I/O Asynchronous I/O operations will usually take one of two forms:  Future<V> operation(…)  void operation(… A attachment, CompletionHandler<V,? super A> handler) See classes AsynchronousXXXXChannel that extends AsynchronousChannel Path path = Paths.get(“/home/deniz/dropbox/Getting Started.pdf”); AsynchronousFileChannel ch = AsynchronousFileChannel.open(path); ByteBuffer buf = ByteBuffer.allocate(1024); Future<Integer> result = ch.read(buf, 0); //read does not block while (!result.isDone()) { System.out.println(“lets do something else while waiting”); } System.out.println(“Bytes read = ” + result.get()); //Future.get will block ch.close();
31. Watch Service WatchService allows you to monitor a watchable object for changes and events. It implements Reactor pattern. Just like Selector does for Channels. Use Watchable.register to register with java.nio.file.WatchService to listen changes WatchKey register(WatchService watcher, WatchEvent.Kind<?>… events)  WatchEvent.Kind is an interface, actual applicable alternatives depends on Watchable Example Watchable objects  Path, FileSystem Path path = Paths.get(“C:/Users/Deniz/Dropbox/”); WatchService watcher = path.getFileSystem().newWatchService(); while (true) { path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE); WatchKey key = watcher.take(); // block for event for (WatchEvent event : key.pollEvents()) { Path pathOfNewFile = (Path) event.context(); // path of new file System.out.println(“File is created:” + pathOfNewFile.toString()); } key.cancel(); }
32. FileVisitorPath start = …Files.walkFileTree(start, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE;   } public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { // directory iteration failed throw e; } }});
33. FileTypeDetector Files.walkFileTree(Paths.get(“C:/Users/Deniz/Downloads”), new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String fileType = Files.probeContentType(file); System.out.println(file.toString() + “:” + fileType); return FileVisitResult.CONTINUE; } });Output:C:UsersDenizDownloadsWirofon-Client-0.2.10-rc01.exe:application/x-msdownloadC:UsersDenizDownloadsPlan B-She Said.mp3:audio/mpegC:UsersDenizDownloadsROM or Kernel-Update.pdf:application/pdf
34. Xrender Pipeline Will replace OpenGL pipeline on Unix, Linux platforms  Due to poor OpenGL drivers OpenGL pipeline has several problems  A lot of drivers has optimized Xrender implementations  Xrender is more suited 2D applications than OpenGL  Xrender applications are native X11 applications  Other GUI libraries are also using Xrender for 2D effects  QT4, GTK+, KDE4 Use -Dsun.java2d.xrender=true to enable it
35. Translucent Windows Java SE 6u10 introduced com.sun.awt.AWTUtilities to support translucent and shaped windows  AWTUtilities is removed in JDK7  Simple translucencysetUndecorated(true);setOpacity (opacityValue); //opacity value is between 0.0 – 1.0 Per-Pixel translucencyColor colorA = new Color (255, 0, 0, 0); // Transparent redColor colorB = new Color (255, 0, 0, 255); // Solid redsetBackground(new Color (0, 0, 0, 0)); // activate per-pixel  Transparent and shaped windows // translucency.protected void paintComponent (Graphics g) { Graphics2D g2d = (Graphics2D) g; GradientPaint gp = new GradientPaint ( 0.0f, 0.0f, colorA, 0.0f, getHeight (), colorB, true); g2d.setPaint (gp); g2d.fillRect (0, 0, getWidth (), getHeight ());}
36. Shaped Windows  Shaped windows  Only the parts that belong to the given Shape remain visible and clickable  A shaped window can also be translucent if you wantsetUndecorated(true);setShape(new Ellipse2D.Float (0, 0, getWidth (), getHeight ()));For code samples see: Exploring JDK 7, Part 2: Translucent and Shaped Windows
37. JLayer and LayerUI Similar to GlassPane but it is a layer around any JComponent not only JRootPane You can mask mouse events in installUI methodLayerUI<JFormattedTextField> layerUI = new ValidationLayerUI();……JFormattedTextField dateField = new JFormattedTextField(dateFormat);JFormattedTextField numberField = new JFormattedTextField(numberFormat);……JPanel datePanel = new JPanel();……datePanel.add(new JLayer<JFormattedTextField>(dateField, layerUI));datePanel.add(new JLayer<JFormattedTextField>(numberField , layerUI));……class ValidationLayerUI extends LayerUI<JFormattedTextField> { public void paint (Graphics g, JComponent c) { super.paint (g, c); JLayer jlayer = (JLayer) c; JFormattedTextField ftf = (JFormattedTextField)jlayer.getView(); if (!ftf.isEditValid()) { //paint an error indicator using Graphics } }}//See http://download.oracle.com/javase/tutorial/uiswing/misc/jlayer.html for details
38. java.util.Objects Static utility methods for simplifying common operations on objects requireNonNull(T obj, String message)  Checks that the specified object reference is not null and throws a customized NullPointerException if it is int compare(T a, T b, Comparator<? super T> c)  Perform null and equals checks before invoking c.compare(a,b) boolean deepEquals(Object a, Object b) boolean equals(Object a, Object b)  Perform null checks and Arrays.deepEquals if necessary String toString(Object o, String nullDefault)  Perform null check and return nullDefault if o is null There are other similar methods, check javadoc
39. ThreadLocal  These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variableimport java.util.concurrent.atomic.AtomicInteger;public class UniqueThreadIdGenerator { private static final AtomicInteger uniqueId = new AtomicInteger(0); private static final ThreadLocal<Integer> uniqueNum = new ThreadLocal<Integer> () { @Override protected Integer initialValue() { return uniqueId.getAndIncrement(); } }; public static int getCurrentThreadId() { return uniqueId.get(); }} // UniqueThreadIdGenerator
40. Locale Category Locale.setDefault(Category, Locale) Locale Locale.getDefault(Category) Category.DISPLAY  Category used to represent the default locale for displaying user interfaces Category.FORMAT  Category used to represent the default locale for formatting dates, numbers, and/or currencies What about default locale Locale.getDefault() ?  It stays as a different locale (not display or format)     But Locale.setDefault(Locale) sets 3 different locales now:display, format and default locales  Default locale depends on OS environment variables or value of –D flags. Set it to English for your health and change newly provided locales (display/format)

41. References Exploring JDK 7, Part 2: Translucent and Shaped Windows What’s New in NIO.2 (pdf) JDK 7 Features The Java NIO.2 File System in JDK 7 Xrender Proposal Java 2D Enhancements in Java SE 7 How to Decorate Components with the JLayer Class StackOverflow

VN:F [1.9.13_1145]
Rating: 10.0/10 (1 vote cast)

Cassandra Data Model

0

As you know from my previous post, database backend of Trendocean is Apache Cassandra. If you have relational database background, data model of Cassandra is difficult to work with. Things get more difficult if nature of your application’s data is highly relational. You have to manage every relation yourself. You have to implement cascaded deletes, and foreign keys. When we have started to use Cassandra there were no secondary index support so we had to generate lots of extra tables to for queries and keeping record of mappings for some UUID fields. Although it was fun for us to experiment with a new technology, with the current state of the tools it was difficult to work with when compared to relational database world.

Data model of our application was simple and it was still difficult to work with, so do not even thing about using  Cassandra something like JC3IEDM.

VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)

trendocean.com

0

I want to introduce trendocean.com to you. It is a multiple choice based question and answer site with social parts. It is a social network where you can see who are popular/marginal, ask and answer questions, follow people and keep in touch with your friends.

trendocean_home

 

Main difference of this question and answer site from others is it is based on multiple choice questions. Since it is multiple choice you do not need to read long answers and you can access statistical information about your choice. Currently they only provide distribution of answers for each choice but in the feature they will provide distribution of choices based on gender, city, country, education and age.

trendocean_oneq

 

Technologically it uses Glassfish and Apache Cassandra at the backend and uses html, javascript and jquery for user interface. It also provides a REST based API for other clients. We really appreciate your feedback at info@trendocean.com.

VN:F [1.9.13_1145]
Rating: 8.5/10 (2 votes cast)

Podcast Suggestions for Software Engineers

0

I try to follow several podcast to catch up with my profession and technology. Generally time cost of listening a podcast is zero. For example you can listen them while driving, walking, etc. Followings are my favorite podcasts, I hope you like them.

  • Java Posse: This is my favorite podcast. If you will listen only one, choose this one. 4 professional talks about Java related technologies. Some times they talk about gadgets like IPhone, Android, tables etc. By listening this podcast you will have general idea of what is happing in Java Community. You may consider to subscribing Google Groups for this podcast. Their recording quality is also very good. They are currently at episode 336, and they are very active since 2005.
  • Software Engineering Radio:They cover wide range of architectural issues. It is not a programming language specific. Recording quality is not as good as Java Posse. Each episode is made with a quest speaker who is closely related with topic of current episode.
  • Glassfish Podcast: This one is about JEE and Glassfish Application Server. Although it is named as Glassfish Podcast, it is still very useful if you are interested in JEE.
  • English as A Second Language: This one is not related to software engineering. But for us, English is a must. This is a very useful podcast for improving your listening and vocabulary.  In addition to improving your English you may improve your knowledge about American Culture.
VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)

Installing GoDaddy SSL Certificates on Glassfish v3 Step by Step

1

Introduction to Glassfish SSL

Newly created domains on glassfish has already a self signed certificate in DOMAIN_DIR/config/keystore.jks file. By default this keystore has default password of “changeit”. This certificate is named as s1as. To see this certificate you could issue following command:

keytool -list -keystore keystore.jks

When asked enter default password “changeit”. You will see a similar output to following:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 6 entries

s1as, Dec 28, 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): EA:56:23:46:7E:12:DA:6A:0D:8C:B9:12:11:0A:1A:8B

There should be a certificate with alias s1as. Since your glassfish will use this certificate by default, your domain.xml file in config folder of your domain will contain references to s1as from several places. We will change these references later.

I recommend you to change default password of keystore.jks. To change password use following command:

keytool  -sotrepasswd –keystore keystore.jks

When asked enter default password “changeit” and later enter new password for you keystore.jks. You should not forget this password. You will need this password for every operation you will perform on your keystore.jks file. Also you will be asked this password every time you start your domain. This password is called master password for your keystore.jks. Each entry in keystore.jks may have its own password, I recommend to make these passwords same with master password if possible.

There is another key file in glassfish’s domain folder named cacerts.jks. This file contains certificates from trusted authorities like godaddy, verisign etc. Certificates from this file is used to verify integrity of certificates you will purchase from certificate authorities. These certificates are called root certificates. But you may also import root certificates to keystore.jks too.

Purchasing Certificate and Installing Certificate

When you buy a certificate from a certificate authority (for example Godaddy) you have given a credit for certificate. You have to convert this credit to valid SSL certificate. To convert a credit to certificate you have to complete several step.

1) Check and correct Whois database entry for your domain:

Check your domain’s whois information and if they are not correct fix them. Especially your company name, and email address. GoDaddy will send an approval email to this email address.

2) Generate a certification request by using following steps:

Generate a new entry in keystore.jks with information of your domain.

keytool -keysize 2048 -genkey -alias www.yourdomain.com -keyalg RSA –dname "CN=www.domain.com,O=company,L=city,S=State,C=Country" -keystore keystore.jks

Enter password of you keystore when asked. GoDaddy requires at least 2048 bits keysize. CN is your sites domain name, O is your company name, L is the city, C is the 2 character country code. There are more options you could specify if you want. But these are enough. alias is the key you will use to refer this certificate. We will refer it from domain.xml.

Create the request file for submitting to Godaddy.

keytool –certreq –alias www.yourdomain.com –keystore keysore.jks –file cert_req.csr

Enter password of you keystore when asked.

cert_req.csr file will contains your certification request which you will submit to certificate authority. For GoDaddy you will open this file with a text editor and enter it to a text area as shown in following figure:

csr entry

You should include everything between and including followings.

—–BEGIN NEW CERTIFICATE REQUEST—–

—–END NEW CERTIFICATE REQUEST—–
After completing certification request submission. They will send an approval email to your email address shown on whois database.

3) Approve certification and import your certificates.

After approval you need to download a zip file which contains all certificates you need. During this step you will be asked for which server you are downloading certificates. You could select other because glassfish is not listed. Your download will contain 4 files:

  • gd_bundle.crt
  • gd_cross_intermediate.crt
  • gd_intermediate.crt
  • yourdomain.com.crt

First 3 of them are certificates belonging to godaddy.com. They are used to verify your domain’s certificate. They may already contained in your cacerts.jks but there is no harm importing them in your keystore.jks. Import these certificates to your keystore.jsk  using following steps:

keytool -import -alias root -keystore keystore.jks -trustcacerts -file gd_bundle.crt

keytool -import -alias cross -keystore keystore.jks -trustcacerts -file gd_cross_intermediate.crt

keytool -import -alias intermed -keystore keystore.jks -trustcacerts -file gd_intermed.crt

keytool -import -alias www.yourdomain.com -keystore keystore.jks -trustcacerts -file yourdomain.com.crt

If you are warned certificate already exist with a different alias choose yes to continue importing certificate.

As we have said at the beginning your domain’s domain.xml file contains references to s1as certificate. Open domain.xml with your editor of choice and replace every s1as with www.yourdomain.com and save it.

4) Test your setup

Start your domain using following command. You will be asked master password of your keystore.jks.

asadmin start-domain your_domain

Enter master password (3) attempt(s) remain)>Enter your master password here

Check your setup my navigating to https://www.yourdomain.com:ssl_port/. Your browser of choice will either warn you about invalid certificate, or you will see that it is verified by Godaddy.com. ssl_port is by default 8181, if you haven’t changed it yet from your domain.xml. If you change it to default 443, do not forget to configure your firewall to allow TCP over that port.

VN:F [1.9.13_1145]
Rating: 10.0/10 (2 votes cast)

java.lang.OutOfMemoryError and Native Memory

0

Thanks for the Memory” is a must read article for every java developer. It is a very good explanation of why sometimes you may need to REDUCE heap size to prevent java.lang.OutofMemoryError. You could download pdf of article writen by Andrew Hall and published at IBM Developerworks.

VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)

HTML 5 Up And Running

0

I could recommend this book to everyone who wants a high level overview of features introduced in HTML 5. Each feature has its own chapter. How to detect browser support for each feature, work around for older browsers (especially internet explorer) are also explained. The book does not go into details of each feature. You can buy the book or go to the book’s site which hosts full version of the book. My favorite chapter was new video element, it is a good introduction to codecs, containers and differences between platforms like, firefox, opera, internet explorer, safari, ios, android.

VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
Go to Top