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 Popular Topics

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,603 Views · 16 Likes
article thumbnail
A Better Way of Using ASP.NET SignalR With Angular JS
A few days back, I blogged on using SignalR and Angular JS together and on Implementing SignalR stock ticker sample using Angular JS(Part 1 and Part 2). In those posts, I have used the traditional call-back model to call the functions defined in controller to modify data whenever an update is received from the server. One of the readers sent me feedback saying that we have a better way to use SignalR and Angular JS together. The way to go is using event methods defined on $rootscope object. This approach is based on publishing and subscribing events. As events can be published from anywhere and subscribed from anywhere, the source and destination will remain completely unaware of each other. Both of them have to depend on just one object, $rootScope. Official documentation on scope contains details on each method defined on $rootScope. We will be using the following methods for publishing and subscribing the events: $emit(name, args): Publishes an event with specified name with given arguments $on(name, listener): Subscribes to an event with specified name. Listener is a function containing logic to be executed once the event has occurred To manage SignalR’s client functionality, it is better to create a service, as services are singletons. There will be only one instance of the service in entire application. This behaviour of services makes it possible to have multiple SignalR client pages in the applications and they can be kept in sync without putting any extra amount of effort. Let’s modify the example discussed in the post titled Hooking up ASP.NET SignalR with Angular JS to use event model. Server hub, references and structure of the HTML page remains the same as past. The only components to be modified are Controller and Service. Service carries the responsibility to initialize a connection to the hub and call the SignalR’s server methods. Once a response is received from the server, we will broadcast an event from the service with data received. app.service('signalRSvc', function ($, $rootScope) { var proxy = null; var initialize = function () { //Getting the connection object connection = $.hubConnection(); //Creating proxy this.proxy = connection.createHubProxy('helloWorldHub'); //Starting connection connection.start(); //Publishing an event when server pushes a greeting message this.proxy.on('acceptGreet', function (message) { $rootScope.$emit("acceptGreet",message); }); }; var sendRequest = function () { //Invoking greetAll method defined in hub this.proxy.invoke('greetAll'); }; return { initialize: initialize, sendRequest: sendRequest }; }); To keep the things simple, I kept names of the server hub event and event rose using $emit the same. The names can be different. Let’s modify the controller to have a listener to the event raised by the service. Following is the implementation of the controller: function SignalRAngularCtrl($scope, signalRSvc, $rootScope) { $scope.text = ""; $scope.greetAll = function () { signalRSvc.sendRequest(); } updateGreetingMessage = function (text) { $scope.text = text; } signalRSvc.initialize(); //Updating greeting message after receiving a message through the event $scope.$parent.$on("acceptGreet", function (e,message) { $scope.$apply(function () { updateGreetingMessage(message) }); }); } Now open the modified page on multiple browsers and click the Greeting button randomly from all browsers. Messages printed on all browsers should be updated whenever the button is clicked. This behaviour is same as it was earlier. We just adopted a better approach to make it work. Happy coding!
September 20, 2013
by Rabi Kiran Srirangam
· 27,366 Views
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,451 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,631 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,984 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,254 Views · 8 Likes
article thumbnail
Groovy Goodness: Check if a String Only Contains Whitespaces
In Groovy we can check if a String value only contains whitespaces with the isAllWhitespace() method. The method checks for spaces, but also takes into account tab and newline characters as whitespace. assert ''.allWhitespace assert ' '.allWhitespace assert '\t '.allWhitespace assert ' \r\n '.allWhitespace assert !'mrhaki'.allWhitespace
September 12, 2013
by Hubert Klein Ikkink
· 12,937 Views
article thumbnail
Groovy Goodness: Replace Characters in a String with CollectReplacements
We can use the collectReplacements(Closure) method to replace characters in a String. We pass a closure to the method and the closure is invoked for each character in the String value. If we return null the character is not transformed, otherwise we can return the replacement character. def s = 'Gr00vy is gr8' def replacement = { // Change 8 to eat if (it == '8') { 'eat' // Change 0 to o } else if (it == '0') { 'o' // Do not transform } else { null } } assert s.collectReplacements(replacement) == 'Groovy is great'Code written with Groovy 2.1.6
September 11, 2013
by Hubert Klein Ikkink
· 10,201 Views
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,394 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,347 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,035 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,209 Views · 2 Likes
article thumbnail
How to create a JQuery DataTable using JSON and Servlet
in this article i’ll introduce the basic coding that require to create jquery datatable using json passed by simple servlet. datatable is very powerful jquery based grid with advance features which can be build in short span of time with customize features. installation 1. download latest jquery datatable download 2. above download will provide two jquery plugin jquery.js and querytables.js 3. default stylesheet which shipped with latest datatable download package note: you can download full source code from github link creating the datatable we can write below code to create the basic datatable with data feedsummary.jsp ========================== $(document).ready will ready to execute the javascript and var otable = $(‘#tableid’).datatable says that write datatable on tableid place. datatables will adding sorting, filtering, paging and information to your table by default, providing the end user of your web-site with the ability to control the display of the table and find the information that they want from it as quickly as possible. the pointer tableid and column name will be defined in table tag as below feedsummary.jsp ===================== first namelast nameaddress 1address 2 above datatable code invoke feedservlet which will return json string as defined below feedservlet.java =============== protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { printwriter out = response.getwriter(); string json = "{ \"demo\":[[\"first name\",\"last name\","+ +\"address1\",\"address2\"],[\"first name\",\"last name\",\"address1\",\"address2\"]]}"; out.println(json); } now either we can use servlet annotation or web.xml as below to register above feedservlet web.xml ========= feedservlet feedservlet feedservlet feedservlet /feedservlet running incorporate the above point and deploy with server to view the result as follows: http://localhost:8080/exampledatatablejson/feedsummary.jsp jquery datatable image conclusion you can download full source code from github link and most welcome to fork or update the same. references: http://datatables.net/examples/
August 27, 2013
by Nitin Kumar
· 90,199 Views · 1 Like
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,046 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,689 Views · 11 Likes
article thumbnail
Remove Characters at the Start and End of a String in PHP
In a previous article about how you can remove whitesapce from a string, I spoke about using the functions ltrim() and rtrim(). These work by passing in a string to remove whitespace. Using the ltrim() function will remove the whitespace from the start of the string, using the rtrim() function will remove the whitespace from the end of the string. But you can also use these functions to remove characters from a string. These functions take a second parameter that allows you to specify what characters to remove. // This will search for the word start at the beginning of the string and remove it ltrim($string, 'start'); // This will search for the word end at the end of the string and remove it rtrim($string, 'end'); Remove Trailing Slashes From a String A common use for this functionality is to remove the trailing slash from a URL. Below is a code snippet that allows you to easily do this using the rtrim() function. function remove_trailing_slashes( $url ) { return rtrim($url, '/'); } A common use for the ltrim() function is to remove the "http://" from a URL. Use the function below to remove both "http" and "https" from a URL: function remove_http( $url ) { $url = ltrim($url, 'http://'); $url = ltrim($url, 'https://'); return $url; }
August 20, 2013
by Paul Underwood
· 41,662 Views
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,121 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,330 Views · 2 Likes
article thumbnail
Implementing a SignalR Stock Ticker Using AngularJS: Part1
In my last post, we saw how to use ASP.NET SignalR and AngularJS together using a "Hello World" type of example. Now that we have some idea of how to use both technologies together, we will take a look at a more advanced scenario in order to make the frameworks work better together. I assume that you have already seen the SignalR Stock ticker sample. If not, download it from GitHub or add the NuGet Package to an existing ASP.NET web application. Make sure that you take some time to run the sample at least once on multiple browsers and have a glance at the code before you proceed any further. I hope you had a look at the code on both the server and the client side of the stock ticker sample. We will not make any modification to the server code and the layout of the page, but we will rewrite the JavaScript part using features of AngularJS. Since there is a lot of client-side code to convert, let’s do it in a two-part series: Creating a custom service to communicate with the hub on the server and using the service in a controller (this post) Performing UI changes on the page, like enabling/disabling buttons, scrolling stock values in a list, and adding animation effect to values in a table and list (next post) Make a copy of the StockTicker.html file and give it a name of your choice. Add two JavaScript files, controller.js and factory.js, to the project. We will add script to these files soon. Modify the script reference section of the page to include the following script files: Let’s start implementing the SignalR part inside a custom service. To keep the controller free from doing anything other than providing data to the view and handling view events, we are creating a custom service to handle the hub communication logic. The service is responsible for: Creating objects needed for communication Configuring client functions to proxy and to respond when a market is opened, closed, or reset, or when a stock value is updated Starting a hub connection Getting the current values of stocks and the current market statuses of the stocks once the connection is started Opening, closing or resetting markets on demand Following is the module and the factory that handles the functionality mentioned above: var app = angular.module('app', []); app.value('$', $); app.factory('stockTickerData', ['$', '$rootScope', function ($, $rootScope) { function stockTickerOperations() { //Objects needed for SignalR var connection; var proxy; //To set values to fields in the controller var setMarketState; var setValues; var updateStocks; //This function will be called by controller to set callback functions var setCallbacks = function (setMarketStateCallback, setValuesCallback, updateStocksCallback) { setMarketState = setMarketStateCallback; setValues = setValuesCallback; updateStocks = updateStocksCallback; }; var initializeClient = function () { //Creating connection and proxy objects connection = $.hubConnection(); proxy = connection.createHubProxy('stockTicker'); configureProxyClientFunctions(); start(); }; var configureProxyClientFunctions = function () { proxy.on('marketOpened', function () { //set market state as open $rootScope.$apply(setMarketState(true)); }); proxy.on('marketClosed', function () { //set market state as closed $rootScope.$apply(setMarketState(false)); }); proxy.on('marketReset', function () { //Reset stock values initializeStockMarket(); }); proxy.on('updateStockPrice', function (stock) { $rootScope.$apply(updateStocks(stock)); }); }; var initializeStockMarket = function () { //Getting values of stocks from the hub and setting it to controllers field proxy.invoke('getAllStocks').done(function (data) { $rootScope.$apply(setValues(data)); }).pipe(function () { //Setting market state to field in controller based on the current state proxy.invoke('getMarketState').done(function (state) { if (state == 'Open') $rootScope.$apply(setMarketState(true)); else $rootScope.$apply(setMarketState(false)); }); }); }; var start = function () { //Starting the connection and initializing market connection.start().pipe(function () { initializeStockMarket(); }); }; var openMarket = function () { proxy.invoke('openMarket'); }; var closeMarket = function () { proxy.invoke('closeMarket'); }; var reset = function () { proxy.invoke('reset'); }; return { initializeClient: initializeClient, openMarket: openMarket, closeMarket: closeMarket, reset: reset, setCallbacks: setCallbacks } }; return stockTickerOperations; } ]); We need a controller to start the work. The controller will have the following components: An array to store the current stock values and a Boolean value to store the current market state Setters to assign values to the fields A function to modify the value of an entry in the stocks array Functions to handle open, close and reset operations when the corresponding button is clicked Set callbacks to the service and ask the service to kick off the communication Following is the code in the controller: var StockTickerCtrl = function ($scope, stockTickerData) { $scope.stocks = []; $scope.marketIsOpen = false; $scope.openMarket = function () { ops.openMarket(); } $scope.closeMarket = function () { ops.closeMarket(); } $scope.reset = function () { ops.reset(); } function assignStocks(stocks) { $scope.stocks = stocks; } function replaceStock(stock) { for (var count = 0; count < $scope.stocks.length; count++) { if ($scope.stocks[count].Symbol == stock.Symbol) { $scope.stocks[count] = stock; } } } function setMarketState(isOpen) { $scope.marketIsOpen = isOpen; } var ops = stockTickerData(); ops.setCallbacks(setMarketState, assignStocks, replaceStock); ops.initializeClient(); } The layout of the HTML page will remain unchanged. But we need to change the way data is rendered on the screen. The stock ticker sample uses a poor man’s template technique to render content in the table and in the scrolling list. Since we are using AngularJS, let’s replace it with expressions. Following is the mark-up on the page in Angular’s style: ASP.NET SignalR Stock Ticker Sample Live Stock Table SymbolPriceOpenHighLowChange% loading... {{stock.Symbol} {{stock.Price | number:2} {{stock.DayOpen | number:2} {{stock.DayHigh | number:2} {{stock.DayLow | number:2} {{stock.Change} {{stock.PercentChange} Live Stock Ticker loading... {{stock.Symbol} {{stock.Price | number:2}{{stock.Change} ({{stock.PercentChange}) Open this page on a browser and the original stock ticker page on another browser window and play with the buttons. You will see that both screens have the same data at any given point in time. The only difference would be the state of the buttons, their color and a scrolling list. We will fix them in the next post. Happy coding!
August 14, 2013
by Rabi Kiran Srirangam
· 16,979 Views
article thumbnail
Algorithm of the Week: Quicksort - Three-way vs. Dual-pivot
It’s no news that quicksort is considered one of the most important algorithms of the century and that it is the de facto system sort for many languages, including the Arrays.sort in Java. So, what’s new about quicksort? Well, nothing except that I just now figured out (two damn years after the release of Java 7) that the quicksort implementation of Arrays.sort has been replaced with a variant called dual-pivot quicksort. This thread is not only awesome for this reason but also how humble Jon Bentley and Joshua Bloch really are. What did I do then? Just like everybody else, I wanted to implement it and do some benchmarking against some 10 million integers (random and duplicate). Oddly enough, I found the following results: Random Data Basic quicksort: 1222 ms Three-way quicksort: 1295 ms (seriously!) Dual-pivot quicksort: 1066 ms Duplicate Data Basic quicksort: 378 ms Three-way quicksort: 15 ms Dual-pivot quicksort: six ms Stupid Question One I am afraid that I am missing something in the implementation of the three-way partition. Across several runs against random inputs (of 10 million numbers), I could see that the single pivot always performs better (although the difference is less than 100 milliseconds for 10 million numbers). I understand that the whole purpose of making the three-way quicksort the default quicksort until now is that it does not give 0(n2) performance on duplicate keys, which is very evident when I run it against duplicate inputs. But is it true that, for the sake of handling duplicate data, a small penalty is taken by the three-way quicksort? Or is my implementation bad? Stupid Question Two My dual-pivot implementation (link below) does not handle duplicates well. It takes forever (0(n2)) to execute. Is there a good way to avoid this? Referring to the Arrays.sort implementation, I figured out that ascending sequences and duplicates are eliminated well before the actual sorting is done. So, as a dirty fix, if the pivots are equal I fast-forward the lowerIndex until it is different than pivot2. Is this a fair implementation? else if (pivot1==pivot2){ while (pivot1==pivot2 && lowIndex=j) break; exchange(input, i, j); } exchange(input, pivotIndex, j); return j; } } Three-way package basics.sorting.quick; import static basics.shuffle.KnuthShuffle.shuffle; import static basics.sorting.utils.SortUtils.exchange; import static basics.sorting.utils.SortUtils.less; public class QuickSort3Way { public void sort (int[] input){ //input=shuffle(input); sort (input, 0, input.length-1); } public void sort(int[] input, int lowIndex, int highIndex) { if (highIndex<=lowIndex) return; int lt=lowIndex; int gt=highIndex; int i=lowIndex+1; int pivotIndex=lowIndex; int pivotValue=input[pivotIndex]; while (i<=gt){ if (less(input[i],pivotValue)){ exchange(input, i++, lt++); } else if (less (pivotValue, input[i])){ exchange(input, i, gt--); } else{ i++; } } sort (input, lowIndex, lt-1); sort (input, gt+1, highIndex); } } Dual-pivot package basics.sorting.quick; import static basics.shuffle.KnuthShuffle.shuffle; import static basics.sorting.utils.SortUtils.exchange; import static basics.sorting.utils.SortUtils.less; public class QuickSortDualPivot { public void sort (int[] input){ //input=shuffle(input); sort (input, 0, input.length-1); } private void sort(int[] input, int lowIndex, int highIndex) { if (highIndex<=lowIndex) return; int pivot1=input[lowIndex]; int pivot2=input[highIndex]; if (pivot1>pivot2){ exchange(input, lowIndex, highIndex); pivot1=input[lowIndex]; pivot2=input[highIndex]; //sort(input, lowIndex, highIndex); } else if (pivot1==pivot2){ while (pivot1==pivot2 && lowIndex
August 14, 2013
by Arun Manivannan
· 46,393 Views
  • Previous
  • ...
  • 536
  • 537
  • 538
  • 539
  • 540
  • 541
  • 542
  • 543
  • 544
  • 545
  • ...
  • 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
×