Showing posts with label how-to. Show all posts
Showing posts with label how-to. Show all posts

Wednesday, March 12, 2014

How to find IP address in mac

How to find internal IP address in mac
1.  Click on the apple icon on the upper left corner.


2.  Click on System Preferences.
3.  Click on Network under Internet & Wireless.
4.  Your IP address will be listed next to your connection status.



Monday, March 10, 2014

Getting started with RESTful webservice using Jersey

Jersey helps developing RESTful webservices seamlessly and makes your life easy. This article gives you a quick start on how to create your first RESTful web service using Jersey & Maven.  I assume you have a decent understanding of maven and J2EE.

Make sure you have
  1. Eclipse Kepler
  2. M2Eclipse plugin
  3. Java 1.7
  4. Tomcat 7
Step 1 - Maven Project
Create a new maven project from your eclipse.  Select maven-archetype-webapp archetype,  provide group id, artifact id, package in the following dialog. (See screenshot below)


Note: By default installed facets will not be Java 1.7, Dynamic web module 2.4.  You can edit this in org.eclipse.wst.common.project.facet.core.xml under .settings folder.  Also make sure to change the JRE from 1.5 to 1.7 in your project build path.

Step 2 - Maven Dependencies
Add the following jersey server and jersey servlet dependencies to your pom.xml
Step 3 - Deployment Descriptor
Add the Jersey servlet container to your web.xml.
Step 4 - REST Resource
Create your package and SampleRestResource class.  Add the path "/sample" at the class level, and add 2 GET resources. One with path "/hello" and the other with "/hello/{message}".  
Step 5 - Run your application
Right click on your project --> Run As --> Run on Server --> Select tomcat.  Now your first resource can be accessed from http://localhost:8080/jersey-rest-helloworld/jersey/sample/hello and the other resource from http://localhost:8080/jersey-rest-helloworld/jersey/sample/hello/your%20message

You can download the complete source here.

Monday, January 20, 2014

Why Singleton design pattern is still a good interview question to Java developers

Why every interviewer asks about singleton design pattern?
Well the answer could be either,
  1. That's what the interviewer knows to ask for.
  2. Or its a good way to start and branch into several other discussions.
  3. Or its one of the simplest design pattern and a controversial one in terms of usage.
What ever the reason may be, we better know it.

What is Singleton
Singleton is categorized under "Creational design pattern" and part of Gang of Four design pattern.  Singleton is a design pattern which suggests only one instance of a class for the entire application at any condition. There are several ways to achieve this, and be assured that most of answers you say may not convince the interviewer and he can over rule the solution.

Ways to do it
Before getting into the details are there any examples of Singleton to be used in real scenarios?  Yes, java Runtime, Logger, Service locators of JEE pattern follows singleton.  Now, we shall look into the most common ways to implement Singleton.

Singleton - Eager Initialization Example
As the name states in this approach the instance is "eagerly" created before it is expected/asked for.  It means the class will be initialized during the application startup.
In this example the interviewer would be interested in asking, What if the instance of this class is not required at all.

Yes it is a drawback that the instance is created even if it is not required. And that would be an issue only if this object is large, or else it is the best to leave it as is.  Lets say the interviewer says,  it is a large object and I do not want it to be eager loaded.  Well the next section describes you how you could write Singleton with lazy initialization.

Singleton - Lazy Initialization Example
Lazy loading is an interesting topic in programming, it means creating the object in a delayed(lazy) way. Generally any expensive process could adapt lazy style. To make our singleton lazy we have initialize the instance variable only when it is expected.
You could see the instance variable is assigned with the object when it is null and then on the same variable is reused. Take a closer look into line 10, it ensures thread safety.  If you are just writing just the pseudo code, there could be a question what would you synchronize as you haven't initialized the object yet. We synchronize the block with the class here.

Next is the volatile keyword for the instance variable, do we need that? If so why.
Yes it is absolutely required or you may run in into out of order write error scenario. ie. The reference is returned even before the object is constructed (in other words the memory is allocated but the constructor code isn't finished execution). Also volatile keyword helps as the concurrency control tool in a multi-threaded application.

Singleton - Enum way Example
Easiest of the ways, by default Enums are thread safe and ensures single instance.
For an interview I would not suggest this approach,  since it would finish up the question pretty quick.  You don't want to do that,  better hold the interviewer on the topic you know well. In terms of implementation I would suggestion the Enum way or the one that is discussed in the next section.

Singleton - Bill pugh way Example
William Pugh co-author of findbugs static code analyzing tool, on his research suggested the following way while implementing singleton.
You could witness  SingletonHolder, SingletonBillPughExample will not be initialized until getInstance() is invoked.

Thursday, October 10, 2013

How to make Eclipse autocomplete to suggest as you type

Recently some one was asking if Eclipse content assist/autocomplete can be made to suggest as I type my class name? Immediately I could remember XCode for mac doing something like that and I felt there should be a way in Eclipse.

By default eclipse autosuggest would trigger once you type "." the goal is to make it suggest me the "Type/Class" names too. How to make it do?

Steps:
Go to Eclipse(Windows for windows users) --> Preferences --> Java --> Editor --> Content Assist

Under subsection "Auto Activation" the default value for Auto activation triggers for Java will be "." change this to

.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

Optionally you can increase/reduce the Auto activation delay to a lesser value.



You are all set! Now Eclipse will start suggesting as you type.

Monday, July 29, 2013

How to right click on a mac mouse

Initially I was puzzled on how do I right click on my new mac mouse. :-) If you have searched for this article, you also would have had the same question.

Navigate to System Preferences --> Mouse --> "Check" Seconday click --> Click on right side.

Once you are done with that you can right click on the mac mouse.

Monday, June 17, 2013

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I got this exception while I was trying to execute an open source application that I found from the web. I was trying to run the application from my eclipse managed tomcat 7 server. I noticed that my project's maven dependencies were not having the right jars.
This problem can be fixed by adding maven dependencies in the project's web deployment assembly.
  1. Open the project's properties (e.g., right-click on the project's name in the project explorer and select "Properties")
  2. Select "Deployment Assembly"
  3. Click the "Add..." button on the right margin
  4. Select "Java Build Path Entries" from the menu of Directive Type and click "Next"
  5. Select "Maven Dependencies" from the Java Build Path Entries menu and click "Finish".
You should see "Maven Dependencies" added to the Web Deployment Assembly definition after the following the above steps.

Thursday, June 13, 2013

How to remove a plugin from eclipse

Go to Help > About Eclipse > Installation Details, select the software you no longer want and click Uninstall. (On Mac it is Eclipse > About Eclipse > Installation Details.) In older versions, you might need to Run Help > Software Updates > Manage Configuration..., select the feature of interest, and disable it with the task shown in the right window.

When a feature is disabled, all its plug-ins will be disabled also. They are still available on disk, and they can be enabled at any time in the future.

To physically remove the feature and its plug-ins, you will have to manually remove the feature from the eclipse/features directory and its plug-ins from the eclipse/plugins directory. I advise extreme caution here. Remove the wrong ones, and you may spend quite some trouble restoring your Eclipse to a stable state.

Wednesday, June 5, 2013

How to exit from an unix manual page

Though the answer is simple, I have struggled a bit to get out of the man page. Thought this could help for unix beginners like me.

"man" command is very useful to read the manual of any commands that you use from terminal on a linux/mac machines.

From your terminal "man command-name" takes you to the manual page.

In order to navigate in the pan page use "up" or "down" arrow keys for navigation. In certain cases you may have to use enter key.

To get out of the man page simply type "q", this will take you to the command prompt from open terminal.

Ex: man ssh, man chmod, man ls

Wednesday, May 22, 2013

Collection of very interesting unix commands

How to get your top 100 unix commands

history | sed "s/^[0-9 ]*//" | sed "s/ *| */\n/g" | awk '{print $1}' | sort | uniq -c | sort -rn | head -n 100 > commands.txt

How to copy a file to all subfolders of a directory using unix command

find . -type d -exec cp pathtofile {}/ \;

How to delete all .svn folders from current directory using unix command

find . -type d -name '.svn' -print -exec rm -rf {} \;

How to list all network connections (including which app they belong to)

lsof -i -nP

How to run the last command as root

sudo !!

How to execute the previous command until it is successful

until !!; do :; done

How to display summary of git commit ids and messages for a given branch

git log --pretty='format:%Cgreen%H %Cred%ai %Creset- %s'

How to list all file extensions present in the current directory

ls | perl -lne '++$x{lc $1} if /[.](.+)$/ }{ print for keys %x'

How to get your top 10 commands with number of times you have used it

cat .bash_history | cut -f 1 -d\ | sort | uniq -c | sort -r | head

To generate list of usernames from an svn logs (Run from top level of the svn project)

svn log | grep -E "r[0-9]+ \| .+ \|" | awk -F"|" '{print $2}' | sort | uniq > ~/authors.txt

How to get process details from its pid

ps -p $pid

How to open firefox profile manager

/Applications/Firefox.app/Contents/MacOS/firefox-bin -p

Credits:
https://docs.google.com/forms/d/1XNMoSdfYFe_WkPfU--M88oL00PDLIOAo1HxjhZvZYJ4/viewform
Mr. Robg
My previous post
http://stackoverflow.com/questions/1102986/most-powerful-examples-of-unix-commands-or-scripts-every-programmer-should-know
http://www.commandlinefu.com/commands/browse/sort-by-votes

Monday, May 6, 2013

How to rename a file or folder in mac

Rename a file or folder in mac

If you were a windows user and new to mac, you would wonder how to rename a file in mac.  

The first thing you would try to do is a function f2, which wouldn't have helped.  The next effort you would have taken would be to do a cntrl click to look through the options.  That wouldn't have helped either.  May be you would have then tried "duplicate" or "alias" option and vent in vein.

Select the file or folder you want to rename and press enter key,  here you go now your will be able to  rename.

Wednesday, May 1, 2013

How to delete all svn folders using mac terminal

How to delete .svn folders

On the process of importing my svn repository to my git (without history),  I wanted to delete all .svn folders from my project without deleting the rest of the content.  Here are the steps to do that,

cd /the root folder of your project
find . -type d -name '.svn' -print -exec rm -rf {} \;
  1. cd --> change directory to the root folder of your project.
  2. find . --> find in the current directory
  3. -type d --> file type directory
  4. -name '.svn' --> file name .svn
  5. -print --> print what matched up to this point (the .svn dirs)
  6. -exec rm -rf --> exec the command rm -rf (thing found from find)
  7. {} --> place holder for out from find
  8. /; --> / to escape ; and ' is to tell find that the command for exec is done

Tuesday, April 30, 2013

How to add a Git submodule from eclipse EGit

Adding a submodule using eclipse

You can add a new submodule to a repository by selecting a repository in the Git Repositories view and selecting the Add Submodule context menu option.

The wizard will prompt for the path and URL of the submodule being added. The path entered will be relative to the parent repository's working directory and the URL will be used to clone the repository locally.

Once the wizard is completed the submodule will be cloned, added to the index, and the submodule will be registered in the .gitmodules file as well as in the parent repository's .git/config file.

Credit: http://wiki.eclipse.org/EGit/User_Guide

Tuesday, April 23, 2013

Mac - How to fix disappearing scroll bar

Are you getting frustrated that you are not able to get your scroll bars in your macbook? You are not the only one. J

How to fix your scroll bar?

Here are the steps,
  1. Click on the Apple logo on the left corner.
  2. Click on System preferences
  3. Under personal select General
  4. Click on Always radio button under Show scroll bars. 
Now you can see your scroll bars not disappearing.


Wednesday, February 22, 2012

How to avoid namespace using JAXB

After banging several times to eliminate namespace from the generated XML found this useful URL. Gives a detail explanation to understand JAXB namespaces.

Monday, July 13, 2009

Software Protection Solutions

Software protection is need of the day. It is estimated that about 30% revenue is lost due to piracy but these figures fail to explain the fact that piracy also increases legal sales. Director of a software company told me they learn about some companies using their pirated software but they did not took any action. The director was not surprised when he received order from the same company next year. He said in the absence of a workable demo or just to try full features before making a purchase decision many people use pirated versions. This does not mean that software companies should not protect their products but only mean that a legal demonstrable product should be made available to customer for evaluation for a sufficient period of time.


So let us learn how to protect software.

1. Third Party Software
Many developers use third party applications to help protect their software. As a result many software developers use a combination of protection methods in an effort to thwart hackers. Third party applications are often part of a total protection solution. The downside to relying on a third party is that if the algorithm of the third party application is cracked your software can be at risk.

2. Wrappers
Wrappers are applications that go around a software download. The wrapper handles the ecommerce, security access and tracks affiliate referrals.

3. Partial Key Verification
A partial key verification is a protection scheme that only verifies certain digits of the registration key. The verification digits vary in different versions.

4. Hardware Locking (generally Hard Disc)
Hardware locking, locks the software to a specific computer hardware, it could be hard disc, sound card, processor, graphics card etc. Hardware locking is used so that a single license can not be used on multiple computers. This is generally unpopular with users because they will often have difficulties if they upgrade their system to a faster system, change hard drive, face system crash. User will have the additional burden of contacting the software publisher so they can get their software to run again.

5. Online Activation
Online activation services provide software developers access to a centralized license server on the Internet, preventing software piracy by means of online software activation. Software activation is the process of obtaining a license for your software so that it becomes active and ready to use on your computer. Users dislike software activation because it is a form of "Call-back" and it will be additional head-ache if you do not have internet connection on the computer on which you want software to be installed.

6. Separate Trial and Download
Many developers release different trial version and full versions. This requires users to uninstall trial and reinstall full version.

7. Dongle Locking
Dongle locking is another form of hardware locking. The software will require the use of an external piece of hardware (either connected to the parallel port or USB port) to "activate" the software. This is very-popular among developers because it is easy to incorporate and easy to deliver. Users always dislike anything extra.

8. USB Drive Lock
USB drives also has unique manufacturer identification numbers like hard discs. Some companies are using USB pen drives as locks. The benefit is that you can continue to use USB drive for data storage. Additionally entire software can be provided in the pen drive with data in it. Imagine taking account ledgers or custom designs (like interior design projects, land escaping project etc.) with you when meeting a customer and updating details their it self. USB Drive Lock solutions will be very popular with users as will as developers.

Having a proper software delivery system is also a requirement in International Standards like ISO 9001, ISO 27001, BS17799 etc..

Wednesday, July 8, 2009

How a denial-of-service attack works

How does this type of cyber attack work? And how can people make sure their computers are safe?

Here are some questions and answers about the attack.

Q: What is a "denial-of-service" attack?

A: Think about what would happen if you and all your friends called the same restaurant over and over and ordered things you didn't even really want. You'd jam the phone lines and overwhelm the kitchen to the point that it couldn't take any more new orders.

That's what happens to Web sites when criminals hit them withdenial-of-service attacks. They're knocked offline by too many junk requests from computers controlled by the attackers.

The bad guys' main weapons in such an attack are "botnets," or networks of "zombie" personal computers they've infected with a virus. The virus lets the criminals remotely control innocent people's machines, which are programmed to contact certain Web sites over and over until that overwhelms the servers that host the sites. The servers become too busy to respond to anything, and the Web site slows or stops working altogether.

It's different from what usually happens when you try to access a Web site. Normally, you just make one request to see the site, and unless there's a crush of traffic from something like a big news event, the servers respond well. Hijacked PCs, on the other hand, are programmed to send way more traffic than a normal user could generate on his or her own.

Q: How often do these attacks happen?

A: People try denial-of-service attacks all the time — many government and private sites report being hit every day. Often the assaults are unsuccessful, because Web sites have ways of identifying and intercepting malicious traffic. However, sites really want to avoid blocking legitimate Web users, so more often than not, Internet traffic is let through until a problem is spotted.

Denial-of-service attacks are noisy by design, and they intend to make a statement. They're not subtle attempts to infiltrate a Web site's defenses, which can be much more insidious because that gives hackers access to whatever confidential information is stored there.

Often the attacks take a site out for a few hours, before Web site administrators can respond. What made the most recent attack notable is that it was widespread and went on for a while, beginning over the July Fourth holiday weekend and running into this week. It's not yet clear how the attack was able to last that long.

Q: Some organizations appear to have fended off these recent attacks, while other Web sites went down. How can this be?

A: The sites that went down probably were less prepared, because they are less accustomed to being hit or aren't sensitive enough to warrant extra precautions.

Popular Web sites, like e-commerce and banking sites, have a lot of experience dealing with denial-of-service attacks, and they have sophisticated software designed to identify malicious traffic. Often that's done by flagging suspicious traffic flowing into the site, and if there's enough of it, preventing it from ever reaching the site's servers.

Another approach is to flag suspicious individual machines that seem to be behind an attack, and ban any traffic from them from reaching the site.

That can often be difficult, though, because criminals use "proxy" computers to route their traffic, masking the source of the original requests. Proxy computers are often other infected computers that are part of a botnet.

Q: Is there usually evidence of who the culprits were? Or is the nature of the attack such that it leaves few fingerprints?

A: It's usually easier to stop a denial-of-service attack than it is to figure out who's behind it. Simply identifying where the malicious traffic is coming from won't get investigators very far, since the infected PCs that get roped into a botnet are owned by innocent people who don't know their computers are being used for nefarious purposes.

Pat Peterson, a security researcher and fellow at Cisco Systems Inc., says sophisticated attackers have also been adding a more subtle approach to evade detection.

Instead of directing huge amounts of traffic at a target site, they'll make more complicated requests one at a time that eat up more of the site's computing power, like trying to log in using bogus usernames and passwords. If enough of those requests are made, on a site that requires a lot of computing power, the effect can be the same, and the site gets knocked out.

This type of attack is trickier because it doesn't involve the sort of massive traffic surge that would normally tip off network administrators.

This advanced tactic wasn't necessarily used in the most recent attacks. In fact there are signs the attacks were relatively amateurish. The programming code appears to have been patched together largely from material that has been circulating in the criminal underground for several years, according to Jose Nazario, manager of security research for Arbor Networks.

Q: If these attacks make use of compromised computers corralled into a "botnet," should I be worried about whether my PC is one of them? What could I do to prevent that or fix it?

A: If your computer is being used in a denial-of-service attack, you're likely to see a significant slowdown, because your processing power is being siphoned for the assault. But there aren't always obvious signs that your computer has been infected.

So the best thing is to focus on prevention, namely by having up-to-date antivirus software. In particular, make sure your antivirus software gets updated over the next few days.

If you're concerned your machine might be infected, it's wise to run an antivirus scan. Many antivirus companies offer a free scan from their Web sites.