Date / Time related Oracle queries


These queries range from date manipulation, getting server info, get execution status, calculate database size etc.

  • Get the first day of the month

Quickly returns the first day of current month. Instead of current month you want to find first day of month where a date falls, replace SYSDATE with any date column/value.
SELECT TRUNC (SYSDATE, 'MONTH') "First day of current month"
    FROM DUAL;

  • Get the last day of the month

This query is similar to above but returns last day of current month. One thing worth noting is that it automatically takes care of leap year. So if you have 29 days in Feb, it will return 29/2. Also similar to above query replace SYSDATE with any other date column/value to find last day of that particular month.
SELECT TRUNC (LAST_DAY (SYSDATE)) "Last day of current month"
    FROM DUAL;

  • Get the first day of the Year

First day of year is always 1-Jan. This query can be use in stored procedure where you quickly want first day of year for some calculation.

SELECT TRUNC (SYSDATE, 'YEAR') "Year First Day" FROM DUAL;

  • Get the last day of the year

Similar to above query. Instead of first day this query returns last day of current year.

SELECT ADD_MONTHS (TRUNC (SYSDATE, 'YEAR'), 12) - 1 "Year Last Day" FROM DUAL

  • Get number of days in current month

Now this is useful. This query returns number of days in current month. You can change SYSDATE with any date/value to know number of days in that month.

SELECT CAST (TO_CHAR (LAST_DAY (SYSDATE), 'dd') AS INT) number_of_days
  FROM DUAL;

  • Get number of days left in current month

Below query calculates number of days left in current month.

SELECT SYSDATE,
       LAST_DAY (SYSDATE) "Last",
       LAST_DAY (SYSDATE) - SYSDATE "Days left"
  FROM DUAL;

  • Get number of days between two dates

Use this query to get difference between two dates in number of days.

SELECT ROUND ( (MONTHS_BETWEEN ('01-Feb-2014', '01-Mar-2012') * 30), 0)
          num_of_days
  FROM DUAL;

OR

SELECT TRUNC(sysdate) - TRUNC(e.hire_date) FROM employees;
Use second query if you need to find number of days since some specific date. In this example number of days since any employee is hired.


  • Display each months start and end date upto last month of the year

This clever query displays start date and end date of each month in current year. You might want to use this for certain types of calculations.

SELECT ADD_MONTHS (TRUNC (SYSDATE, 'MONTH'), i) start_date,
       TRUNC (LAST_DAY (ADD_MONTHS (SYSDATE, i))) end_date
  FROM XMLTABLE (
          'for $i in 0 to xs:int(D) return $i'
          PASSING XMLELEMENT (
                     d,
                     FLOOR (
                        MONTHS_BETWEEN (
                           ADD_MONTHS (TRUNC (SYSDATE, 'YEAR') - 1, 12),
                           SYSDATE)))
          COLUMNS i INTEGER PATH '.');

  • Get number of seconds passed since today (since 00:00 hr)

SELECT (SYSDATE - TRUNC (SYSDATE)) * 24 * 60 * 60 num_of_sec_since_morning
  FROM DUAL;

  • Get number of seconds left today (till 23:59:59 hr)

SELECT (TRUNC (SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_left
  FROM DUAL;

How to Make Own Java Framework

Today i am telling you how to make own java framework and i know that you may be curious about how framework works? A simple framework example will be made here to demonstrate the idea of frameworks.

Goal of a Framework
First of all, why do we need a framework other than just a normal library? The goal of framework is defining a process which let developers implement certain functions based on individual requirements. In other words, framework defines the skeleton and developers fill in the flash when using it.

In the following example, the first 3 classes are defined as a part of framework and the 4th class is the client code of the framework.

Main.java is the entry point of the framework. This can not be changed.
//imagine this is the entry point for a framework, it can not be changed
public class Main {
 public static void main(String[] args) {
  Human h = new Human(new Walk());
  h.doMove();  
 }
}
Move.java is the Hook. A hook is where developers can define / extend functions based on their own requirements.
public abstract class Move {
 public abstract void action();
}
Human.java is the Template, which reflects the idea of how the framework works.
public class Human {
 private Move move;
 
 public Human(Move m){
  this.move = m;
 }
 
 public void doMove(){
  this.move.action();
 }
}
This simple framework allows and requires developers to extend “Move” class. Actually, in this simple framework, action() method is the only thing developers are able to change.

Inside of the implementation, different “action” can be programmed to different purpose. E.g. the example below print “5 miles per hour”, of course, you can redefine it as “50 miles per hour”.
public class Walk extends Move {
 
 @Override
 public void action() {
  // TODO Auto-generated method stub
  System.out.println("5 miles per hour - it is slow!");
 }
}
Conclusion:
The example here just shows how a simple Template and Hook works. A real framework is more complicated than this. Not only does it contain other relations like template-temple relation, but also very complex process about how to efficiently improve performance and programming usability.

How to Use Drag and Drop in Android

In this Android tutorial, we shall see how to make it happen in an Android app.Drag and drop implementation uses events triggered by onLongPress or onTouch Android callback functions. The triggered events are handled by the set of listener classes and their corresponding callback functions. At low level, drag and drop is used to move data from one view to another.
Steps for Drag and Drop Implementation
  • Design Layout: Design layout that contains two or more bounding spaces and the view to be dragged.
  • Create Activity: Create activity which implements required listener classes.
  • Define Callbacks: Define call back functions onTouch() and onDrag().

Step 1. Design Layout
Need to create two or more bounding spaces.
Create Android views to be dragged between available bounding spaces.
First, open the xml file needed for the design. The bounding space is nothing but any view like Linear layout, Relative layout, listview or like such views. These views should be dragged from the left panel in the graphical layout. And then the dimensions are needed to be given for the width, height and padding attribute of the views to separate them from one another. Then, any views like TextView, ImageView or any other should be placed inside the bounding area. So when the user holds on to this view for little bit of time, the drag event will be triggered.
Step 2. Create Activity
In this step, an activity class should be created and let it to implement the required listener classes; for example, onLongClickListener or onDragListener and so on. These classes will be set to the view objects. This will be done in onCreate callback function. Because the listener classes are needed to be set to the view objects on launching the activity itself. Then only the system can dispatch the events to the listener classes during the drag.
Step 3. Define Callbacks
OnTouchListener and OnDragListener are the two interfaces that needs to be implemented. These two Android interfaces contain one method each, respectively onTouch and onDrag. We can even use OnLongClickListener, if so then the respective method to be implemented is onLongClick. For onTouch event, MotionEvent object and the View object should be sent as arguments. For onDrag event the DragEvent object and View object should be sent.
onTouch()

When the user presses the View to be dragged the methods like onTouch() or onLongClick() will be invoked by the Android runtime.

  • How do we pass meta data onDrag?

To achieve that, in the listener method implementation, a clip data should be created. It should have the data to be dragged and clip description. This clip data can be accessed on leaving the drag control using getClipData().

This clip data work is optional. If the use case requires to pass information, then this can be done. If created, the data will be sent via the startDrag() method. On invoking the startDrag(), the application will intimate the system about the start of the drag.

  • How do we show drag shadow?

Before calling startDrag a shadowBuilder object should be created. This class has two type constructors. One is a no argument constructor which will be called by View.DragShadowBuilder(). The another is the single argument constructor which holds the Android View object as its argument like View.DragShadowBuilder(view).

Based on the type of constructor call the shadow to be shown during the drag will differ. If the later constructor is used, then the shadow will be as like as the view on which the user made a long press. If the former constructor is used, then the shadow will not be shown on the screen.

After creating shadowBuilder object the startDrag method will be invoked. This method holds data, shadowBuilder object, local state and flags as its argument. Immediately the following two methods of shadow builder will be invoked one after another.

onProvideShadowMetrics() – It holds two arguments as dimensions and touch_point. Both are point objects. The dimension provides the width and height of the drag shadow and the touch_point points the drag position.
onDrawShadow() – This method will be invoked after onProvideShadowMetrics(). This method use the metrics provided by the above method and let the system to create the canvas object. Canvas is the only argument to this method to draw the shadow.
onDrag()

After the information about the start of the drag is intimated to the Android runtime, immediately it will allow the DragEventListener to handle the drag event using the onDrag() method. It holds two arguments as View and DragEvent object. On handling the drag event there are several possible actions. That action is returned by the method getAction(). This method can be invoked from the drag event object which is one of the argument of onDrag method.
Those actions have different states and they are listed as follows.
  • ACTION_DRAG_STARTED – This action will be returned after the startDrag method is invoked.
  • ACTION_DRAG_ENTERED – Whenever the Android View to be dragged enters into a new bounding space, this action will be returned.
  • ACTION_DRAG_LOCATION – This will be returned for each touch point during the drag. It holds the x,y coordinates of the drag position.
  • ACTION_DRAG_EXITED – Once the dragged view leave some bounding space or layout, then this action will be returned.
  • ACTION_DROP – Once the finger release the hold from drag, then this is returned.
  • ACTION_DRAG_ENDED – This action is the end of the Android drag and drop cycle. 
Download the Drag and Drop Code

Read RSS Feed in Java Using Feed Parser

Today i am telling you how to read rss feed in java using feed parser.RSS  stands for  Rich Site Summary or Really Simple Syndication .Feed4j.jar is a library for parsing RSS feeds.
There are 4 type of exception can be thrown while parsing RSS feed like

  1. FeedException
  2. FeedIOException
  3. FeedXMLParseException
  4. UnsupportedFeedException.
The Feed4j library is dependent on 4 other java libraries 
  1. dom4j-1.6.1.jar
  2.  nekohtml.jar 
  3. xercesImpl.jar
  4.  xml-apis.jar 


The Project Structure is as below :

The Java code for the feed parsing is TutorialSavvyRssFeedParser.java .
package com.sandeep.blog.parser;
 
import it.sauronsoftware.feed4j.FeedIOException;
import it.sauronsoftware.feed4j.FeedParser;
import it.sauronsoftware.feed4j.FeedXMLParseException;
import it.sauronsoftware.feed4j.UnsupportedFeedException;
import it.sauronsoftware.feed4j.bean.Feed;
import it.sauronsoftware.feed4j.bean.FeedItem;
import java.net.MalformedURLException;
import java.net.URL;
 
public class TutorialSavvyRssFeedParser {
 
 public static void main(String[] args) {
 
  URL url = null;
 
  Feed feed = null;
 
  try {
   /*RSS URL For Blog's Feed*/
   url = new URL("http://www.geekonjava.blogspot.com/feeds/posts/default?max-results=1000");
 
   feed = FeedParser.parse(url);
 
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (FeedIOException e) {
   e.printStackTrace();
  } catch (FeedXMLParseException e) {
   e.printStackTrace();
  } catch (UnsupportedFeedException e) {
   e.printStackTrace();
  }
 
  int items = feed.getItemCount();
   
  for (int i = 1; i <= items; i++) {
    
   FeedItem item = feed.getItem(i-1);
    
   System.out.println(i+" Title: " + item.getTitle());
    
  }
 
 }
 
}
Download the Demo Code

How to read and write JSON in Java

JSON means JavaScript Object Naming. In this example we are going to see a very nice JSON framwork, JSON.simple. It is a simple Java toolkit for JSON. You can use JSON.simple to encode or decode JSON text.

Features
  • Full compliance with JSON specification (RFC4627) and reliable.
  • Provides multiple functionalities such as encode, decode/parse and escape JSON text while keeping the library lightweight
  • Flexible, simple and easy to use by reusing Map and List interfaces
  • Supports streaming output of JSON text
  • Stoppable SAX-like interface for streaming input of JSON text.
  • Heap based parser
  • High performance.
  • No dependency on external libraries
  • Both of the source code and the binary are JDK1.2 compatible.

Note: You need to put the latest json-simple-1.1.1.jar in your CLASSPATH
Write JSON using Java
package com.javacodegeeks.java.core;

import java.io.FileWriter;
import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class JsonSimpleLibraryExample {

 private static final String jsonFilePath = "F:\\nikos7\\Desktop\\filesForExamples\\jsonFile.json";

 public static void main(String[] args) {

  JSONObject jsonObject = new JSONObject();

  jsonObject.put("URL", "www.geekonjava.blogspot.com");

  jsonObject.put("Site Name", "Geek On Java");

  jsonObject.put("Members", 120);

  JSONArray jsonArray = new JSONArray();

  jsonArray.add("Jack");
  jsonArray.add("James");

  jsonObject.put("Names", jsonArray);

  try {

   FileWriter jsonFileWriter = new FileWriter(jsonFilePath);
   jsonFileWriter.write(jsonObject.toJSONString());
   jsonFileWriter.flush();
   jsonFileWriter.close();

   System.out.print(jsonObject);

  } catch (IOException e) {
   e.printStackTrace();
  }

 }

}
Output:
jsonFile.json:
{"Site Name":"Geek On Java","Members":120,"URL":"www.geekonjava.blogspot.com","Names":["Jack","James"]}
Read JSON from Java
package com.javacodegeeks.java.core;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonSimpleLibraryExample {

 private static final String jsonFilePath = "F:\\nikos7\\Desktop\\filesForExamples\\jsonFile.json";

 public static void main(String[] args) {

  JSONParser jsonParser = new JSONParser();

  try {

   FileReader fileReader = new FileReader(jsonFilePath);

   JSONObject jsonObject = (JSONObject) jsonParser.parse(fileReader);

   String siteName = (String) jsonObject.get("Site Name");

   System.out.println("Site Name: " + siteName);

   long members = (long) jsonObject.get("Members");

   System.out.println("Members: " + members);

   String url = (String) jsonObject.get("URL");

   System.out.println("URL: " + url);

   JSONArray names = (JSONArray) jsonObject.get("Names");

   Iterator i = names.iterator();

   while (i.hasNext()) {

    System.out.println(" "+i.next());

   }

  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ParseException e) {
   e.printStackTrace();
  }

 }

}
Output:
Site Name: Geek On Java
Members: 120
URL: www.geekonjava.blogspot.com
 Jack
 James