Skip to main content

Posts

Write a Java program to read console data using bufferedreader API

BufferedReader is a class which simplifies reading text from a character input stream. It buffers the characters in order to enable efficient reading of text data. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example, // BufferedReader in = new BufferedReader(new FileReader("foo.in")); will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream...

Absorbing Feedback

We all want to improve, absorbing feedback is the most important step in the process of improvement. Even when we get feedback, we don't know how to act on it. We have good techniques for giving feedback like SBI (Situation, Behavior, Impact) however, it took me some time to develop a good framework to absorb and act on feedback. Let me start with a real-life situation: A couple of years back, I received feedback, however incapable of acting on it. I was struggling to make any improvement. During this phase, I developed the framework which helped me.  This framework has two attributes " Understand Deeply" and "Act Swiftly".  Understand Deeply is about understanding the feedback and situations where behaviour is depicted so that you can relate to the situation. Some situations bring out the same undesired behaviour. It is also very important to understand the intent of the feedback.  Act Swiftly talks about acting on feedback, taking steps to ...

Grow faster by making yourself redundant!

Redundant ! but why? What about job security? Shouldn't we be consolidating our position instead of going redundant? All these questions are obvious when you read the title of this article. Don't worry, we are not talking about how to get yourself fired but opposite, how to grow faster by making yourself redundant in a role . In a job, we are expected to play roles that are needed from us e.g. program manager, project manager, people manager, technical lead are few roles engineering managers play to be successful. This article talks about how we can progressively outgrow in our current role and start learning (or mastering) the new roles. Transferring responsibilities to people you are managing are the best way of making space for learning something new. Over the past couple of years as an engineering manager, I have been following this philosophy to learn new things. Let's take an example of leading a project to understand this better. Engineering Managers are the b...

Engineering Leader: How to make a difference?

Being an engineering leader is not an easy task, especially when you are stepping into this role as a first-timer. Seldom you go through a training, however in most situations you are expected to figure it out yourself with little or no guidance. Often leadership demands you to play following roles: People Manager Product/Business knowledge Architect/Senior Developer Vision for technology I will be writing separate blogs to cover the first two roles. For a beginner, last two roles are very important to gain credibility of the team which is the most important factor in succeeding at your job. As a technical leader, you will be facing the challenges from all the directions like decision making, improving team efficiency and choosing the technology roadmap for your team. However, I hope adopting following patterns can help you sail through these challenges. Decision Making : When hit with the problem, as a techie you rely on your technical skills and often start suggestin...

Play framework 1.2.x excel export with I18n and custom filename

play-excel is a very well written plugin of Play-framework for exporting excel from java objects. I used this plugin for my requirement of generating the I18n supported xls with custom names. This blog will explain this in details so that I can use it later :). Line# 4: will basically make the play-excel to take the rendering functionality in play. (you can also use xlsx instead of "xls") Line# 5: Will set the exported filename to given name i.e. "downloadUsers.xls" Line# 6&7: pick up the template from views/ /users_ .xls. 2. public static void users() { 3. List users = User.findAll(); 4. request.format = " xls "; 5. renderArgs.put(" __FILE_NAME__ ", "downloadUsers.xls"); 6. String template = "users-" + Lang.get() + ".xls"; 7. renderTemplate (template, users); 8. } That's it you are done. Happy coding :).

Gear 2 and Gear 2 Neo working with Nexus 5

Gear 2 and Gear 2 Neo are working perfectly with Nexus 5. Please go to the following URL: http://forum.xda-developers.com/showthread.php?t=2677686 and download the " Galaxy Gear Manager " app on your phone. Launch the gear manager app and select your gear device and you are good to go. For receiving additional notifications, goto Gear Manager and select Notification item and select from the list of apps you want to receive notification from.

Simplest iterative algorithm Post order traversal

package com.test; import java.util.Stack; public class PostOrderTraversal { static class Node { int data ; Node left , right ; Node( int item ) { data = item ; left = right ; } } private void pfIterate(Node root ) { Node prev = null ; Stack stack = new Stack<>(); stack .push( root ); while (! stack .isEmpty()) { root = stack .pop(); if ( root . left == null && root . right == null ) { System. out .print( root . data + " " ); prev = root ; } else if ( prev == root . left || prev == root . right ) { System. out .print( root . data + " " ); prev = root ; } else { stack .push( root ); if ( root . right != null ) stack .push( root . right ); if ( root . left != null ) stack .push( root . left ); } } } public static void main(String[] args ) { // Let u...

How to inject multiple endpoint in SEI using Camel's @EndpointInject

By default you can inject annotation on single method of an interface like: public interface MyListener {   @EndpointInject(uri="activemq:foo.bar")     String sayHello(String name); } what if you need multiple methods like this with @EndpointInjection happening over them for each endpoint e.g.: public interface MyListener {   @EndpointInject(uri="direct:foo")     String sayHelloFoo(String name); @EndpointInject(uri="direct:bar")     String sayHelloBar(String name); } The simple solution i have working involved spring's FactoryBean implementation. It need following steps: <!-- Define route for which you need injection to happen --> <bean id="r" class="MyListener" /> <!-- Define producer template having that route  -->   <camelContext  xmlns="http://camel.apache.org/schema/spring">         <template id="producerTemp...

Use recipientList for dynamic routes

I was writing the route in which "to" endpoint was need to be configured dynamically with the URL coming in the body. I was trying to use simple expression language (e.g. ${in.header.test} where test is the property set in the in-message header) also with header method (e.g. header(test)). The routes for the same were: from("direct:test").to("${in.header.test}"); &  from("direct:test").to(header("test"));   after literally every thing i could have. I figured out recipientlist can do the trick e.g. from("direct:test").recipientList("${in.header.test}"); &  from("direct:test").recipientList(header("test")); Hope this works for you too.

Spring: implements interface not working in @Controller

Guys,  I had a @Controller in which I was trying to implement an interface. But i was getting the following error message: PageNotFound WARN  No mapping found for HTTP request with URI [/test/form] in DispatcherServlet with name 'Spring MVC Dispatcher Servlet' where "/test" (at class level) and "/form" (at method level) where my @RequestMapping args.  The issue is described at following link: http://forum.springsource.org/showthread.php?92303-Spring-Servlet-MVC-RequestMapping-breaks-with-AOP-Advice Now you may not find anything wrong with your spring.xml but should check all the xml used by used in the project in out case metrics was causing the problem.  The aop config was overridden by metrics here: https://github.com/ryantenney/metrics-spring#xml-config  By default JDK proxy are created using interface and if controller implements an interface the RequestMapping annotation gets ignored as the targetClass is not being using. http://static.spr...

60 days at expedia India

About to complete 60 days at Expedia, Gurgaon and till now the ride has been a rollercoaster. I joined Expedia hoping for challenging work, participating in building a good team and workplace full of amazing people. To be frank, everything is as close to reality as I imagined. The experience is amazing, people are awesome, the new office is great, the parties are crazy, but the most important thing is the freedom to express yourself and asking questions. And people around you listen (even leaders) and have enough patience to make you feel comfortable. Work-wise finishing user-stories (part of the onboarding process), building a team by interviewing the brightest mind in the industry and ideating about the new ideas to make it a better workplace and best technology platform. It's a great learning opportunity to contribute to one of the fastest-growing company's in the technology and travel industry. I hope this answers some of your initial questions about joining Expedia. Looki...

Java references in nutshell

Java developers struggle to use java references and i don't blame them. The topic seldom covered by text books and even code reviews rarely give emphasis on usage of references. Why the topic is important at all? and if everybody (atleast people i have come across) is coding without it why the hell you need it? Since you are reading this, either you are already aware of them or for the interview. Anyways, knowing references helps you manage memory better because you are able to define the behavior of the object when GC (garbage collector)  is run. Type of references: 1. Strong R eference : The normal reference in the java code is strong reference and the object referenced by strong reference is eligible for GC as soon as scope ends or reference started pointing to null in the code. E.g.  Person p = new Person();                 p = null; // will make object initialized...

CXF-RS adding custom response code

Following snippet show how to return the custom Response code as http response code while returning the response: import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; @Path("/") @Consumes("application/xml") @Produces("application/xml") public class Test  { public  Test () { } @POST public Response test() { Response response = Response.status( 4xx ).entity("Testing").build(); return response; } }

CXF-RS Hiding JAXRS Service Endpoints Listing

You may come across a scenario where you want to stop listing of the exposed service from given endpoint. This can be achieved by setting the property " org.apache.cxf.endpoint.private "   to true as shown in following snippet: < jaxrs:server id = "serivceId" address = "/test" > . . . < jaxrs:properties > < entry key = "org.apache.cxf.endpoint.private" value = "true" /> </ jaxrs:properties > </ jaxrs:server > This will stop the listing of the service when url http://server:port/ test is typed in the browser.

Eclipse Tips: Escape string while pasting in the editor

Escape string while pasting in the editor Go to Window > Preferences, type escape in the search field. Go to Java > Editor > Typing preference page. In last group label "String literals" select the "Escape text when pasting into a string literal".

CXF JSON Generation remove @ prefix

Working with CXF-RS if you want to generate the json response along with xml than it becomes pain in cases where your xml is a mixture of attributes and elements. Problem comes because of default jettison json provider which is configured in cxf-rs. The jettison appends the '@' prefix  with the attributes. However, I needed json free from any prefixes. To achieve this i had configure jackson as json provider like this:                <jaxrs:providers>             <ref bean="jaxbProvider" />             <ref class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>         </jaxrs:providers>                         That's it and you should be free from prefixes.

CXF-RS: Java Code Generation from xml/xsd

Cleaner approach is to use xjc like this: Continue to dirty approach below if u need to: When working with CXF-RS services often we start with XML message that will be served. After that we go through endless iteration of generating the right Java POJO's for the XML. The library like apache XMLBeans generate the Java code but the code generated is not what a developer would write and generally tedious to modify and understand. I have come across a work around for generating Java classes from XSD (xml) which is very close to what a developer with decent experience will write.  Follow the steps given below to explore the solution: 1. Generate the wsdl from from xsd as given in at this link  ( http://cxf.apache.org/docs/xsd-to-wsdl.html ). 2. The Java classes can be generated from wsdl from maven plugin entry below find complete details here   http://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html org.apache.cxf cxf-codegen-plugin ...

Spring Roo is amazing

Developer spend 75% of their time working on boiler-plate code. Spring Roo do amazing job of doing that for you and gets you started really-2 fast. After that you can follow the application curve if writing the business logic. Why Roo? Define the class and its relation it will generate the DB using hibernate  you can generate the controller's ( and UI) from the same classes with CURD operation supported test code is also gets generated  code generated is clean and easy to modify dependency resolution happens through maven once you are done projects are eclipse ready easy to get rid of metadata for production  Other tools: I came across Grails but i needed a framework which will generate the java so roo was the better choice for me Video helped me get started:  http://s3.springsource.com/MRKT/roo/2010-01-Five_Minutes_Roo.mov

Netbeans or Eclipse which one to choose

There are so many articles on the web discussing this, what I am going to do is just briefly explain the pros and cons of each which will help you choose better. Description Netbeans Eclipse Plugins It helps you extend the reach of your IDE to newer technologies without changing the IDE Good Good Code Refactor Reflects the change made in all the references Decent Good Getting Started The time it takes to get going on with your application Good Decent Enterprise Support Usage in big companies, spending effort in eclipse Decent Good Debugging Easy in which you can find a problem Decent Good UI Looks old Decent Good Spell Check Not Pres...

First CXF-RS service with Tomcat web-container

Looking to get started on CXF-RS, well that was what i was looking for and there are load of articles doing however none of them provide sufficient bullet points to make me understand how the control is following are how to debug the application if something is not working. Well that's what i am going to write here. Following are components you need to get started with first CXF-RS: Tomcat Eclipse (or some equivalent IDE) Spring Create a dynamic web project in the eclipse (this is nothing but a simple web project which can deployed and can run when deployed in the web container like Tomcat). Keep your eye on the bold terms featuring in the files... Start will writing the web.xml descriptor file. contextConfigLocation WEB-INF/ deploy-context.xml org.springframework.web.context.ContextLoaderListener CXFServlet CXF Servlet org.apache.cxf.transport.servlet.CXFServlet 1 ...