Thursday, 12 June 2014

Textual description of firstImageUrl

Git : How to add commit in between old commits

I have a Git repository and need to rewrite my local history by inserting a new commit in between old commits.

More specifically my sitatution is like this:
  AB—BC—CD—EF   MASTER
and I wanted to come up with something like this:
  AB—BC—SA—CD—EF   MASTER
Where SA is my new commit i.e to be inserted b/w commit BC & CD.

Well, it isn’t actually an extreme or difficult case.It’s actually a very simple procedure to follow:
$ git checkout master
$ git checkout -b temp BC 
$ git add
$ git commit # your changes that will be SA
Now your Repo will look like this :
  AB—BC—SA  temp
      \
      CD—EF MASTER
After this repository layout it’s rather simple to transform it into a single sequence of commits:
 $ git rebase temp master
You may get few conflicts that you need to resolve .

  Now you are all Done !!!

TAGGING COMMITS


You will notice that your SHA keys are modified and tag doesn't appear above commit BC to make sure your tags are in line follow the steps:
 $ git tag -l #to list all your tags.
For each tag type the following command,
 $ git show TAG_NAME
to see the details of the old commit.

Make note of the subject line, date, and hash of the old commit.
Page through git log looking for that subject line and date. Make note of the hash of the new commit when you find it.
 $ git tag --force TAG_NAME NEW_COMMIT_HASH #to update the tag.
Hope that you have not mistaken one commit for another with a similar subject line and date.

Thanks to Santosh Mohanty for writing this post .

Post Comments And Suggestions !!!

Monday, 9 June 2014

Textual Representation of logo

Validate XML against XSD in Java

Here's the sample java program which will validate xml file against a particular schema file .

import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;


public class XmlValidator
{
 public static void main(String[] args)
 {
  try {
      

      SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

      Schema sch= schemaFactory .newSchema(new StreamSource("D:\\example.xsd"));
      Validator validator = sch.newValidator();

      validator.validate(new StreamSource("D:\\example.xml"));
      
      System.out.println("Successfully validated");

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

Thursday, 22 May 2014

Textual description of firstImageUrl

How to Limit No Of Files in Mule File Connector

File Connector is very important and useful utility provided by MULE ESB . We can use this to monitor a directory , and process the files as it comes in directory . But , if there are hundreds files pumped in the source directory , mule tries to load all of them by creating different threads . To control the number of files , mule can read once , we have to write our own custom File Receiver .

First , change your file connector in xml , to use custom file receiver :
<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:file="http://www.mulesoft.org/schema/mule/file" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" version="CE-3.3.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd 
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd 
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd ">
 <file:connector name="myFileConnector" >
 <service-overrides messageReceiver="InputFileMessageReceiver"/>
 </file:connector>

    <flow name="fileInboundTestFlow1" doc:name="fileInboundTestFlow1">
        <file:inbound-endpoint path="E:/fileTest" responseTimeout="10000" doc:name="File" pollingFrequency="5000" connector-ref="myFileConnector"/>
        <byte-array-to-object-transformer doc:name="Byte Array to Object"/>
    </flow>
</mule>


Use Byte-Array-To-Object-Transformer carefully as it loads the full file in memory , it might create Out Of Memory Error if the file is too large .

And here is our custom file receiver which will allow only two files at a time .
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.mule.api.construct.FlowConstruct;
import org.mule.api.endpoint.InboundEndpoint;
import org.mule.api.lifecycle.CreateException;
import org.mule.api.routing.filter.Filter;
import org.mule.api.transport.Connector;
import org.mule.transport.ConnectException;
import org.mule.transport.file.FileConnector;
import org.mule.transport.file.FileMessageReceiver;

/**
 * Created.
 * User: Abhishek Somani
 * Date: 14/05/2014
 * Time: 2:19 PM
 */
public class InputFileMessageReceiver extends FileMessageReceiver {
    
    private int maxFiles = 2;

    public InputFileMessageReceiver(Connector connector, FlowConstruct flowConstruct, InboundEndpoint endpoint, String readDir, String moveDir, String moveToPattern, long frequency) throws CreateException, ConnectException, IOException {
        super(connector, flowConstruct, endpoint, readDir, moveDir, moveToPattern, frequency);
    }
    
    protected void basicListFiles(File currentDirectory, List<File> discoveredFiles)
    {
        File[] files;
        Filter filter = endpoint.getFilter(); 
        if ( filter instanceof FileFilter)
        {
            files = currentDirectory.listFiles((FileFilter)filter);
        }
        else if(filter instanceof FilenameFilter)
        {
            files = currentDirectory.listFiles((FilenameFilter)filter);
        }
        else
        {
         files = currentDirectory.listFiles();
        }

        // the listFiles calls above may actually return null (check the JDK code).
        if (files == null)
        {
            return;
        }

        for (File file : files)
        {
            if (!file.isDirectory())
            {
                discoveredFiles.add(file);
                if(discoveredFiles.size() >= maxFiles)
                 return ;
            }
            else
            {
                if (((FileConnector)connector).isRecursive())
                {
                    this.basicListFiles(file, discoveredFiles);
                }
            }
        }
    }

}

So this is how we can limit the number of file to be processed by Mule File Connector .


Post Comments And Suggestions !!!


Wednesday, 21 May 2014

Textual description of firstImageUrl

How To Improve Performance Of ROR Application

Top Ten Ways to Speed Up Your ROR Application:

Session Storage: Choose your session storage carefully according to your need. Here are what rails provide:

      CookieStore– Stores everything on the client.

       DRbStore– Stores the data on a DRb server.

      MemCacheStore – Stores the data in a memcache.

       ActiveRecordStore – Stores the data in a database using Active Record.

•DRY (Don’t repeat yourself ): Programmers tend to listen and don’t follow this basic principle.
e.g: Novice Way
if(Student.find_by_id(params[:id]).name == " Santosh")
return Player.find_by_id(params[:id])
else
return nil
end


Experienced Way :
student = Student.find_by_id(params[:id])
if(student.name == "Santosh") ?  student : nil


STI :Use STI(Single Table Inheritance) wherever needed which Dries up your Model. Single Table Inheritance is, as the name suggests it, a way to add inheritance to your models. STI lets you save different models inheriting from the same model inside a single table.

For example, let’s say you have an employee model. The employees can be of two types : manager or developer. They pretty much share the same attributes and columns. However, their behavior should be different. Creating two tables having the exact same fields would be bad.

Slim/Thin Controller: Thin controllers are easy to test and has good performance profile because there’s some overhead involved in passing the controller instance variable around. In short, you need to follow “Thin controller and slim model .

Use Of Partials : Use of partials help to cache your web pages content/component easily. You can also thread your views to render data's parallely.

Eager loading : Eager loading is a way to solve the classic N + 1 query performance problem caused by inefficient use of child objects.
Have a look at the following Code: It will fetch account of 100 users.
users = User.all(:limit => 100)
users.each do |user|
puts user.bank_details.accounts
end


Hence, 101 queries will be executed, 1 for the top and 100 for rest. The solution is to rewrite it to eager load accounts.
users = User.includes(:bank_details).limit(100)
users.each do |user|
puts user.bank_details.accounts
end
You can use bullet gem, a cool Gem to kill N + 1 query problem.

DB Indexing :Database indexing is one of the simplest ways to improve database performance. The insert operation will become slower but will boost up fetching data which is more frequently used in web application.

Note: Always Index Primary and Foreign keys, Never Index columns that frequently gets updated.

Avoid unnecessary Dynamic Programming

Rails Batch Finders (find_by and find_all_by) dynamic methods are really cool, the are also kind of slow because each one needs to run through method_missing and parse the filename against the list of columns in database table.

Anyways in production mode it works fine once it caches your queries.

Caching: This is the one of the best way to speed up a rails application.Types of caching:
       Page Caching
      Action Caching
      Fragment Caching:
      SQL Caching
      Asset caching


Image spriting : In websites, a significant times are consumed for loading large number of images. One way of minimizing is to sprite your images. This will reduce number of images to be served significantly.

Minify and GZip your assets(JS & CSS Lib): You can reduce size of the stylesheets and javascripts significantly by Minifying it and serve as GZip format. It will improve the performance significantly by reducing request/response time.

Use CDN for Non Commercial Sites : CDN also known as content delivery network is an interconnected system of computers on the Internet that provides Web content rapidly to numerous users by duplicating the content on multiple servers and directing the content to users based on proximity. When, concurrent users will come to your site, using CDN rather than serving asset (like image, javascript, stylesheets) from your server will boost up performance.
You can try CDN from Amazon Cloudfront or Rackspace cloud files.

Use of Proper Application Server : Never use WEBrick or thin server for running your application in production mode as they don’t generate concurrent running processes.

UNICORN is the better choice as the processes are managed by unix rather than Ruby JVM .

Thanks to Santosh for writing this post .

Post Comments And Suggestions !!

Friday, 9 May 2014

Textual description of firstImageUrl

How To Remove Annoying trailing white space

There is no reason to leave trailing white-space characters in your project's files, so don't add some.

A git diff will usually highlight them and you should not commit when you see them. So go ahead and switch your editor/IDE to automatically remove them for you. Below are a few instructions on how to get them removed by your favorite IDE or editor.

Note that except for Older Version of RubyMine(v <= 5.4.3 ), the following changes will remove trailing white-space on all lines, not only those that you changed. While this should not be a problem if your project is always clean of trailing spaces, it may not be what you want if you are in the wild west.

In that case you need to take care not to commit trailing spaces. Always git diff, kids!

RubyMine :
• Settings (Ctrl-S)
• Pick "Editor" (in the "IDE Settings" section)
• In the bottom left, set "Strip trailing white spaces on Save" to "Modified Lines"

Vim:

• Open up your ~/.vimrc file
• Add this:
autocmd BufWritePre * :%s/\s\+$//e


TextMate

• The Text bundle offers a command Remove Trailing Spaces in Document/Selection.
• In the bundle editor, assign it a shortcut like Cmd + Alt + Backspace.
• Update: Since 9-29-2012, TextMate2 has a callback will-save. In the above command, set 'Semantic class' to callback.document.will-save, and it will be called before saving the document.

If that is too invasive for you, try only highlighting trailing spaces like suggested in the Vim wiki (also put this into your ~/.vimrc):
Show trailing whitepace and spaces before a tab:
:highlight ExtraWhitespace ctermbg=red guibg=red
:autocmd Syntax * syn match ExtraWhitespace /\s\+$\| \+\ze\t/


Git:

• There is a thread on Stackoverflow about a git pre-commit hook.
To use it, add the following to .git/hooks/pre-commit.
#!/bin/sh
#

# A git hook script to find and fix trailing whitespace
# in your commits. Bypass it with the --no-verify option
# to git-commit
#

if git-rev-parse --verify HEAD >/dev/null 2>&1 ; then
  against=HEAD
else
  # Initial commit: diff against an empty tree object
  against=er4433dd
fi
# Find files with trailing whitespace
for FILE in `exec git diff-index --check --cached $against -- | sed '/^[+-]/d' | (sed -r 's/:[0-9]+:.*//' > /dev/null 2>&1 || sed -E 's/:[0-9]+:.*//') | uniq` ; do
  # Fix them!
  (sed -i 's/[[:space:]]*$//' "$FILE" > /dev/null 2>&1 || sed -i '' -E 's/[[:space:]]*$//' "$FILE")
  git add "$FILE"
done

# Now we can commit
exit

Thanks to Santosh for writing this post .

Post Comments And Suggestions !!

Textual description of firstImageUrl

Out Of Memory Error In Java

A Simple Example of creating Out Of Memory Error in a Java Program . It is an Error , so you can catch it also .
import java.util.*;


public class OutOfMemoryTest
{
 public static void main(String[] args)
 {
  try
  {
   LinkedList list = new LinkedList();
   while(true)
   {
    list.add(new Object());
   }
  }
  catch(Throwable e)
  {
   System.out.println("caught it ");
  }
  
  
 }
}



Tuesday, 29 April 2014

Textual description of firstImageUrl

MongoDB Integration with RAILS

This blog post lists step by step instructions for integrating MongoDB in RAILS Application .

STEP 1:

To create application with Mongo db you need to skip active record.
Type command
rails new app_name -–skip-active-record 
STEP 2:

Before bundle install make sure that you have included following gems in your gemfile.

gem 'mongoid'
gem 'bson_ext'
run bundle intsall
IF any problem occurs during bundle installation remember dependencies of mongoid should be of same version.Otherwise it will give error while installing bundle.

Now you can see that dependencies of gem 'mongoid' are of same version in snapshot. gem 'mongo' '1.6' gem 'bson' '1.6' gem 'bson_ext' '1.6' STEP 3:

Now run the server check whether connection established with mongoid.











Mongoid.yml is not found.



STEP 4:

Let's create mongoid.yml file .


rails g mongoid:config
















STEP 5:

Let's generate scaffold,here we dont need to mention skip active record though it is already mentioned. Type command
rails g scaffold article name:string content:text 
When you will check your model you will find instead of
 class Article<ActiveRecord::Base
 end
class Article
          include Mongoid::Document
end
Now instead of generating migration we will write fields in model itself.
class Article
          include Mongoid::Document
field :name,:type => String
end
No need of migration file in mongo db.










Now Start the Server .

STEP 5:

Validation and Association Validation is same as it was in ActiveRecord but Associations is slightly different.Some new association are introduced.

embeds_many and embedded_in,embeds_one and embedded_in,references_many and referenced_in,references_one and referenced_in and associations used in active record.


Post Comments And Suggestions !!!

Thanks to Santosh for writing this post .


Tuesday, 1 April 2014

Textual description of firstImageUrl

How To Fix jQuery msgBox IE Security Warning Error

jQuery MsgBox is a jQuery plugin highly configurable to replace the basic functionality provided by the standard javascript alert(), confirm(), and prompt() functions.

BROWSER COMPATILITY:

Firefox,Chrome,Safari,Opera , IE > 7

But for IE Version 8 it throws a security warning error as it loads & Removes the div with background image using background-url which is a know bug in IE *


Solution :


Remove the Background Image Url and use CSS instead.

Replace Line 167 of Plugin or Overide the Show method of Plugin:
divMsgBox.css("background-image", "url('"+msgBoxImagePath+"msgBoxBackGround.png')");
with
divMsgBox.css("background-color", "#FFFFFF"); 
For Auto Scroll Modify the CSS with :
div.msgBoxContent 
{ 
    font-size:11pt; 
    margin:0 3px 6px 3px; 
    display:inline-block; 
    float:left; 
    height:90px; 
    width:319px; 
    overflow-y: auto; 
}
For Full Functionality with JS and CSS Visit this fiddle

Post Comments And Suggestions !!

Tuesday, 25 March 2014

Textual Representation of logo

How to Make String Palindrome

Problem : Write a program to find whether the string is a palindrome or not.
If it is palindrome, return empty string. If it is not, return the minimum length string which should be appended at the end of it to make it palindrome.

public class PalindromeTest
{
 public String palindrome(String s)
 {

  char[] input = s.toCharArray();

  int start = 0;
  int end = input.length - 1;

  if (isPalindrome(input, start, end))
   return "";
  else
  {
   start++;
   while (start < end)
   {
    if (isPalindrome(input, start, end))
    {
     break;
    }
    start++;

   }
   char[] toReturn = new char[start];
   for (int i = 0; i < toReturn.length; i++)
   {
    toReturn[i] = input[--start];
    //start--;
   }
   return new String(toReturn);

  }

 }

 public boolean isPalindrome(char[] input, int start, int end)
 {
  boolean isPalindrome = true;
  while (start < end)
  {
   if (input[start] != input[end])
   {
    isPalindrome = false;
    break;
   }
   start++;
   end--;
  }
  return isPalindrome;

 }
 
 public static void main(String[] args)
 {
  
  PalindromeTest test = new PalindromeTest();
  System.out.println(test.palindrome("NITI"));
  System.out.println(test.palindrome("aaab"));
  System.out.println(test.palindrome("abb"));
  System.out.println(test.palindrome("abc"));
  System.out.println(test.palindrome("abcde"));
  System.out.println(test.palindrome("abcaba"));
  System.out.println(test.palindrome("system"));
  
  
  
 }

}


Tuesday, 18 March 2014

Textual description of firstImageUrl

How To Fix IE 8 Warning For HTTPS Connections

When Your web application is running on HTTPS then you might get an annoying warning like this in Internet Explorer . Internet Explorer will give you warning like this :

Do You Want to view Only the webpage content that was delivered securly ?

This webpage contains contents that will not be delivered using a secured HTTPS connection , which could compromise the security of entire web page.










This warning occur because one or more resources in your web page are accessed via HTTP protocol while the parent page is loaded through HTTPS . The resource may be a image , js , css or anything .


This warning may be removed by doing some setting in internet explorer , but that is not a good solution because you don't expect your client to do that job .

The other option is , to make every resource in your web page to be accessed via HTTPS only . To know which resources of your web pages are accessed via HTTP , you need to install a HTTPWATCH tool .

This tool will give you all the information about the resources getting loaded . From this you can find out what all resources are getting loaded via HTTP , and then you can fix these resources .

















Update : This error can also occur if the web page script calls removeChild on a div which references a background image
You can read more about this on this security warning in Internet Explorer. This error occurs on IE 6 , IE 7 and earlier versions of IE 8 .


You can refer to this link to fix this error when using JQuery MsgBOX. Post Comments And Suggestions !!

Wednesday, 29 January 2014

Textual description of firstImageUrl

Egit Error Unchanged Files Marked As Changed

While Working with EGit in eclipse, i have faced a problem where some files are not changes but still showing as changed . When I tried to commit the changes , all the unchanged files also get listed in commit dialog .When I compare this with head revision , there was no changes .


The solution to this problem was simple , just go to preference then git configuration and add property core.autocrlf with false .

Wednesday, 13 November 2013

Textual description of firstImageUrl

How to Send email using mule

Sending Email using mule is very easy by using SMTP Outbound End Point . Here is a sample mule application to send mail. To use gmail network to send mails , you have to use gmail smtp connector , otherwise you will get tls errors .
<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:smtp="http://www.mulesoft.org/schema/mule/smtp" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" version="CE-3.3.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd 
http://www.mulesoft.org/schema/mule/smtp http://www.mulesoft.org/schema/mule/smtp/current/mule-smtp.xsd 
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd 
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd ">
 <smtp:gmail-connector name="gmail" />

    <flow name="mailTestFlow1" doc:name="mailTestFlow1">
        <http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8081" doc:name="HTTP" 
        path="sendMail"/>
        <component doc:name="Java" class="Component1"/>
        <smtp:outbound-endpoint host="smtp.gmail.com" port="587" 
        user="yourEmailAddress%40gmail.com" password="pass" to="javaroots@gmail.com" 
        from="Abhishek Somani" subject="Testing mule" responseTimeout="10000" connector-ref="gmail" doc:name="Send notification email"/>
    </flow>
</mule>
use %40 instead of @ in user field ,otherwise you might get error like this :
ERROR 2013-10-10 15:02:20,702 [main] org.mule.module.launcher.application.DefaultMuleApplication: null
org.mule.api.endpoint.MalformedEndpointException: The endpoint "smtp://yourEmailAddress@gmail.com:pass@smtp.gmail.com:587" is malformed and cannot be parsed.  If this is the name of a global endpoint, check the name is correct, that the endpoint exists, and that you are using the correct configuration (eg the "ref" attribute).  Note that names on inbound and outbound endpoints cannot be used to send or receive messages; use a named global endpoint instead.
 at org.mule.endpoint.UserInfoEndpointURIBuilder.setEndpoint(UserInfoEndpointURIBuilder.java:34)
 at org.mule.endpoint.AbstractEndpointURIBuilder.build(AbstractEndpointURIBuilder.java:55)
 at org.mule.endpoint.MuleEndpointURI.initialise(MuleEndpointURI.java:223)
 at org.mule.endpoint.AbstractEndpointBuilder.doBuildOutboundEndpoint(AbstractEndpointBuilder.java:246)
 at org.mule.endpoint.AbstractEndpointBuilder.buildOutboundEndpoint(AbstractEndpointBuilder.java:122)
 at org.mule.endpoint.DefaultEndpointFactory.getOutboundEndpoint(DefaultEndpointFactory.java:89)
 at org.mule.config.spring.factories.OutboundEndpointFactoryBean.doGetObject(OutboundEndpointFactoryBean.java:50)
 at org.mule.config.spring.factories.AbstractEndpointFactoryBean.getObject(AbstractEndpointFactoryBean.java:43)

......
it is a known Bug .

Here is the component class where you can set your email body .
import org.mule.api.MuleEventContext;
import org.mule.api.lifecycle.Callable;


public class Component1 implements Callable{


 @Override
 public Object onCall(MuleEventContext eventContext) throws Exception {
  eventContext.getMessage().setPayload("This is email Body ");
  return eventContext.getMessage();
 }

}



If you want to send html multimedia mails , use content type field in smtp or gmail connector like this :
<smtp:connector name="smtpConnector" contentType="text/html" />

Setting mimeType on smtp outbound endpoint will have no impact , unless you set contentType property on smtp connector.


Thursday, 24 October 2013

Textual description of firstImageUrl

How to use Exdp and Impdp over Network Link : Oracle DB

We have different enviornment like test , dev , and prod and data on these enviornment is different .Many Times , we want to have exactly the same data of production in to dev enviornment . For this , we need to export the data on production server and import and overwrite the data in development server . Oracle provides expdp and impdp utilities for transferring the data .Oracle Data Pump is a newer, faster and more flexible alternative to the "exp" and "imp" utilities used in previous Oracle versions. In addition to basic import and export functionality data pump provides a PL/SQL API and support for external tables.

In this post , we will create a export dump of remote database on our local system . The remote database ,whose data needs to be exported, let's call it targetdb . Here are the steps needs to be taken to create a exported dump file on our local machine .
First login as sysdba on your local database .

#Login in sqlplus 
sqlplus / as sysdba
Then create a public connection link for the remote database .
#Create a connection link for the database which you want to export 
create database link remotelink connect to targetdbuser identified by targetdbpassword using 'hostname:port/sid'
#check connection 
select * from dual@remotelink
Now create a local directory on your file system , and map it to your local oracle db like this :
# create a local directory where the dump file will be stored and map it to your database dir by creating 
create directory dumpdir as 'C:/Users/abhishek/dump';
# give permission to local user by whom we will be running expdp
GRANT read, write ON DIRECTORY dumpdir TO localdb;
# check if the dir is created 
 select directory_name, directory_path from dba_directories ;
You might get following error , if you do not grant read write access of directory to the user .
ORA-39002: invalid operation
ORA-39070: Unable to open the log file.
ORA-39087: directory name dumpdir is invalid
Now run the expdp command with specifying the directory , network link and other parameters . We are exporting a particular schema here .
expdp userid=localdb/localdb@//localhost:1521/ORCL dumpfile=testdump.dmp logfile=testdump.log SCHEMAS=myschema directory=dumpdir 

You might get error like this :
ORA-31631: privileges are required
ORA-39149: cannot link privileged user to non-privileged user
This error occurs because target database user should have exp_full_database privilege for exporting data over network link.So give the privilege for remote user , by logging in as remote user sysdba and grant access .
GRANT EXP_FULL_DATABASE to targetdbuser;
Now to import the data on your local database . Run the following command :
impdp myschema/mytest@//localhost:1521/orcl schemas=myschema directory=dumpdir dumpfile=testdump.dmp logfile=impdpnewtest1.log 
You might get error like this :
ORA-39154: Objects from foreign schemas have been removed from import
ORA-31655: no data or metadata objects selected for job
And no data imported in your schema . To resolve this , you have to give the following privilege to the local user , where you are importing the schema .
grant imp_full_database to myschema ;
This import will create the schema imported , if it is not available in local database. If the schema is already present in your local db , it will try to import tables in it . If the tables are already present in the schema , it will skip importing those tables . To overwrite all the tables , you have to add paramter TABLE_EXISTS_ACTION=REPLACE in impdp command . It will truncate the tables , and create new one with the dump file .

Here is a nice read comparing different approaches like , exp , expdp and expdp over network link and security issues regarding these.

Source 1
Source 2
Source 3
Source 4



Post Comments and Suggestions !!

Monday, 21 October 2013

Textual description of firstImageUrl

Validation Query in DBCP : When And Why

Configuring Database Connection Pool is very simple by using Commons DBCP and explained in my previous post . There are some other important properties available which we need to keep in mind while creating connection pool. Like Init sqls and validation queries . Validation queries are used to validate connections in the pool .


Database Connection pool maintains alive connections (already opened and being used ) , idle connections(opened but not in use ) and closed connection. When a database is restarted , all connections in the pool becomes broken connections . So it is very important to check for the validity of connection while borrowing it from pool .


To Check for whether the connection is valid or not , we have validation query , which get fired if we specify the validation query along with other flags . There are three flags available for this :

testOnBorrow : Default value is true for this . If this is enabled , then whenever we get a connection from pool , validation query is fired . If the connection is broken , that connection will be dropped and new connection will be borrowed .

testOnReturn: Default value is false . Validation query is fired while returning the connection to the pool .

testWhileIdle : Default value is false.Validation query is fired while getting the idle connection from the pool .

All these flags first check whether validation query is set or not . If there is no validation query , then these flags will have no impact .


If you do not use these validation query , and if the database is restarted while your application is running , you might get error like this :

java.sql.SQLException: No more data to read from socket
 at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1157)
 at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:290)
 at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)


There are different validation queries defined for various databases . You can check the full list here . For oracle , the validation query is :
select 1 from dual
This may impact your overall performance also , because everytime a connection is made , one more query is fired . So use this wisely .

Source

Sunday, 20 October 2013

Textual description of firstImageUrl

Send Jersey Response to other flows in Mule 3.3

Creating Rest Web Services in mule is very easy and explained in previous post Now If you want to preserve the rest response in your flow , or apply some checks on it or send it to other flows , you will write following java code to do this :
//If you want to transform or send the request from your jersey component to next resource/flow then you need to use
ContainerResponse cr = (ContainerResponse) eventContext.getMessage().getInvocationProperty("jersey_response");
String messageString = (String) cr.getResponse().getEntity();
message.setPayload(messageString);
//remove this property 
eventContext.getMessage().removeProperty("jersey_response",PropertyScope.INVOCATION);
This code will convert org.mule.module.jersey.MuleResponseWriter$1 type to String, which you can forward to your next resource. If you don't do that , you might get exception like this :


Message               : java.io.NotSerializableException: com.sun.jersey.spi.container.ContainerResponse (org.apache.commons.lang.SerializationException). Message payload is of type: String
Code                  : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. com.sun.jersey.spi.container.ContainerResponse (java.io.NotSerializableException)
  java.io.ObjectOutputStream:-1 (null)
2. java.io.NotSerializableException: com.sun.jersey.spi.container.ContainerResponse (org.apache.commons.lang.SerializationException)
  org.apache.commons.lang.SerializationUtils:111 (null)
3. java.io.NotSerializableException: com.sun.jersey.spi.container.ContainerResponse (org.apache.commons.lang.SerializationException). Message payload is of type: String (org.mule.api.MessagingException)
  org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor:35 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/MessagingException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
java.io.NotSerializableException: com.sun.jersey.spi.container.ContainerResponse
        at java.io.ObjectOutputStream.writeObject0(Unknown Source)
        at java.io.ObjectOutputStream.writeObject(Unknown Source)
        at org.apache.commons.collections.map.AbstractHashedMap.doWriteObject(AbstractHashedMap.java:1182)
    + 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
******************************************************************************** 

Post Comments and Suggestions !!

Thursday, 10 October 2013

Textual description of firstImageUrl

How to read zip file in java

java Program to unzip a zip file .
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnzipExample {

 public static void main(String[] args) throws IOException {

  String inputZipFilePath = "C:\\Downloads\\Office.zip";

  String outputFileDir = "C:\\Downloads\\Office";
  byte[] buffer = new byte[1024];

  File outputDir = new File(outputFileDir);

  if (!outputDir.exists())
   outputDir.mkdir();

  ZipInputStream zin = new ZipInputStream(new FileInputStream(new File(
    inputZipFilePath)));

  ZipEntry next = zin.getNextEntry();

  while (next != null) {
   String name = next.getName();
   File fileToWrite = new File(outputFileDir + File.separator + name);
   //create directory structure
   new File ( fileToWrite.getParent()).mkdirs();
   FileOutputStream fos = new FileOutputStream(fileToWrite);

   int len;
   while ((len = zin.read(buffer)) > 0) {
    fos.write(buffer, 0, len);
   }
   
    fos.close();   
             next = zin.getNextEntry();

  }
  zin.closeEntry();
     zin.close();
 
     System.out.println("Unzip File Completed");

 }

}


Post Comments And Suggestions !!



Friday, 27 September 2013

Textual description of firstImageUrl

How to Set Default Schema In Oracle Using Commons DBCP

We need to specify schema name explicitly if the schema owner is different than the user by which we are logging in to database .This case is very common in production where schema is created by someone else , and you are provided separate user name and credentials to access the schema .

First we create a user schema_owner , which will create a table called TEST_TAB , and now this user will create another user called app_user , and grants him read, write access .Here is the script :
// done by sysdba
-- Schema owner.
CREATE USER schema_owner IDENTIFIED BY owner
  DEFAULT TABLESPACE users
  TEMPORARY TABLESPACE temp
  QUOTA UNLIMITED ON users;
  
GRANT CONNECT, CREATE TABLE TO schema_owner;

-- Application user.
CREATE USER app_user IDENTIFIED BY user
  DEFAULT TABLESPACE users
  TEMPORARY TABLESPACE temp;

GRANT CONNECT, CREATE SYNONYM TO app_user;

CREATE ROLE schema_rw_role;

GRANT schema_rw_role TO app_user;

//// Done by schema_owner

CREATE TABLE test_tab (
  id          NUMBER,
  description VARCHAR2(50),
  CONSTRAINT test_tab_pk PRIMARY KEY (id)
);

GRANT SELECT, INSERT, UPDATE, DELETE ON test_tab TO schema_rw_role;

/// done by app_user
SELECT * FROM SCHEMA_OWNER.test_tab;

insert into SCHEMA_OWNER.test_tab values (1,'abhishek');
commit;


Now if you want to use SCHEMA_OWNER with user APP_USER , you have to set default schema in your Connection. For this , we can use setConnectionInitSqls , which will fire the query everytime a connection is requested from the pool . Here is the code to set Default Schema in Commons DBCP .If you do not set the default schema , you will not be able to access test_tab from app_user.

package com.datamigration.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.dbcp.BasicDataSource;

/**
 * 
 * 
 * @author Abhishek Somani
 * 
 */
public class DataBase {
 
 private String driverClassName ;
 private String userName;
 
 private String password;
 
 private static int MAX_ACTIVE= 10;
 
 private String url;
 
 String SET_DEFAULT_SCHEMA="ALTER SESSION SET CURRENT_SCHEMA=SCHEMA_OWNER";
 private BasicDataSource ds = null;
 
 public void init() throws SQLException
 {
  ds = new BasicDataSource();
  ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
  ds.setPassword("user");
  ds.setUsername("app_user");
  ds.setUrl("jdbc:oracle:thin:@localhost:1521:ORCL");
  ds.setMaxActive(MAX_ACTIVE);
  List initSqls = new LinkedList();
  initSqls.add(SET_DEFAULT_SCHEMA);
  ds.setConnectionInitSqls(initSqls);
  //check connections
 }
 
 
 public Connection getConnection() throws SQLException
 {
  return ds.getConnection();
 }


 public String getDriverClassName() {
  return driverClassName;
 }


 public void setDriverClassName(String driverClassName) {
  this.driverClassName = driverClassName;
 }


 public String getUserName() {
  return userName;
 }


 public void setUserName(String userName) {
  this.userName = userName;
 }


 public String getPassword() {
  return password;
 }


 public void setPassword(String password) {
  this.password = password;
 }


 public String getUrl() {
  return url;
 }


 public void setUrl(String url) {
  this.url = url;
 }
 
 public static void main(String[] args) throws SQLException {
  
  DataBase db = new DataBase();
  db.init();
  Connection con = db.getConnection();
  String SELECT_BY_NAME="select * from TEST_TAB where id=?";
  PreparedStatement stmt = con.prepareStatement(SELECT_BY_NAME);
  stmt.setInt(1,1);
  ResultSet rs = stmt.executeQuery();
  if(rs.next())
  {
   System.out.println(rs.getString("description"));
  }
  
  
 }

}



In hibernate , we are given default_schema property to set default schema .


Post Comments and Suggestions !!


Source



Monday, 23 September 2013

Textual description of firstImageUrl

Remove File History In GIT

Problem :


If you have a connection config file , where you have your admin password or other sensitive information . If you commit this file accidently in git , it will show in the history , even if you remove it later . To Complete remove the committed file from git , you need to run this command
git filter-branch --force --index-filter "git rm --cached --ignore-unmatch ${full path to your file}" --prune-empty --tag-name-filter cat -- --all
and push the changes to remote branch . Now all the history related to this file will be deleted . Post Comments and Suggestions !!

Textual description of firstImageUrl

Java Program To Convert Duration in Milliseconds To HH:MM:SS Format

This Java Program Converts duration in MilliSeconds to "HH:MM:SS" format .
import java.util.concurrent.TimeUnit;

public class MiliSecondsConverter {
 public static void main(String[] args) throws InterruptedException {

  long millis = System.currentTimeMillis();
  Thread.sleep(5000);
  millis = System.currentTimeMillis() - millis;

  
  System.out.println(new MiliSecondsConverter().convert(millis));
 }
 
 public String convert(long miliSeconds)
 {
  int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
  int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
  int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
  return String.format("%02d:%02d:%02d", hrs, min, sec);
 }
}
Post Comments !!

Friday, 13 September 2013

Textual description of firstImageUrl

Jersey Rest Service : Stream Already Closed Error

Creating File Upload functionality in WebServices using Jersey is very simple , you can go through this post to create file upload functionality in Jersey Rest Service. However , you may get an exception like this , if you are using Buffered Reader to read the uploaded file stream.
 java.lang.IllegalStateException: Stream already closed
 at org.jvnet.mimepull.DataHead$ReadMultiStream.fetch(DataHead.java:237)
 at org.jvnet.mimepull.DataHead$ReadMultiStream.read(DataHead.java:212)
 at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
 at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
 at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
 at java.io.InputStreamReader.read(InputStreamReader.java:184)
 at java.io.BufferedReader.fill(BufferedReader.java:154)
 at java.io.BufferedReader.readLine(BufferedReader.java:317)
 at java.io.BufferedReader.readLine(BufferedReader.java:382)

This is a known issue in mimepull version 1.6 , which we are using along with jersey multi part jar . Try using mimepull version 1.9 and you will not see this error any more .

Jersey Multipart 1.6 depends on MimePull 1.4 . First exclude the 1.4 and include this dependency explicitly like this :
<dependency>
   <groupId>com.sun.jersey.contribs</groupId>
   <artifactId>jersey-multipart</artifactId>
   <version>1.6</version>
   <exclusions>
 <exclusion>
    <groupId>org.jvnet</groupId>
    <artifactId>mimepull</artifactId>
 </exclusion>
   </exclusions>
</dependency>
<dependency>
 <groupId>org.jvnet.mimepull</groupId>
 <artifactId>mimepull</artifactId>
 <version>1.9</version>
</dependency>

Post Comments and Suggestions !!