Posts

Showing posts from 2012

Simple Calculator

//Imports are listed in full to show what's being used //could just import javax.swing.* and java.awt.* etc.. import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.Container; public class SimpleCalc implements ActionListener{ JFrame guiFrame; JPanel buttonPanel; JTextField numberCalc; int calcOperation = 0; int currentCalc; //Note: Typically the main method will be in a //separate class. As this is a simple one class //example it's all in the one class. public static void main(String[] args) { new SimpleCalc(); } public SimpleCalc() { guiFrame = new JFrame(); //make sure the program exits when the f...

Event Handling in Java - Assignment 2

The objective of this assignment is to understand events handling in abstract way. We have used events with GUI components, but events are not only associated with GUI components. You can define events and fire them even when there is no GUI of your application. In this assignment you are supposed to create ResultAnnouncedEvent which is fired by ExaminationCenter. Different entities (or classes) can register themselves as listeners so that when result is announced they are notified, for example Student, Teacher and Administrator. So these classes are event listeners. These classes should just receive the event and print the event attributes. The ResultAnnouncedEvent class should be composed of class, section, and date attributes. Also create ExaminationCenterTest class that fires the event. Before doing this assignment, it is recommended you read API docs of java.util.EventObject, java.util.EventListener. Also See: http://www.jguru.com/faq/view.jsp?EID=98547 Due: Next Lab.

Introduction to Java Swing

LabelFrame.java import java.awt.FlowLayout; // loads images import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingConstants;  public class LabelFrame extends JFrame  {  private JLabel label1; // JLabel with just text  private JLabel label2; // JLabel constructed with text and icon  private JLabel label3; // JLabel with added text and icon  // LabelFrame constructor adds JLabels to JFrame  public LabelFrame()  { super( "Testing JLabel" );  setLayout( new FlowLayout() );  label1 = new JLabel( "Label with text" ); label1.setToolTipText( "This is label1" ); add( label1 ); Icon bug = new ImageIcon( getClass().getResource( "bug.jpg" ) ); label2 = new JLabel( "Label with text and icon", bug, SwingConstants.LEFT ); label2.setToolTipText( "This is label2" ); add( label2 ); label3 = new JLabel(); // JLabel constructor no arguments label3.setText( "Label ...

What is the difference between sandy bridge and ivy bridge processors

Transistor is key component inside processor, which has a physical size. In Sandy Bridge, the transistor size is 32 nano meter (also called 32nm technology). These are called Intel 2nd Generation Processors. There are multiple i3, i5, and i7 Sandy Bridge models. Under Ivy Bridge, Intel has decreased the transistor size to 22 nano meter. Its mean, more components can be embedded inside same size processor chip, so more processing power can be introduced inside same size physical chip. i3, i5 and i7 with Ivy Bridge type processors are called Intel 3rd Generation Processors. In Ivy Bridge, Intel has also introduced a new transistor named 3D / Tri-Gate .

Introduction to Computing Fall 2012

Course Objective This course is an introduction to broad class of computer issues. It is designed for students who are not CS majors, who have had little or no previous experience with computers.  Announcements Section A and B, your labs are being conducted as per schedule. The Lab instructor comes in each lab. It is required for every student to attend lab. Its attendance is required to be at least 80%. There is separate exams of tasks done in lab. So don't miss it. Oct 2. The course for Sessional-1 exam is first 8 lectures, as per our course outline. All what we covered before Input Devices (excluding input devices). Nov. 8. There is quiz # 2 in next week's first lecture (of both sections in their classes). Nov 15 . The course for S-II exam for both sections is Input and Output Devices, Operating Systems and Databases. (Section B, please note, no any topic of Data Communication is included in S-II exam). 23 Dec, If any one has attendance shortage issue because of 1-2 l...

Spring MVC 3.1 - How to Get HttpServletRequest and HttpServletResponse objects in Controller Method

When Spring MVC 3.1 dispatcher introspect the parameters lists of user defined controller method that is to be executed. It identifies it from URL pattern. Using reflections it introspect the types of parameters and pass the required object to that controller method. For example, there is a method hello() which expect HttpServletRequest and HttpServletResponse object binded or associated with current under-process request, the hello() method can be declared like this: @Controller @RequestMapping("/hello") public class HelloController { @RequestMapping(method = RequestMethod.GET) public String hello(HttpServletRequest request, HttpServletResponse response) { // Use request and response object as you in JSP or Servlets } So, the Spring MVC 3.1 would automatically pass the defined parameters.

Spring MVC 3.1 - How to Get HttpSession in Controller Method

In Spring MVC 3.1, there is great improvement on ways how we get frequently used object during request processing life cycle. You may need to have access to following classes instances frequently in different controllers e.g. HttpServletRequest, HttpServletResponse, HttpSession, etc. When Spring MVC 3.1 dispatcher receive the raw request, it introspect the parameters lists of user defined controller methods which is supposed to be executed (from URL pattern). Using reflections it introspect the types of parameters and pass the required object to that controller method. For example, there is a method names index which expect HttpSession, so that it could perform something related to session. the index() method can be declared just like this: @Controller @RequestMapping("/home") public class HomeController { @RequestMapping(method = RequestMethod.GET) public String index(HttpSession session) { // Use session object here, as you like } The Spring MVC 3.1 would automatic...

Spring MVC 3.1 - How to Convert Form Empty String Values to null Before Controller Execution

If you are using Spring MVC 3.1. Sometime, we want the framework should return the null values for parameters whose values are not set on HTML form. But Spring by default get then as empty strings e.g. "" instead null. You need to configure @InitBinder inside your controller class. It would do the magic of converting all empty strings to null before passing the form object to controller. @InitBinder /* Converts empty strings into null when a form is submitted */ public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); }

What is Port in Context of Client Server Communication

IP address is unique numerical address of each computer directly connected to internet. If you want to send data to a computer, all you need is the IP address of that computer. But data is received by some program running on a computer. If you send data to a computer just specifying its IP address, how can that computer decide which program the data should be passed to? (as a computer runs multiple programs). Here comes the port. Port is a number used to specify which program should receive the data. So when a computer send data to another, in addition to IP address, the sender also specify the port number so that the operating system could decide the target program where data should be passed. Say there is a computer with IP address = 172.43.98.34 which is running a web server (a program that receive HTTP request and send response) on port 88. You can access it by point your web browser to http://172.43.98.34:88/ Some pre-defined port numbers are used for particular type of s...

How to Subscribe to a Particular Category or Label on Blogger

Some blogger blog on multiple categories. That means their posts contains articles on more than one topic. What if you are interested to read all articles published under a particular category only. For example, BitsPedia publish articles on many topics. If you want to read articles published under Web Businees category, here is the URL you need to subscribe in your RSS reader: http://www.bitspedia.com/feeds/posts/default/-/Web Business You can replace " Web Business " with any label/category you want to subscribe to. You can subscribe to any Blogger blog using this technique.

Programming Language for Entrepreneurs

As entrepreneur, we need to test our ideas by making a product fast. Its difficult to predict about success. So the speed to create a new product matters a lot. So that you can try more ideas fast. So if you have a mindset of entrepreneur, I recommend to choose a programming language that suits your personality well. For example, as web entrepreneur you should develop skills on highly productive programming language. I started my career with Java development and doing it for last 5 years. I created a few web products but it took a lot of time to develop because of long code-compile-deploy cycle. And less availability of plugins/gems. Now I see, If I have done that work using more productive language (e.g. Ruby on Rails, PHP etc), I would have test my ideas faster. So if you happen to be a web entrepreneur, don't go into Java or .Net development. Prefer Rails or PHP. It would help you in long run to test your web ideas fast. You may think, some language are more fast as others (...

Where They Search The Stuff?

You must know where your product users search the stuff you offer. Some of these places may be: Word of mouth Search engine Newspapers Blogs Experts Famous People Peers TV shows Books B2B / B2C sites Make sure you are there, where you are being searched out.

Where They Hangout?

To target right customers, we must know where the hangout. These are places where a communicated message reaches more potential customers. Some of these places include: Social Networks Business Association (or union) Meetings Events /  Conferences Communities A right marketing strategy can produce better results in places that have more potential customers.

How to Change Your Name on Facebook

Image
If you want to change your name, follow following steps to change your name Facebook. 1. Login to Facebook 2. Go to Account Settings, see image below: 3. On the Open page, click on Edit link, see image: 4. On the form that opens, choose your new First Name and Last Name. Input your password below (yes, Facebook requires your enter your password to change your name). See image: 5. Click on Save Changes, and your name has been changed.

How to Change Relationship Status on Facebook

Image
If you want to change your relationship status on Facebook, follow following steps to change relationship status on Facebook. 1. Login to Facebook 2. Go to Your Profile Home by clicking on your name or picture (see top left) 3. Click Update Info button, see image below: 4. On the opened page, click on Edit button. on Basic Info section. See image below: 5. A Pop-up window will open, chose your relationship status and privacy settings (i.e. who can see you relationship status) and click Save button below. See image below:

How to Create a Facebook Account

Image
Hey! young man, my guess is you have heard from one of your friend or relative about Facebook. And you want to create a Facebook account. But you don't know how to create it. Here I would help you step by step to do so. Facebook is a social networking website that helps you connect with you friends. To create a new facebook account, you just need to follow these steps: 1. Before creating facebook account, you should have your own email address. If you have it, fantastic! If not, go to gmail.com and create a new email address by clicking Sign Up link. 2.  Click here  or go to http://www.facebook.com , once web page is open, at first page (it is called Home Page), you will see a form. The form looks like this: 3. So just fill the form with asked information (name, email, password, gender, date of birth), and click Sign Up button. 4. After you submit the form (by clicking Sign Up button), Facebook company will send you an email at email address you written in form. Read tha...

How to Create Another Facebook Account

If you already have a Facebook account, but for some reason you need to create another Facebook account. There are following point to note, or way to create another account. 1. If you no longer need earlier account, you can delete that account and create new account using same email address you used with your first account. 2. If you want to create another account without deleting previous account. Facebook do not allow to create multiple accounts with same email address. You must have a new email address, if you don't have one, you should create new email address first. And then create another facebook account with new email address. They have done it to stop spam facebook accounts. Although, one can create new email and then new facebook account, but facebook had put this hurdle so that people avoid creating new accounts. Like one person has only one Social Security Number, same way, facebook also treat email as unique number to counts its 'population' i.e. users. Good lu...

When Servlets are Loaded

If you are developing web applications using Java based technologies, JSP or Servlets. You must be familiar with the loading time of Servlets. First lets see whats mean by loading. If you see the Servlet life cycle. Its as follows: 1. First of all init() method is called (this is called loading) 2. For each request, service() method is called. Which process the request and sends response to user. In case of HttpServlet, the service() method delegates the request processing to doGet(...) or doPost(...), depending on type of request. 3. When you undeploy you web app or stop Tomcat from running, destroy() method is called. You see, init() and destroy() are called only once, after you deploy your application. After serving user request, the servlet instance remains in memory to serve other requests. But the question is, when does the init() method is called first time, or when does the servlet loaded? If you do not do any explicit configuration, the servlet is loaded when first request com...

How Session Work in Web Applications and Why We Need It

Image
Term 'Session' is used in different contexts in computer science e.g. connection, telnet session, session layer, web session, etc. I would discuss the sessions in context of web applications only. There are following fundamental points related to sessions in web applicaitons: 1. What is a session in web application? 2. Why we need a session? 3. How session creation and identification work? 4. Where session data is stored? 5. How to Delete a session? Lets look at each part one-by-one: 1. What is a Session in Web Application? Web developer may need to store small data temporarily at server side, for each user who is interacting with the web application. Such data is stored in a session, so session is a temporary storage at web server. For each user, there is unique session are at server. During request processing of a particular user, the user's session is accessable in all web pages i.e. data stored in session by index.php can be accessed by products.php or a...

How To Improve Object Oriented Programming Skill Beyond Basics

Most software developers join industry after undergrad in CS. The Object Oriented Programming course we study in early BS semester covers only basics of Object Oriented Design. I had good luck to study Design Patterns in MS and other relates stuff by self study. The good thing is, there is nothing difficult of rocket science. If we just have some basic guidelines, we can explore things by our own. Here I would share very brief outline how we can switch our object oriented design skill to next level. Level - I: Object Oriented Programming Concepts Here comes the basics. We should study basic object oriented concepts. These are mostly covered in OOP course of undergrad level. Basic concepts, one must be familiar with at this level includes: Association Composition Aggregation Inheritance Polymorphism Encapsulation Abstraction Generalization Overloading Overriding Level - 2: Object Oriented Design (Patterns) There are some scenarios we frequently encounter during object orien...

My Experience on Cloud with Linode VPS - Its time to say THANKS to Linode

Image
About a year earlier, I developed a reviews portal for products, services and institutions using Java technologies (i.e. FaceRank.PK ), I was not sure how I would host it. Here is how I goes ... I explored different Java based web apps hosting providers. I was almost shocked to see, Java hosting was really very expensive as compare to PHP based hosting. I looked into shared Java hosting, but they didn't provided enough freedom e.g. to restart Tomcat anytime, update JDK, redeploy app. Dedicated hosting were expensive for me, then I explored different Virtual Hosting Providers. From those, I was inspired by users' opinion about Linode.com . I spend a lot of time on web, and I believe, if a lot of users are saying something about a particular provider, there must is something great about it. So I decided to try Linode.com I purchased Linode 768 package. Its almost a year now, guys! Linode is simply awesome. And only 4 times, I need to put support ticket, their response time was be...

How to Scale An Image Maintaining Aspect Ratio Using java-image-scaling API

Image
Below is the static function that I use to scale images in Java using Java Image Scaling 0.8.5 API . When user uploads a file, I pass that file as InputStream to this function, with StandardSize and ThumbSize, the function saves the images at passed fileStorePath with name "newFileName". It also maintains the aspect ratio for thumb and standard image both. import com.mortennobel.imagescaling.ResampleOp; import javax.imageio.ImageIO; // Import other classes here ... public class UtilMethods { public static void saveStandardAndThumbImage(String fileStorePath, String newFileName, InputStream imageInputStream, final int standardSize, final int thumbSize) throws Exception { BufferedImage srcImage = ImageIO.read(imageInputStream); String extension = newFileName.substring(newFileName.indexOf(".")+1, newFileName.length()); int actualHeight = srcImage.getHeight(); int actualWidth = srcImage.getW...

How to Upload Multiple Files using Spring MVC 3.1

Image
Here I share only related parts of the code: 1. Declare Multipart Resolver in spring config file. 2. Define FormBean: public class User implements java.io.Serializable { private String name; private List files; // Must generate getter/setters here } 3. Define the JSP View for Form <%@ taglib prefix="f" uri="http://www.springframework.org/tags/form" %> <f:form action="/users/new" enctype="multipart/form-data" method="POST" modelattribute="user" name="user"> Name:<f:input path="name"> Picture 1 : <f:input path="files" type="file"> Picture 2 : <f:input path="files" type="file"> <input name="Submit" type="submit" /> </f:input></f:input></f:input></f:form> 4. Just get your files in Controller @Controller @RequestMapping ("/users") public class UsersController { @RequestM...

Web Applications Performance Optimization Brainstorming Result

Image
Recently one of my friend asked to share few points about performance optimization that he need to add in a lecture. Here are what major points, I could think of. Feel free to add another point in comments (I will add in post with thanks)! The web applications performance can be optimized on different tiers. I would share some points for each tier. Some are to-do items. Others are little advance and requires protocol level understanding of web. Web Browser Incorporate data compression for things that moves from server to browser (CSS/HTML/JS etc). See  https://developers.google.com/speed/articles/gzip for details. Use AJAX where possible ... to avoid page refreshes, reduce load on server, provide better user experience. Minification of JS and CSS, see various tools here http://www.devcurry.com/2009/11/7-free-tools-to-minify-your-scripts-and.html Let browser to cache resources that you believes would not be updated soon (using HTTP headers) e.g. CSS, images, JS, etc. Merge JS ...

My Reset CSS Stylesheet

I often find me looking into old projects for my very simple reset stylesheet. Not remember from where I get it initially. Here it goes: (sometime I blog things for myself too, so never mind :) html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; background: transparent } body { line-height: 1 } ol, ul { list-style: none } blockquote, q { quotes: none } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none } :focus { outline: 0 } ins { text-decoration: none } del { text-decoration: line-through } table { border...

Seems the Web Application Architectures are Converging to Message Oriented

It seems the web is converging to messaging based architecture from traditional resource based architecture in which a hyperlink was treated as resource identifier. In recent past, came the RESTful style, that suggested to expose resources on web to let HTTP methods (GET, POST, PUT, DELETE, etc.) play with resources. Now WebSockets are getting into play, that is socket based two way communication between web server and client. The protocol has already been standardized by IETF . The API standardization is almost done by W3C ( see WebSockets API ). With Java perspective, the implementation is already bundled with latest releases of Tomcat and Jetty containers. Java Specification Request ( JSR 356 ) for Java API for WebSockets' Review Ballot closed on March 2012. Spring is highly used framework for different enterprise requirements, on 30 April, Spring Source also  rolled a ticket  to add WebSockets support into Spring Framework. As Java developer, there are a lot of intere...

How to Generate JAX-WS Client Proxy Using Wsimport of JAX-WS 2.2.6 or later

I am using JDK 1.6 on Ubuntu. Implemented web services using JAX-WS 2.2.6 but when tried to generate client proxy code using "wsimport" utility of JDK. It failed, because the "wsimport" utility in JDK 1.6 is older (probably JAX-WS 2.1.6 or an earlier release ships with JDK 1.6) So I used "wsimport" utility that comes with JAX-WS 2.2.6 RI. How? I defined two environmental variables like this, by putting into ~/.bashrc file: JAXWS_HOME=/opt/jaxws-ri2.2.6 JAVA_ENDORSED_DIRS=/opt/endorsedlibs In JAVA_ENDORSED, I pasted jaxws-api.jar and jaxb-api.jar The JAXWS_HOME contains standard files/folders that comes with JAX-WS 2.2.6 Reference Implementation download bundle. Here is how I generated client proxy code: wsclient-project/src:~$>  bash $JAXWS_HOME/bin/wsimport.sh -Xendorsed -s . http://localhost:8181/myproject/webservices/Alpha?wsdl It generates the client proxy code and put into current folder i.e. src.

How to use JAX-WS 2.2.6 with JDK 1.6

JDK 1.6 comes with spec + implementation of JAX-WS 2.1. If we add all libs of JAX-WS 2.2.6 in our project classpath, the JDK still prefers it own JAXWS API i.e. version 2.1. It will cause jar conflicts or MethodNotFoundError etc. To use JAX-WS 2.2.6 or later with JDK 1.6, we must force JDK to load spec+impl ver. 2.2.6. It is done by endorsing new library. There are two ways to endorse JDK to use our provided libraries instead of its own. From JAX-WS 2.2.6 downloaded bundle. Put only jaxws-api.jar and jaxb-api.jar to JDK1.6/jre/lib/endorsed directory. Set "java.endorsed.dirs" environment variable, it should point to directory than must contain jars to be endorsed. e.g. java.endorsed.dirs=d:\endorsedlibs, where endorsedlibs directory contains two jar files mentioned in step 1.  We must not put all JAX-WS 2.2.6 jar files into endorsed directory. Only specifying two API jars (the specification) is enough. At runtime, the right implementation would be loaded from your project clas...

How To Sign-In With Multiple Google Accounts in Same Browser

Image
Google has made it possible to sign-in with multiple Google accounts at same time in a web browser. Sign-in with any of your account and open following URL: https://accounts.google.com/MultipleSessions Check the radio box " On - Use multiple Google Accounts in the same web browser " and three check boxes under it (after reading what they state). Here is the screen shot, this way you can setup multiple accounts. That you can open in different tabs.

How To Find Good Articles To Read On Internet Without Wasting Time

Image
The issue is, say you are interested to read articles on marketing or on a topic of your interest. You Googled and found some good blogs that contains articles on category of your choice. Say, you got 15 such sites. You have to visit 15 blogs daily to see whether they have published a new article. Which is very time wasting and boring if you discover nothing interesting from most of them. The solutions is RSS reader! Oooops what the hell it is? Don't worry, its very simple to use. Someone said, if we knew the pleasure of destination, a difficult journey becomes very easy. After you have configured the RSS reader, you will use RSS reader to subscribe to different sites/blogs, its only 6-8 seconds task. But as result, it pulls all new articles from that blog and shows you their titles at one page. From where you can read any articles. Assume how easy the life would be if you get 100 articles on different sites at one page. Let me demonstrate by example , say you love to read new stu...

How to Get Spring Managed Service Instance Outside the Action Class in Struts2

In Struts 2, we can configure Spring to inject service instanced using Dependency Injection into Action classes. But sometime we need these service class instances in other components who are are Spring aware. For example you need AccountsService instance in StudentService class. For such purpose I have createds util class which can return me reference to any service instance at run time, in any class. I call is SpringContext, here is its definition: package com.bitspedia.util; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringContext implements ApplicationContextAware { private static ApplicationContext CONTEXT; public void setApplicationContext(ApplicationContext context) throws BeansException { CONTEXT = context; } public static Object getBean(String beanName) { return CONTEXT.getBean(beanName); } } Now getting the r...

How to Run a Code Immediately After the Web Application or Context is Deployed in Tomcat

If are writing a web app using Java (JSP or Servlets), sometime we want to execute a code section immediately after the application context has deployed. For examples to: Initialize Caching system Initialize some scheduling services Put some data is application scope that will be needed frequently. Before Servlets 2.4, such code was put in a normal Serlvet, which was configured in web.xml to run at startup. But in Servlets 2.4, there is explicit mechanism to do so. Here is how you can do it: Make a class MyListener that implements ServletContextListener Write the code you want to run only once (after the context is loaded, i.e. when the web application is deployed in Tomcat) in contextInitialized(ServletContextEvent cse) method. package mypackage; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class MyListener implements ServletContextListener { public void contextInitialized(ServletContextEvent cse)...

How To Define Handlers Chain in JAX-WS Using LogicalHandler and SOAPHandler At Same Time

JAX-WS Handlers implement Interceptor Pattern and Chain of Responsibility Pattern, that means when a client sends a SOAP request to a service endpoint, the handles intercept the request, perform some processing and (optionally) forward request to next handler in the chain, until the actual service implementation process the request. A handler may process the request by itself by replying to the service client. It depends how you have implemented the handlers. JAX-WS provides two types of handlers i.e. LogicalHandler and SOAPHandler. In this article I will show have you can define both types of handlers in the a chain and how/when the runtime calls their life cycle method i.e. handleMessage() to provide them opportunity of processing the request. Generally handlers do not process the request, they only perform 'cross cutting concerns' tasks e.g. authentication, authorization, logging, accounting, validation, etc. Let us define a web service, which have only one method. We can al...