DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Java Topics

article thumbnail
Clojure: Converting a string to a date
I wanted to do some date manipulation in Clojure recently and figured that since clj-time is a wrapper around Joda Time it’d probably do the trick. The first thing we need to do is add the dependency to our project file and then run lein reps to pull down the appropriate JARs. The project file should look something like this: project.clj (defproject ranking-algorithms "0.1.0-SNAPSHOT" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [[org.clojure/clojure "1.4.0"] [clj-time "0.6.0"]]) Now let’s load the clj-time.format namespace into the REPL since we know we’ll be parsing dates: > (require '(clj-time [format :as f])) The string that I want to convert into a date looks like this: (def string-date "18 September 2012") The first thing we should do is check whether there is an existing formatter that we can use by evaluating the following function: > (f/show-formatters) ... :hour-minute 06:45 :hour-minute-second 06:45:22 :hour-minute-second-fraction 06:45:22.473 :hour-minute-second-ms 06:45:22.473 :mysql 2013-09-20 06:45:22 :ordinal-date 2013-263 :ordinal-date-time 2013-263T06:45:22.473Z :ordinal-date-time-no-ms 2013-263T06:45:22Z :rfc822 Fri, 20 Sep 2013 06:45:22 +0000 ... There are a lot of different built in formatters but unfortunately I couldn’t find one that exactly matched our date format so we’ll have to write our own one. For that we’ll need to refresh our knowledge of Java date formatting: We end up with the following formatter: > (f/parse (f/formatter "dd MMM YYYY") string-date) # It took me much longer than it should have to remember that ‘MMM’ is the pattern to match a short form of a month but it’s just the same as what we’d have to do in Java but with some neat wrapper functions.
October 2, 2013
by Mark Needham
· 5,884 Views
article thumbnail
Introducing the NPM Maven Plugin
This post comes from Alberto Pose at the MuleSoft blog. Introduction Suppose that you have a Maven project and you want to download Node.js modules previously uploaded to NPM. One way of doing that without running node is by using the npm-maven-plugin. It allows the user to download the required Node modules without running node.js: It is completely implemented on the JVM. Getting Started First of all, you will need to add the Mule Maven repo to your pom.xml file: mulesoft-releases MuleSoft Repository https://repository.mulesoft.org/releases/ After doing that, you will need to add the following to the build->plugin section of your pom.xml file: org.mule.tools.javascript npm-maven-plugin 1.0 generate-sources fetch-modules colors:0.5.1 jshint:0.8.1 Then just execute: mvn generate-sources and that’s it! One more thing… By default, the modules can be found in src/main/resources/META-INF but that path can be changed setting the ‘outputDirectory’ parameter. Also, module transitivity is taken into account. That means that it will download all the required dependencies before downloading the specified module. Show me the code! The source code can be found here. Feel free to fork the project and propose changes to it. Happy (Node.js and Maven) hacking!
October 1, 2013
by Ross Mason
· 18,873 Views · 1 Like
article thumbnail
ElasticSearch: Java API
ElasticSearch provides Java API, thus it executes all operations asynchronously by using client object.
September 30, 2013
by Hüseyin Akdoğan DZone Core CORE
· 137,593 Views · 4 Likes
article thumbnail
Clojure: Converting an Array/Set into a Hash Map
When I was implementing the Elo Rating algorithm a few weeks ago one thing I needed to do was come up with a base ranking for each team. I started out with a set of teams that looked like this: (def teams #{ "Man Utd" "Man City" "Arsenal" "Chelsea"}) and I wanted to transform that into a map from the team to their ranking e.g. Man Utd -> {:points 1200} Man City -> {:points 1200} Arsenal -> {:points 1200} Chelsea -> {:points 1200} I had read the documentation of array-map, a function which can be used to transform a collection of pairs into a map, and it seemed like it might do the trick. I started out by building an array of pairs using mapcat: > (mapcat (fn [x] [x {:points 1200}]) teams) ("Chelsea" {:points 1200} "Man City" {:points 1200} "Arsenal" {:points 1200} "Man Utd" {:points 1200}) array-map constructs a map from pairs of values e.g. > (array-map "Chelsea" {:points 1200} "Man City" {:points 1200} "Arsenal" {:points 1200} "Man Utd" {:points 1200}) ("Chelsea" {:points 1200} "Man City" {:points 1200} "Arsenal" {:points 1200} "Man Utd" {:points 1200}) Since we have a collection of pairs rather than individual pairs we need to use the apply function as well: > (apply array-map ["Chelsea" {:points 1200} "Man City" {:points 1200} "Arsenal" {:points 1200} "Man Utd" {:points 1200}]) {"Chelsea" {:points 1200}, "Man City" {:points 1200}, "Arsenal" {:points 1200}, "Man Utd" {:points 1200} And if we put it all together we end up with the following: > (apply array-map (mapcat (fn [x] [x {:points 1200}]) teams)) {"Man Utd" {:points 1200}, "Man City" {:points 1200}, "Arsenal" {:points 1200}, "Chelsea" {:points 1200} It works but the function we pass to mapcat feels a bit clunky. Since we just need to create a collection of team/ranking pairs we can use the vector and repeat functions to build that up instead: > (mapcat vector teams (repeat {:points 1200})) ("Chelsea" {:points 1200} "Man City" {:points 1200} "Arsenal" {:points 1200} "Man Utd" {:points 1200}) And if we put the apply array-map code back in we still get the desired result: > (apply array-map (mapcat vector teams (repeat {:points 1200}))) {"Chelsea" {:points 1200}, "Man City" {:points 1200}, "Arsenal" {:points 1200}, "Man Utd" {:points 1200} Alternatively we could use assoc like this: > (apply assoc {} (mapcat vector teams (repeat {:points 1200}))) {"Man Utd" {:points 1200}, "Arsenal" {:points 1200}, "Man City" {:points 1200}, "Chelsea" {:points 1200} I also came across the into function which seemed useful but took in a collection of vectors: > (into {} [["Chelsea" {:points 1200}] ["Man City" {:points 1200}] ["Arsenal" {:points 1200}] ["Man Utd" {:points 1200}] ]) We therefore need to change the code to use map instead of mapcat: > (into {} (map vector teams (repeat {:points 1200}))) {"Chelsea" {:points 1200}, "Man City" {:points 1200}, "Arsenal" {:points 1200}, "Man Utd" {:points 1200} However, my favourite version so far uses the zipmap function like so: > (zipmap teams (repeat {:points 1200})) {"Man Utd" {:points 1200}, "Arsenal" {:points 1200}, "Man City" {:points 1200}, "Chelsea" {:points 1200} I’m sure there are other ways to do this as well so if you know any let me know in the comments.
September 28, 2013
by Mark Needham
· 13,119 Views
article thumbnail
Creating Custom JavaFX Components with Scene Builder and FXML.
one of the goals of our development with our javafx application is to try to keep as much of the ui design as possible within the scene builder ui design tool , and the business logic for the application in java. one of the things that is not entirely clear is how to create a new component in scene builder and then reuse that component within other components created in scene builder. in the example below, i illustrate how to create a custom table and ‘add plan’ components, and then add them to a new scene using fxml. the first step is to create a simple component which acts as an “add plan” widget on the ui. the widget contains an anchorpane, imageview and label. for the next step, open up the fxml file and change the first “anchorpane” declaration to “ create a class which will act as both the root of the component as well as its controller. the class must extend the type that was previously defined in the fxml file. use the fxml loader to set the root and controller of the component to “this” class, and then load the component’s fxml file. /* * to change this template, choose tools | templates * and open the template in the editor. */ package com.lynden.fx.test; import com.lynden.ui.util.uiutilities; import java.io.ioexception; import javafx.event.eventhandler; import javafx.fxml.fxml; import javafx.fxml.fxmlloader; import javafx.scene.input.dragevent; import javafx.scene.input.dragboard; import javafx.scene.input.transfermode; import javafx.scene.layout.anchorpane;/** * * @author robt */ public class testbutton extends anchorpane { @fxml private anchorpane mytestbutton; public testbutton() { fxmlloader fxmlloader = new fxmlloader( getclass().getresource("/com/lynden/planning/ui/testbutton.fxml")); fxmlloader.setroot(this); fxmlloader.setcontroller(this); try { fxmlloader.load(); } catch (ioexception exception) { throw new runtimeexception(exception); } } } next, the 2nd component is a tableview which contains a collection of beans, and displays their corresponding data. as with the last component, the first declaration is changed to next, the corresponding root and controller class is created for the table component. /* * to change this template, choose tools | templates * and open the template in the editor. */ package com.lynden.fx.test; import com.lynden.fx.inboundbean; import java.io.ioexception; import javafx.event.eventhandler; import javafx.event.eventtype; import javafx.fxml.fxml; import javafx.fxml.fxmlloader; import javafx.scene.control.tableview; import javafx.scene.input.clipboardcontent; import javafx.scene.input.dragboard; import javafx.scene.input.mouseevent; import javafx.scene.input.transfermode; import javafx.scene.layout.anchorpane; /** * * @author robt */ public class testtable extends anchorpane { @fxml private tableview mytableview; public testtable() { fxmlloader fxmlloader = new fxmlloader( getclass().getresource("/com/lynden/planning/ui/testtable.fxml")); fxmlloader.setroot(this); fxmlloader.setcontroller(this); try { fxmlloader.load(); } catch (ioexception exception) { throw new runtimeexception(exception); } } } finally, a new scene can be created which includes both the testtable and testbutton components that were constructed above. unfortunately, custom components can’t be added to the scene builder palette, so they must be inserted manually into the fxml file. you just need to ensure that you have the proper import statements defined, and the testtable and testbutton components can be inserted into the fxml code just as any native javafx component. when scene builder opens the fxml file you will see that both components are displayed on the new scene that’s it, hopefully this will help others who have been looking at adding custom components to their uis that are designed with scene builder. twitter: @robterp
September 25, 2013
by Rob Terpilowski
· 61,466 Views · 1 Like
article thumbnail
Clojure: Updating keys in a map
I’ve been playing with Clojure over the last few weeks and as a result I’ve been using a lot of maps to represent the data. For example if we have the following map of teams to Glicko ratings and ratings deviations: (def teams { "Man. United" {:points 1500 :rd 350} "Man. City" {:points 1450 :rd 300} }) We might want to increase Man. United’s points score by one for which we could use the update-in function: > (update-in teams ["Man. United" :points] inc) {"Man. United" {:points 1501, :rd 350}, "Man. City" {:points 1450, :rd 300} The 2nd argument to update-in is a nested associative structure i.e. a sequence of keys into the map in this instance. If we wanted to reset Man. United’s points score we could use assoc-in: > (assoc-in teams ["Man. United" :points] 1) {"Man. United" {:points 1, :rd 350}, "Man. City" {:points 1450, :rd 300} If we want to update multiple keys at once then we can chain them using the -> (thread first) macro: (-> teams (assoc-in ["Man. United" :points] 1600) (assoc-in ["Man. United" :rd] 200)) {"Man. United" {:points 1600, :rd 200}, "Man. City" {:points 1450, :rd 300} If instead of replacing just one part of the value we want to replace the whole entry we could use associnstead: > (assoc teams "Man. United" {:points 1600 :rd 300}) {"Man. United" {:points 1600, :rd 300}, "Man. City" {:points 1450, :rd 300} assoc can also be used to add a new key/value to the map. e.g. > (assoc teams "Arsenal" {:points 1500 :rd 330}) {"Man. United" {:points 1500, :rd 350}, "Arsenal" {:points 1500, :rd 330}, "Man. City" {:points 1450, :rd 300} dissoc plays the opposite role and returns a new map without the specified keys: > (dissoc teams "Man. United" "Man. City") {} And those are all the map based functions I’ve played around with so far…
September 24, 2013
by Mark Needham
· 6,179 Views
article thumbnail
How to generate Hailstone Sequence in Java?
Program Statement How to generate Hailstone Sequence in Java? Solution The Hailstone sequence of numbers can be generated from a starting positive integer, n by: If n is 1 then the sequence ends. If n is even then the next n of the sequence = n/2 If n is odd then the next n of the sequence = (3 * n) + 1 Code ? package com.skilledmonster.examples.operations; import java.util.Scanner; /** * Program to generate Hailstone Sequence. * This program reads a number from the user then displays the Hailstone sequence * for that number followed by a line that shows the number of steps taken to reach 1. * * @author Jagadeesh Motamarri * @version 1.0 */ public class HailstoneSequenceGenerator { public static void main(String[] args) { Scanner inputScanner = new Scanner(System.in); System.out.printf("Enter a Number: "); try { int number = inputScanner.nextInt(); int steps = 0; while (number != 1) { if (number % 2 == 0) { System.out.println(number + " is even, so I take half: " + number / 2); number /= 2; } else { System.out.println(number + " is odd, so I make 3n + 1: " + (number * 3 + 1)); number = number * 3 + 1; } steps++; } System.out.println("The process took " + steps + (steps < 2 ? " step" : " steps") + " to reach 1"); } catch (Exception e) { System.out.println("Not a Number!! Run your Program again "); } } } Output As shown in the console output, for interger 17, it took 12 steps to reach 1 using Hailstone Sequence. References http://en.wikipedia.org/wiki/Collatz_conjecture
September 20, 2013
by Jagadeesh Motamarri
· 31,667 Views · 16 Likes
article thumbnail
Top 10 Methods for Java Arrays
The following are top 10 methods for Java Array. They are the most voted questions from stackoverflow. 0. Decalre an array String[] aArray = new String[5]; String[] bArray = {"a","b","c", "d", "e"}; String[] cArray = new String[]{"a","b","c","d","e"}; 1. Print an array in Java int[] intArray = { 1, 2, 3, 4, 5 }; String intArrayString = Arrays.toString(intArray); // print directly will print reference value System.out.println(intArray); // [I@7150bd4d System.out.println(intArrayString); // [1, 2, 3, 4, 5] 2. Create ArrayList from array String[] stringArray = { "a", "b", "c", "d", "e" }; ArrayList arrayList = new ArrayList(Arrays.asList(stringArray)); System.out.println(arrayList); // [a, b, c, d, e] 3. Check if an array contains a certain value String[] stringArray = { "a", "b", "c", "d", "e" }; boolean b = Arrays.asList(stringArray).contains("a"); System.out.println(b); // true 4. Concatenate two arrays int[] intArray = { 1, 2, 3, 4, 5 }; int[] intArray2 = { 6, 7, 8, 9, 10 }; // Apache Commons Lang library int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2); 5. Declare array inline method(new String[]{"a", "b", "c", "d", "e"}); 6. Joins the elements of the provided array into a single String // containing the provided list of elements // Apache common lang String j = StringUtils.join(new String[] { "a", "b", "c" }, ", "); System.out.println(j); // a, b, c 7. Covnert ArrayList to Array String[] stringArray = { "a", "b", "c", "d", "e" }; ArrayList arrayList = new ArrayList(Arrays.asList(stringArray)); String[] stringArr = new String[arrayList.size()]; arrayList.toArray(stringArr); for (String s : stringArr) System.out.println(s); 8. Convert Array to Set Set set = new HashSet(Arrays.asList(stringArray)); System.out.println(set); //[d, e, b, c, a] 9. Reverse an array int[] intArray = { 1, 2, 3, 4, 5 }; ArrayUtils.reverse(intArray); System.out.println(Arrays.toString(intArray)); //[5, 4, 3, 2, 1] 10. Remove element of an array int[] intArray = { 1, 2, 3, 4, 5 }; int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array System.out.println(Arrays.toString(removed)); One more – convert int to byte array byte[] bytes = ByteBuffer.allocate(4).putInt(8).array(); for (byte t : bytes) { System.out.format("0x%x ", t); } In addition, do you know what arrays look like in memory ?
September 18, 2013
by Ryan Wang
· 71,552 Views · 2 Likes
article thumbnail
A Painless Introduction to Java's ThreadLocal Storage
Let’s look at some best practices for using another powerful class: ThreadLocal from java.lang, which is also implemented using WeakReference.
September 16, 2013
by Patson Luk
· 134,900 Views · 3 Likes
article thumbnail
Lambda Links and the Search for Final Closure (Java 8 and Scala)
Java 8 lambda walkthrough | Java Code Geeks Java 8 Lambdas – The missing link to moving away from Java – all that jazz Guava Functions & Java 8 Lambdas | Java Code Geeks Futures in Akka with Scala | Java Code Geeks Java 8, Lambdas | zeroturnaround.com Ade Trenaman, Why Java 8 doesn’t rock my Scala Java 8 vs Scala: a Feature Comparison Why We Need Lambda Expressions in Java – Part 1 | Javalobby Love and hate for Java 8 – JavaWorld Mary Had a Little Lambda Project Lambda in Java SE 8 Lambda Jam 2013 Content on InfoQ Everything About Java 8 Enabling Microservice Architectures with Scala Functional Reactive Programming in the Netflix API
September 14, 2013
by Tim Spann DZone Core CORE
· 4,988 Views · 1 Like
article thumbnail
Top 10 Websites for Advanced-level Java Developers
this is my collection of websites for advanced level java developers. these websites provide news, answers to popular questions, interview questions, science lectures, etc. quality is the key factor of good websites. in my opinion, they all have the highest quality. in the following, i will also share how i use these websites for learning or for fun. 1. stackoverflow.com stackoverflow.com is probably the most popular website in the programming world. there are millions of good questions and answers. learning an api or a programming language often rely on code examples, stackoverflow has a lot of code segments. another good thing about stackoverflow is that it is social. you can view questions under some certain tags, e.g. “java” and “regex”, then you can see what question is most frequently asked and most voted. this can serve as a good resource for learning, also a good resource to write popular topics of java bloggers. url: http://stackoverflow.com/ 2. dzone.com i would say this website is fun, lots of developers share their blog articles. it is like an adventure, you never know what you are going to read next from this site. url: http://www.dzone.com 3. leetcode.com if interview question is java specific, like “what array look like in memory in java”, you can get answers from java websites. however, if the question is something like “how to convert an sorted array to a balanced tree”, then leetcode is the right place to go. it is a social platform for preparing it technical interviews and contains a collection of algorithm related questions. the best part is that it also has an online judge which can check if your code is correct or not by feeding different size of data. to be successful in a technical interview, they believe it is mainly repeating these three important steps: code → read → discuss. url: http://leetcode.com/ 4. java se technical documentation this website contains all documents you will need to use api of java se. even if you are an advanced level java developer, i’m pretty sure that you will find something useful and official here. for example, you can read some tutorials of “essential java classes”, “deployment”, etc. url: http://docs.oracle.com/javase/ 5. github you probably know that you can host your projects free there, but you may not know it is an excellent resource for learning java libraries and frameworks. for instance, if you want to learn spring mvc framework, you can search and find some open source projects. as the “monkey see monkey do” rule works for learning frameworks, you will be able to learn the frameworks quickly by examples, especially you are an experienced developers. url: https://github.com/ 6. coursera this is the best site for video lectures. you can find a lot of good computer science courses from famous professors of top schools. some of them are even the inventor of some computer science areas. url: https://www.coursera.org/ 7. java world this site contains a large collection of java tutorials on various kinds of topics. a lot of articles are well written and has pictures/diagram for illustrations. it can be used as a book for deep learning. url: http://www.javaworld.com/ 8. ibm developerworks it has a lot of nice articles wrtten by ibm people. url: http://www.ibm.com/developerworks/java/ 9. wikipedia this is one of the best resources for looking up and learning almost any concepts. for example, as an experienced java developer you may just want to know some concept, but not learn much. this is a great place to find updated information for free. for example, what is service-oriented programming . url: http://en.wikipedia.org/wiki/ 10. program creek comparing with the above 9 websites, the size of programcreek.com is much smaller. but the good thing about it is that it is a well-written site that can provide some fun to read. you can find some topics that haven’t been written by any other websites, and each of the articles always contains nice diagram or code examples. it contains articles written by people from different areas (research, industry) and it is always updated and share all good-quality stuff for java developers. url: http://www.programcreek.com/
September 12, 2013
by Ryan Wang
· 173,342 Views · 8 Likes
article thumbnail
Top 10 Books for Advanced-level Java Developers
Java is a very popular programming language. Here are the top 10 books for advanced Java developers.
September 5, 2013
by Ryan Wang
· 142,493 Views · 1 Like
article thumbnail
Weblogic Thread Monitoring Tips
If you are working as a middleware administrator or application support individual, you may have realized by now how crucial it is to have proper knowledge of the JVM along with a good understanding of the Java concurrency principles (yes you have to learn how to analyze thread dumps). There is one principle I’m sure about: it is never too late to improve our knowledge and troubleshooting skills. Reaching a skill “plateau” is quite common and typically not due to our ability to learn but because of our fear and lack of willingness to embrace the challenges. One of such challenges is possibly your ability to understand and assess the health of the JVM & middleware threads of the Java EE container you are responsible for such as Oracle Weblogic Server. If this is your situation then this post is for you. Question: How can you monitor the JVM threads in an efficient manner using the Weblogic admin console? Also, please elaborate how you can differentiate between healthy threads vs. slow running threads. Finally, what other tools can help you achieve this task? Answer: Please note that Weblogic Server 10.3.5 was used for the following example. Oracle Weblogic Server is always installed with an admin console that provides you with out-of-the-box monitoring functions of the various Java EE resources exposed via the JMX API. Weblogic threads (created and assigned by the WLS kernel to the default self-tuning thread pool) are also fully exposed. This monitoring page allows you to: Monitor the full list of all Java threads under Weblogic control. Correlate any slow running thread with your application, request and assigned Work Manager, if any. Generate a JVM Thread Dump of the Weblogic managed server directly from the page via the Dump Thread Stacks button. Thread states - summary view This section provides a summary of all different Weblogic threads and states. Thread states - detailed view The detailed view is much more interesting. This is where you will be spending most of your analysis time. Make sure that you add all proper columns including the associated Work Manager, application name etc. The live Weblogic thread monitoring analysis process I usually follow is as per below. This approach is very useful for production environments when you are trying to determine the source of a performance slowdown or just to give you an idea of the health of the Weblogic threads. Refresh the page every 3-5 seconds. In between the refresh actions, identify the threads that are still executing the same request (slow running threads). This can be determined if you see the same Weblogic thread “Name” executing the same “Current Request” with the same “Total requests” value. Other criteria’s would be if Weblogic “promote” the affected thread(s) to Hogger or STUCK. Continue until you are done with your monitoring activity. As soon as one or a few slow running threads are found, identify the affected request(s) and application(s). Immediately after, generate a JVM Thread Dump using the Dump Thread Stacks button and copy/paste the output to a text editor for live or future analysis. I also recommend that you use other tools to monitor the JVM and threads such as JVisualVM. JVisualVM will give a full view of all the threads, including GC related threads. It will also allow you to monitor the Java heap and correlate any finding with the health of the activity of the garbage collector. Finally, if you suspect that you are dealing with a deeper thread concurrency problem such as thread lock contention or Java-level deadlock, you will need to generate a native thread dump (JVisualVM, kill -3 PID, jstack etc.) which will allow you to review the different monitor locks and locked ownable synchronizers.
September 3, 2013
by Pierre - Hugues Charbonneau
· 24,411 Views
article thumbnail
When Reading Excel with POI, Beware of Floating Points
Our problem began when we tried to read a certain cell that contained the value 929 as a numeric field and store it into an integer.
August 30, 2013
by Lieven Doclo
· 48,099 Views · 1 Like
article thumbnail
What is an Inner Interface in Java?
inner interface is also called nested interface, which means declare an interface inside of another interface. for example, the entry interface is declared in the map interface. public interface map { interface entry{ int getkey(); } void clear(); } why use inner interface? there are several compelling reasons for using inner interface: it is a way of logically grouping interfaces that are only used in one place. it increases encapsulation. nested interfaces can lead to more readable and maintainable code. one example of inner interface used in java standard library is java.util.map and java.util.map.entry. here java.util.map is used also as a namespace. entry does not belong to the global scope, which means there are many other entities that are entries and are not necessary map’s entries. this indicates that entry represents entries related to the map. how inner interface works? to figure out how inner interface works, we can compare it with nested classes. nested classes can be considered as a regular method declared in outer class. since a method can be declared as static or non-static, similarly nested classes can be static and non-static. static class is like a static method, it can only access outer class members through objects. non-static class can access any member of the outer class. because an interface can not be instantiated, the inner interface only makes sense if it is static. therefore, by default inter interface is static, no matter you manually add static or not. a simple example of inner interface? map.java public interface map { interface entry{ int getkey(); } void clear(); } mapimpl.java public class mapimpl implements map { class implentry implements map.entry{ public int getkey() { return 0; } } @override public void clear() { //clear } }
August 28, 2013
by Ryan Wang
· 23,264 Views · 2 Likes
article thumbnail
Spring Security 3.2.0 RC1 Highlights: Security Headers
This post was originally authored by Rob Winch from SpringSource. This is my last post in a two part series on Spring Security 3.2.0.RC1. My previous post discussed Spring Security's CSRF protection. In this post we will discuss how to use Spring Security to add various response headers to help secure your application. SECURITY HEADERS Many of the new Spring Security features in 3.2.0.RC1 are implemented by adding headers to the response. The foundation for these features came from hard work from Marten Deinum. If the name sounds familiar, it may because one of his 10K+ posts on the Spring Forums has helped you out. If you are using XML configuration, you can add all of the default headers using Spring Security's element with no child elements to add all the default headers to the response: ... If you are using Spring Security's Java configuration, all of the default security headers are added by default. They can be disabled using the Java configuration below: @EnableWebSecurity @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers().disable() ...; } } The remainder of this post will discuss each of the default headers in more detail: Cache Control Content Type Options HTTP Strict Transport Security X-Frame-Options X-XSS-PROTECTION Cache Control In the past Spring Security required you to provide your own cache control for your web application. This seemed reasonable at the time, but browser caches have evolved to include caches for secure connections as well. This means that a user may view an authenticated page, log out, and then a malicious user can use the browser history to view the cached page. To help mitigate this Spring Security has added cache control support which will insert the following headers into you response. Cache-Control: no-cache, no-store, max-age=0, must-revalidate Pragma: no-cache Simply adding the element with no child elements will automatically add Cache Control and quite a few other protections. However, if you only want cache control, you can enable this feature using Spring Security's XML namespace with the element. ... Similarly, you can enable only cache control within Java Configuration with the following: @EnableWebSecurity @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers() .cacheControl() .and() ...; } } If you actually want to cache specific responses, your application can selectively invokeHttpServletResponse.setHeader(String,String) to override the header set by Spring Security. This is useful to ensure things like CSS, JavaScript, and images are properly cached. When using Spring Web MVC, this is typically done within your configuration. For example, the following configuration will ensure that the cache headers are set for all of your resources: @EnableWebMvc public class WebMvcConfiguration extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry .addResourceHandler("/resources/**") .addResourceLocations("/resources/") .setCachePeriod(31556926); } // ... } Content Type Options Uploading Files There are many additional things one should do (i.e. only display the document in a distinct domain, ensure Content-Type header is set, sanitize the document, etc) when allowing content to be uploaded. However, these measures are out of the scope of what Spring Security provides. It is also important to point out when disabling content sniffing, you must specify the content type in order for things to work properly. Historically browsers, including Internet Explorer, would try to guess the content type of a request using content sniffing. This allowed browsers to improve the user experience by guessing the content type on resources that had not specified the content type. For example, if a browser encountered a JavaScript file that did not have the content type specified, it would be able to guess the content type and then execute it. The problem with content sniffing is that this allowed malicious users to use polyglots (i.e. a file that is valid as multiple content types) to execute XSS attacks. For example, some sites may allow users to submit a valid postscript document to a website and view it. A malicious user might create a postscript document that is also a valid JavaScript file and execute a XSS attack with it. Content sniffing can be disabled by adding the following header to our response: X-Content-Type-Options: nosniff Just as with the cache control element, the nosniff directive is added by default when using the element with no child elements. However, if you want more control over which headers are added you can use the element as shown below: ... The X-Content-Type-Options header is added by default with Spring Security Java configuration. If you want more control over the headers, you can explicitly specify the content type options with the following: @EnableWebSecurity @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers() .contentTypeOptions() .and() ...; } } HTTP Strict Transport Security (HSTS) When you type in your bank's website, do you enter mybank.example.com or do you enter https://mybank.example.com? If you omit the https protocol, you are potentially vulnerable toMan in the Middle attacks. Even if the website performs a redirect to https://mybank.example.com a malicious user could intercept the initial HTTP request and manipulate the response (i.e. redirect to https://mibank.example.com and steal their credentials). Many users omit the https protocol and this is why HTTP Strict Transport Security (HSTS)was created. Once mybank.example.com is added as a HSTS host, a browser can know ahead of time that any request to mybank.example.com should be interpreted as https://mybank.example.com. This greatly reduces the possibility of a Man in the Middle attack occurring. HSTS Notes In accordance with RFC6797, the HSTS header is only injected into HTTPS responses. In order for the browser to acknowledge the header, the browser must first trust the CA that signed the SSL certificate used to make the connection (not just the SSL certificate). One way for a site to be marked as a HSTS host is to have the host preloaded into the browser. Another is to add the "Strict-Transport-Security" header to the response. For example the following would instruct the browser to treat the domain as an HSTS host for a year (there are approximately 31536000 seconds in a year): Strict-Transport-Security: max-age=31536000 ; includeSubDomains The optional includeSubDomains directive instructs Spring Security that subdomains (i.e. secure.mybank.example.com) should also be treated as an HSTS domain. As with the other headers, Spring Security adds the previous header to the response when the element is specified with no child elements. It is also automatically added when you are using Java Configuration. You can also only use HSTS headers with the element as shown below: ... Similarly, you can enable only HSTS headers with Java Configuration: @EnableWebSecurity @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers() .hsts() .and() ...; } } X-Frame-Options Content Security Policy Another modern approach to dealing with clickjacking is using a Content Security Policy. Spring Security does not provide support for this as the specification is not released and it is quite a bit more complicated. To stay up to date with this issue and to see how you can implement it with Spring Security refer to SEC-2117 Allowing your website to be added to a frame can be a security issue. For example, using clever CSS styling users could be tricked into clicking on something that they were not intending (video demo). For example, a user that is logged into their bank might click a button that grants access to other users. This sort of attack is known asClickjacking. There are a number ways to mitigate clickjacking attacks. For example, to protect legacy browsers from clickjacking attacks you can use frame breaking code. While not perfect, the frame breaking code is the best you can do for the legacy browsers. A more modern approach to address clickjacking is to use X-Frame-Options header: X-Frame-Options: DENY The X-Frame-Options response header instructs the browser to prevent any site with this header in the response from being rendered within a frame. As with the other response headers, this is automatically included when the element is specified with no child elements. You can also explicitly specify the element to control which headers are added to the response. ... Similarly, you can enable only frame options within Java Configuration with the following: @EnableWebSecurity @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers() .frameOptions() .and() ...; } } X-XSS-Protection Some browsers have built in support for filtering out reflected XSS attacks. This is by no means full proof, but does assist in XSS protection. The filtering is typically enabled by default, so adding the header typically just ensures it is enabled and instructs the browser what to do when a XSS attack is detected. For example, the filter might try to change the content in the least invasive way to still render everything. At times, this type of replacement can become a XSS vulnerability in itself. Instead, it is best to block the content rather than attempt to fix it. To do this we can add the following header: X-XSS-Protection: 1; mode=block This header is included by default when the element is specified with no child elements. We can explicitly state it using the element as shown below: ... Similarly, you can enable only xss protection within Java Configuration with the following: @EnableWebSecurity @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers() .xssProtection() .and() ...; } } FEEDBACK PLEASE If you encounter a bug, have an idea for improvement, etc please do not hesitate to bring it up! We want to hear your thoughts so we can ensure we get it right before the code is generally available. Trying out new features early is a good and simple way to give back to the community. This also ensures that the features you want are present and working as you think they should. Please log any issues or feature requests to the Spring Security JIRA. After logging a JIRA, we encourage (but do not require) you to submit your changes in a pull request. You can read more about how to do this in the Contributor Guidelines If you have questions on how to do something, please use the Spring Security forums orStack Overflow with the tag spring-security (I will be monitoring them closely). If you have specific comments questions about this blog, feel free to leave a comment. Using the appropriate tools will help make it easier for everyone. CONCLUSION You should have a good understanding of the new features present in Spring Security 3.2.RC1.
August 26, 2013
by Pieter Humphrey
· 17,116 Views
article thumbnail
How to Configure SLF4J with Different Logger Implementations
There are many good benefits in using slf4j library as your Java application logging API layer. Here I will show few examples on how to use and configure it.
August 21, 2013
by Zemian Deng
· 253,802 Views · 11 Likes
article thumbnail
Optional in Java 8 Cheat Sheet
java.util.Optional in Java 8 is a poor cousin of scala.Option[T] and Data.Maybe in Haskell. But this doesn’t mean it’s not useful.
August 19, 2013
by Tomasz Nurkiewicz
· 74,240 Views · 7 Likes
article thumbnail
Destroy Cookie while Logging out.
I was facing a problem where while a person logs out his session is invalidated but the JSESSIONID still remained in the browser. As a result while logging in the Java API used to get the request from the browser along with a JSESSIONID(Just the ID since the session was invalidated) and would create the new session with the same ID. To fix this problem I used the above code so that whenever a user logs out the entire JSESSIONID becomes empty and thus cookie wont exist for that site.Anyone using JAVA can utilize this in their code. @RequestMapping(value = "/logout", method = RequestMethod.POST) public void logout(HttpServletRequest request, HttpServletResponse response) { /* Getting session and then invalidating it */ HttpSession session = request.getSession(false); if (request.isRequestedSessionIdValid() && session != null) { session.invalidate(); } handleLogOutResponse(response); } /** * This method would edit the cookie information and make JSESSIONID empty * while responding to logout. This would further help in order to. This would help * to avoid same cookie ID each time a person logs in * @param response */ private void handleLogOutResponse(HttpServletResponse response) { Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { cookie.setMaxAge(0); cookie.setValue(null); cookie.setPath("/"); response.addCookie(cookie); } }
August 15, 2013
by Shiv Kumar Ganesh
· 41,370 Views · 2 Likes
article thumbnail
AspectJ with Akka and Scala
Imagine that you need to find out how your actors are performing, but without using the Typesafe Console. (You don’t actually want to use this code in production, but it is an interesting project to learn.) What we are interested in is intercepting the receiveMessage call of the ActorCell class. A Short Introduction to AOP We could roll our own build of Akka, but that is not a good idea. Instead, we would like to somehow modify the bytecode of the existing Akka JARs to include our instrumentation code. It turns out that we can use aspect oriented programming to implement cross-cutting concerns in our code. Cross-cutting concerns are pieces of code that cut across the object hierarchy; in other words, we inject the same functionality to different levels of our class structure. In OOP, the only way to share functionality is with inheritance. I will explain the simplest case here, but the same rules apply to mix-in inheritance. If I have: class A { def foo: Int = 42 } class B { def bar: Int = 42 } class AA extends A class BB extends B Then the only way to share the implementation of foo is to extend A; the only way to share the implementation of bar is to extend B. Suppose we now want to measure how many times we call foo on all subtypes of A and bar, but only in subtypes of BB. This now turns out to be rather clumsy. Even if all we do is println("Executing foo") or println("Executing bar"), we have a lot of duplication on our hands. Instead, we would like to write something like this: before executing A.foo { println("Executing foo") } before executing BB.bar { println("Executing bar") } And have some machinery apply this to the classes that make up our system. Importantly, we would like this logic to be applied to every subtype of A and every subtype of BB, even if we only have their compiled forms in a JAR. Enter AspectJ And this is exactly what AspectJ does. It allows us to define these cross-cutting concerns and to weave them into our classes. The weaving can be done at compile time, or even at class load time. In other words, the AspectJ weaver can modify the classes with our cross-cutting concerns as the JVM loads them. The technical details now involve translating our before executing pseudo-syntax into the syntax that AspectJ can use. We are going to be particularly lazy and use AspectJ’s Java syntax. package monitor; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanRegistrationException; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; @Aspect public class MonitorAspect { @Pointcut( value = "execution (* akka.actor.ActorCell.receiveMessage(..))" + "&& args(msg)", argNames = "msg") public void receiveMessagePointcut(Object msg) {} @Before(value = "receiveMessagePointcut(msg)", argNames = "jp,msg") public void message(JoinPoint jp, Object msg) { // log the message System.out.println("Message " + msg); } } The annotations come from the AspectJ dependencies, which, in SBT syntax are just: "org.aspectj" % "aspectjweaver" % "1.7.2", "org.aspectj" % "aspectjrt" % "1.7.2" Excellent. We have defined a pointcut, which you can imagine as a target in the structure of our system. In this particular case, the pointcut says on execution of the receiveMessage method in akka.actor...ActorCell class, with any parameters of any type (..), returning any type * as long as the argument is called msg and inferred to be of the type Object. Without an advice though, a pointcut would be useless–just like having a method that is never called. An advice applies our logic at the point identified by the pointcut. Here, we have the message advice, which runs on execution of the methods matched by the receiveMssagePointcut. At the moment, it does nothing of importance. To see this in action, we need to tell the JVM to use the AspectJ weaver. We do so by specifying the Java agent, which registers a Java Instrumentation implementation, which performs the class file transformation. However, this transformation is costly. Imagine if we had to re-compile every class as it is loaded. To restrict the scope of the transformations, the AspectJ load-time weaver loads an XML file (boo, hiss, I know) from META-INF/aop.xml, which includes its settings. Now, to get it all running all you need to do is include javaagent:~/path-to/aspectjweaver.jar when we start the JVM. Measuring Now that we have our monitor.MonitoringAspect and META-INF/aop.xml ready, all we need to do is implement the logic that records the messages and prints out their per-second averages. I will leave it to the curious reader to come up with a much better approach, but here is one that works, albeit in a very naive way: package monitor; import java.util.HashMap; import java.util.Map; class ActorSystemMessages { private final Map messages = new HashMap<>(); void recordMessage() { long second = System.currentTimeMillis() / 1000; int count = 0; if (messages.containsKey(second)) { count = messages.get(second); } messages.put(second, ++count); } float average() { if (messages.isEmpty()) return 0; int total = 0; for (Integer i : messages.values()) { total += i; } return total / messages.size(); } } We can now use it in our MonitorAspect: @Aspect public class MonitorAspect { private ActorSystemMessages asm = new ActorSystemMessages(); @Pointcut( value = "execution (* akka.actor.ActorCell.receiveMessage(..)) " + "&& args(msg)", argNames = "msg") public void receiveMessagePointcut(Object msg) {} @Before(value = "receiveMessagePointcut(msg)", argNames = "jp,msg") public void message(JoinPoint jp, Object msg) { asm.recordMessage(); System.out.println("Average throughput " + asm.average()); } } Bringing in an Actor Let's see it all run. We will make a simple actor. This time, we will use the Actor DSL. We are not interested that much in its behavior, but we want to see messages being sent around. So, we construct a simple App subclass with two actors. One that sends the messages around and one that prints any message it receives. import akka.actor.{ActorRef, ActorSystem} object Main extends App { import akka.actor.ActorDSL._ import Commands._ implicit val system = ActorSystem() val chatter = actor(new Act { become { case i: Int => self ! (sender, i) case (sender: ActorRef, i: Int) => if (i > 0) self ! (sender, i - 1) else sender ! "zero" } }) implicit val _ = actor(new Act { become { case x => println(">>> " + x) } }) def commandLoop(): Unit = { readLine() match { case CountdownCommand(count) => chatter ! count.toInt case QuitCommand => return } commandLoop() } commandLoop() system.shutdown() } object Commands { val CountdownCommand = """(\d+)""".r val QuitCommand = "quit" } The chatter actor, as you can see, receives the number of messages to be crunched. It then sends a message to itself as a tuple containing the original sender and the number of messages, which will continue to decrease until we hit 0, when we send the "zero"String back to the original sender. As an interesting aside, we have the tail-recursive commandLoop() function that deals with the input that the users type in. Running the Example If you run the example without specifying the -javaagent JVM parameter, the aspect will not be weaved in; consequently, no bytecode will be modified and our logging will not work. Because your IDEs are different, the only reliable way is to run it in SBT. And so, execute sbt run, enter the number of messages and see them displayed. Note that I’m setting the javaOptions, fork and connectInput. The javaOptions is obvious since that’s how I specify the -javaagent parameter and fork makes SBT fork the java process so that the javaOptions takes effect. Finally, the connectInput parameter connects the System.in to the console’s STDIN. (We must do this because we use readLine() in our app.) JMX Now, I don’t like println in the best of the times, and System.out.println is even worse. So, the last modification is to add JMX exporter and to expose the ActorSystemPerformance MBean. The rather baroque JMX code is: public interface ActorSystemPerformanceMXBean { float getMessagesPerSecond(); } public class ActorSystemPerformanceMXBeanImpl implements ActorSystemPerformanceMXBean{ private ActorSystemMessages messages; ActorSystemPerformanceMXBeanImpl(ActorSystemMessages messages) { this.messages = messages; } @Override public float getMessagesPerSecond() { return this.messages.average(); } } public class JMXEndpoint { public static void start(ActorSystemMessages messages) throws ... { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("monitor:type=Performance"); ActorSystemPerformanceMXBeanImpl mbean = new ActorSystemPerformanceMXBeanImpl(messages); mbs.registerMBean(mbean, name); } } With this in place, we can remove the System.out.println and call the JMXEndpoint.start) method in the aspect’s constructor, giving us: @Aspect public class MonitorAspect { final ActorSystemMessages messages; public MonitorAspect() throws ... { this.messages = new ActorSystemMessages(); JMXEndpoint.start(messages); } @Pointcut(...) public void receiveMessagePointcut(Object msg) {} @Before(...) public void message(JoinPoint jp, Object msg) { messages.recordMessage(); } } Run the application using sbt run again, connect to the JMX MBean using jconsole and see the wonders: Summary This article is a simple exploration of AOP (as implemented in AspectJ) and its use in Scala and Akka. The implementation is very simplistic. If you use it in production, I will endorse you for Enterprise PHP on LinkedIn. However, it is an interesting exercise and really shows how Scala fits well into even the slightly more esoteric Java libraries. The source code for your compiling pleasure is at https//github.com/eigengo/activator-akka-aspectj.
August 8, 2013
by Jan Machacek
· 9,735 Views
  • Previous
  • ...
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×