Open Mind, Open Source…

Latest

How to sftp in java using jsch : Example

Hi,

Well i got some interesting work today. Transfer a file from a machine to another using java. From last couple of months i was working on uploading  the excel files using UI, which is quite easy and for me just some hours of work. But this time i need to upload a file on server and after finish of upload, need to transfer it to another machine which will consume it. Quite interesting stuff cause was exhausted by doing the same stuff, excel file upload and UI from last 2 or 3 mnths.

Well to do this i Google some key words and found using Java Secure Channel jsch library we can do it easily in JAVA. It is also used by  ANT, Eclipse, NetBeans and some other big projects. Then i thought to give it a try  and wrote a Util class for my project using jsch. I added copy, and move methods in class for copy the file (without deleting the original location) and to Move the file (After copying delete the original file) respectively. You need to download and add  jsch.jar  file in ur classpath.

Below is the code i wrote for my sftp util class, use it share it and enjoy the coding.

package com.maddy.util;

import java.io.File;
import java.io.FileInputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SftpUtility {

private String sftpHost ;
private int    sftpPort ;
private String sftpUser ;
private String sftpPassword ;
private String sftpDir ;

public SftpUtility(String sftpHost, int sftpPort, String sftpUser,
String sftpPassword, String sftpDir) {
super();
this.sftpHost = sftpHost;
this.sftpPort = sftpPort;
this.sftpUser = sftpUser;
this.sftpPassword = sftpPassword;
this.sftpDir = sftpDir;
}

public String getSftpHost() {
return sftpHost;
}

public void setSftpHost(String sftpHost) {
this.sftpHost = sftpHost;
}

public int getSftpPort() {
return sftpPort;
}

public void setSftpPort(int sftpPort) {
this.sftpPort = sftpPort;
}

public String getSftpUser() {
return sftpUser;
}

public void setSftpUser(String sftpUser) {
this.sftpUser = sftpUser;
}

public String getSftpPassword() {
return sftpPassword;
}

public void setSftpPassword(String sftpPassword) {
this.sftpPassword = sftpPassword;
}

public String getSftpDir() {
return sftpDir;
}

public void setSftpDir(String sftpDir) {
this.sftpDir = sftpDir;
}

public boolean moveFileToDir(String localFilePath){
return moveFileToDir(localFilePath, null, null, true);
}
public boolean moveFileToDir(String localFilePath, String remoteDirPath){
return moveFileToDir(localFilePath, remoteDirPath, null, true);
}
public boolean moveFileToDir(String localFilePath, String remoteDirPath, String remoteFileName){
return moveFileToDir(localFilePath, remoteDirPath, remoteFileName, true);
}

public boolean copyFileToDir(String localFilePath){
return moveFileToDir(localFilePath, null, null, false);
}
public boolean copyFileToDir(String localFilePath, String remoteDirPath){
return moveFileToDir(localFilePath, remoteDirPath, null, false);
}
public boolean copyFileToDir(String localFilePath, String remoteDirPath, String remoteFileName){
return moveFileToDir(localFilePath, remoteDirPath, remoteFileName, false);
}

public boolean moveFileToDir(String localFilePath, String remoteDirPath, String remoteFileName, boolean isDelete){
boolean returnResult = false;
boolean deleteSuccess = false;
Session     session     = null;
Channel     channel     = null;
ChannelSftp channelSftp = null;

try{
JSch jsch = new JSch();
session = jsch.getSession(this.sftpUser,this.sftpHost,this.sftpPort);
session.setPassword(this.sftpPassword);
java.util.Properties config = new java.util.Properties();
config.put(“StrictHostKeyChecking”, “no”);
session.setConfig(config);
session.connect();
channel = session.openChannel(“sftp”);
channel.connect();
channelSftp = (ChannelSftp)channel;
if(null != remoteDirPath)
channelSftp.cd(remoteDirPath);
else
channelSftp.cd(this.sftpDir);

File f = new File(localFilePath);
String fileName = f.getName();
if(null != remoteFileName && remoteFileName.length() > 0)
fileName = remoteFileName;

channelSftp.put(new FileInputStream(f), fileName);
//Disconnecting the channel
channel.disconnect();
//Disconnecting the session
session.disconnect();
if(isDelete){
deleteSuccess = f.delete();
}else{
deleteSuccess = true;
}
returnResult = deleteSuccess;
}catch(Exception ex){
ex.printStackTrace();
}

return returnResult;
}

}

:)

Cheers !!

Open Mind, Open Source.

MySQL Cheat Sheet

Found a mysql cheat sheet on Net, thought share with yo… as well as with me also in future….. :)

Selecting a database:

mysql> USE database;

Listing databases:

mysql> SHOW DATABASES;

Listing tables in a db:

mysql> SHOW TABLES;

Describing the format of a table:

mysql> DESCRIBE table;

Creating a database:

mysql> CREATE DATABASE db_name;

Creating a table:

mysql> CREATE TABLE table_name (field1_name TYPE(SIZE), field2_name TYPE(SIZE));
Ex: mysql> CREATE TABLE pet (name VARCHAR(20), sex CHAR(1), birth DATE);

Load tab-delimited data into a table:

mysql> LOAD DATA LOCAL INFILE "infile.txt" INTO TABLE table_name;
(Use \n for NULL)

Inserting one row at a time:

mysql> INSERT INTO table_name VALUES ('MyName', 'MyOwner', '2002-08-31');
(Use NULL for NULL)

Retrieving information (general):

mysql> SELECT from_columns FROM table WHERE conditions;
All values: SELECT * FROM table;
Some values: SELECT * FROM table WHERE rec_name = "value";
Multiple critera: SELECT * FROM TABLE WHERE rec1 = "value1" AND rec2 = "value2";

Reloading a new data set into existing table:

mysql> SET AUTOCOMMIT=1; # used for quick recreation of table
mysql> DELETE FROM pet;
mysql> LOAD DATA LOCAL INFILE "infile.txt" INTO TABLE table;

Fixing all records with a certain value:

mysql> UPDATE table SET column_name = "new_value" WHERE record_name = "value";

Selecting specific columns:

mysql> SELECT column_name FROM table;

Retrieving unique output records:

mysql> SELECT DISTINCT column_name FROM table;

Sorting:

mysql> SELECT col1, col2 FROM table ORDER BY col2;
Backwards: SELECT col1, col2 FROM table ORDER BY col2 DESC;

Date calculations:

mysql> SELECT CURRENT_DATE, (YEAR(CURRENT_DATE)-YEAR(date_col)) AS time_diff [FROM table];
MONTH(some_date) extracts the month value and DAYOFMONTH() extracts day.

Pattern Matching:

mysql> SELECT * FROM table WHERE rec LIKE "blah%";
(% is wildcard - arbitrary # of chars)
Find 5-char values: SELECT * FROM table WHERE rec like "_____";
(_ is any single character)

Extended Regular Expression Matching:

mysql> SELECT * FROM table WHERE rec RLIKE "^b$";
(. for char, [...] for char class, * for 0 or more instances
^ for beginning, {n} for repeat n times, and $ for end)
(RLIKE or REGEXP)
To force case-sensitivity, use "REGEXP BINARY"

Counting Rows:

mysql> SELECT COUNT(*) FROM table;

Grouping with Counting:

mysql> SELECT owner, COUNT(*) FROM table GROUP BY owner;
(GROUP BY groups together all records for each 'owner')

Selecting from multiple tables:

(Example)
mysql> SELECT pet.name, comment FROM pet, event WHERE pet.name = event.name;
(You can join a table to itself to compare by using 'AS')

Currently selected database:

mysql> SELECT DATABASE();

Maximum value:

mysql> SELECT MAX(col_name) AS label FROM table;

Auto-incrementing rows:

mysql> CREATE TABLE table (number INT NOT NULL AUTO_INCREMENT, name CHAR(10) NOT NULL);
mysql> INSERT INTO table (name) VALUES ("tom"),("dick"),("harry");

Adding a column to an already-created table:

mysql> ALTER TABLE tbl ADD COLUMN [column_create syntax] AFTER col_name;

Removing a column:

mysql> ALTER TABLE tbl DROP COLUMN col;
(Full ALTER TABLE syntax available at mysql.com.)

Batch mode (feeding in a script):

# mysql -u user -p < batch_file
(Use -t for nice table layout and -vvv for command echoing.)
Alternatively: mysql> source batch_file;

Backing up a database with mysqldump:

# mysqldump --opt -u username -p database > database_backup.sql
(Use 'mysqldump --opt --all-databases > all_backup.sql' to backup everything.)
(More info at MySQL's docs.)

 

Thanks to Neal Parikh for this useful information. All credit goes to him, for original post click here.

Open Mind, Open Source.

Converting Double to String without scientific (E) notation in java

A numeric field in excel files was represented as string in database. Even though this number was not used for calculation, it seems for some reason, the database designer has kept it that way! Trouble started when the POI library’s getNumericCellValue() method returned the numbers in the form of scientific notation. The number 12,345,600 would be returned as 123.456E5. But I need it in plain text 1245600 without scientific notation and grouping of numbers!

Solution to this problem lies in configuring NumberFormat or DecimalFormat class found in the package java.text. Here is solution code:

Double comSysNumber = Cell.getNumericCellValue();
NumberFormat f = NumberFormat.getInstance();
f.setGroupingUsed(false);
String refinedNumber = f.format(comSysNumber);

Now the string variable refinedNumber is all set to be stored into my database :-) . Hope this becomes useful to others.

I just reshare, Thanks to this post: http://technopaper.blogspot.com/2009/06/converting-double-to-string-without-e.html

How to Install couchdb 1.0.1 on Ubuntu 10.04 step by step

Hi,

From last couple of month i am using “Hadoop” and “CouchDB” in my project with Python language. Honestly speaking I was a RDBMS guy, and before worked with “Postgresql“(One of my all time fav. db ) database. So as usual i started applying Rdbms concepts in couchdb (cause for me database means RDBMS)and start working, and totally got frustrated by Couchdb for a complete week. then after that, i started reading CouchDB: The Definitive Guide, and get to know that DBMS is not always RDBMS .  There also some  DB’s which are not using SQL queries to get, put data in db. Ok enough talk lets come to the topic. and try to solve our problems :)

Steps to Install couchdb on ubuntu 10.04:

1. Install the required packages:

Open your terminal and run the following command in your terminal:

#sudo apt-get install libicu-dev libcurl4-gnutls-dev libtool erlang-dev erlang

It will show you a message and ask for your permission to processed. Press “y” and it will start the required pkg installation.

2. Download the couchdb from net:

#wget http://www.fightrice.com/mirrors/apache//couchdb/1.0.1/apache-couchdb-1.0.1.tar.gz

or you can download from below link too by using your browser

http://www.apache.org/dyn/closer.cgi?path=/couchdb/1.0.1/apache-couchdb-1.0.1.tar.gz

3. Extract the compressed file:

#tar xvzf apache-couchdb-1.0.1.tar.gz

it will create a new directory in same directory, where you downloaded the compressed file.

4. Configure The couchdb to install:

#./configure –prefix=<directory path where you installing the couchdb>

e.g #./configure –prefix=/home/maddy/ProgramFiles/couch_install/

SpiderMonkey Problem:  If it will show you the below message, it means “libmozjs-dev” is missing in your system(By default it is not present in ubuntu 10.04) so you need to install it first. Here you have two approach to to solve the problem. First run it with latest Xulrunner(Recommended by apache couchdb, you can find the steps here), second download and install the pkg manually(Below is the steps provided).

Error: configure: error: Could not find the js library.
Is the Mozilla SpiderMonkey library installed?

Solution: download and install

“libmozjs0d” (download: link1, link2) or you can wget also:

“libmozjs-dev” (download: link1, link2) or you can wget also:

#wget http://launchpadlibrarian.net/24586256/libmozjs0d_1.8.1.18%2Bnobinonly.b308.cvs20090331t155113-0ubuntu0.8.10.1_i386.deb

#wget http://launchpadlibrarian.net/17059687/libmozjs-dev_1.8.1.16%2Bnobinonly-0ubuntu1_all.deb

5.  Configure it again:

#./configure –prefix=/home/maddy/ProgramFiles/couch_install/

If it will show you below message after running the configure command again it means everything going fine :)

“You have configured Apache CouchDB, time to relax.
Run `make && sudo make install’ to install.”

6.     install couchDB

#make && sudo make install

It will show you a message like this, and now really time to relax. :)
You have installed Apache CouchDB, time to relax.

7.   Change the directory  permission :

#sudo chown -R <current-ubuntu-username>: ${prefix}/var/{lib,log,run}/couchdb ${prefix}/etc/couchdbsudo

#chmod 0770 ${prefix}/var/{lib,log,run}/couchdb ${prefix}/etc/couchdb

8. Start the server:

go to couch install directory and run

#./etc/init.d/couchdb start

Error: * Starting database server

chown: changing ownership of `/home/maddy/ProgramFiles/couch_install/var/run/couchdb’: Operation not permitted

su: Authentication failure

Solution: /home/maddy/ProgramFiles/couch_install/etc/default #  sudo vim couchdb ,

Now change the “COUCHDB_USER=couchdb” to COUCHDB_USER=<ubuntu-user-name>

and start the couchdb server again

#./etc/init.d/couchdb start

9.     Open browser and check this link  http://localhost:5984/_utils

10.  Time for beer     :)

 

Cheers !!
Open Mind, Open Source

Postgres SQL Commands

I started using postgreSQL command line mode and then stop, again start and stop. So keep forgetting the some common commands. Listing them here so if i again forget no need to do google again.

1. # \l : List of all DataBases
2. # \c database-name : Connact to database
3. # \d :List tables in database
4. # \d table-name :D escribe table
5. # select * from table-name :List table contents
6. # \d for list of table and then “q” to came out
7. # \? : To see all available commands

A rare pic from great bollywood movie “SHOLEY”

sholey

Amitabh Bachchan...... (Jai --> Jaidev), Dharmendra...... (Veeru), Sanjeev Kumar......( Thakur Baldev Singh), Amjad Khan......( Gabbar Singh)

AND THIS PICTURE WAS TAKEN WHEN SUPERHIT SHOLEY WAS STARTED……

They were looking at ashrani when he was doing practice first time with his funny Jailer’s dress… ALONE on one rock…

 

:) ….. I am on cloud nine cause i made a request to Mr. Bachchan to “come on my blog and put a comment on my blog if he really like it” …and he really did it……yipeeeeeeeeeee. Wish u a very much  gud luck Mr. Bachchan. :)

dell vostro a840 windows xp driver

Hi,

What i am thinking is Microsoft have lots of business  minded peoples to sell Windows Vista, and that’s why only they made bond with most of the notebook sellers to give vista only(Other then linux i think Win XP is the biggest competitor of vista), no other flavor of windows( like win XP) . Like others i am also a win XP lover, and had a chance to install it on my friend notebook(Dell vostro A840). But the problem is DELL provided us a driver cd  for Windows Vista, so some drivers working for windows XP(Most of them not working really), for rest of the thing we need to find out win XP drivers for his notebook and install on it. Again i googled and found some links to download and install the drivers for our notebook.

Here I am including the links to download and install windows xp drivers for DELL Vostro system.

For sound driver we faced a problem related to  conexant sound driver in winxp sp2(DELL Vostro A840).  Conexant sound driver is not working. Once i install the audio driver the system replys cannot find the media device. Again we goggled it, and found a solution(mentioning below in steps to apply the solution).

  1. remove sound drive(if installed )
  2. Download driver sp32646.exe (Other link:  link )
  3. then download  sp34386exe (Other link: linklink)
  4. install both of them(same order)
  5. then install DELL DRIVERS Conexant Audio driver & Conexant Modem driver .

Guys thnx for your  reply’s,  i forgot to add one more thing and Mr. Thong comment remind it to me. Problem is “WLAN not working”  for that i installed QMI Wireless LAN Drivers version: 1.05.0725 driver(R194080.exe). And it start working for me. :)
Restart the windows, and Enjoy the Win XP sp2 on your system.

Cheers !!

Maddy

Open Mind, Open Source

Note: I want to give all of my credit to the writer of this blog to provide the valuable information.

Dell Vostro A840 Internet Not working in Ubuntu 8.04

Hi,

My friend bought a new “DELL vostro A840 Notebook”. An avarage configuration(Core 2 duo, 2GB ram, 160GB HD, with Ubuntu 8.04 linux)  notebook in decent price some around 32k(600$). I like it cause it is the best for the people who do not need lots of xtra feateres in there laptop(or u can say it is purely for busniess people). We checked all the things at shop all ports, internet, wifi each and everything which we are able to check there and everything working fine(in ubuntu). He is not familier with ubuntu linux so he made it duel boot(Win XP, and ubuntu 8.04), And then problem will start to come in ubuntu linux. Internet Not working in ubuntu 8.04. We checked every thing and found that the problem is coming in  ethernet card (Realtek RTL810). I search the ubuntu forum and found a thread here , they provide some solution there .

The problem coming due the disabled Wake-On-Lan setting of  wired ethernet cards.

Every time when we shutdown the winxp it disable the Wake-On-Lan(to save the power). After that when u boot with ubuntu, ethernet card not wakup so it is not connecting you with internet.

what is the fix?

To fix the problem you need to setup ur Wake-On-Lan settings in BIOS and Windows OS. I am giving the steps to set the settings. (I did these steps in DELL Vostro A840, You can do it according to your system ).

Enable Wake-On-Lan in BIOS:

  • In your system go in to the BIOS (after switch on the power press F12 to go in BIOS).
  • head to the Power management section and look for a Wake-on-LAN setting. If you find one, go ahead and make sure it’s enabled, then save and exit your BIOS and start up your notebook.

Enable Wake-On-Lan in BIOS:

  • MyComputer –> properties –>Hardware –> Device manager.
  • Select your Ethernet card –> properties –> power management tab.
  • Uncheck the option saying “Allow the computer to turn off this device to save the power “.
  • Now head to the Advanced tab, which is full of options for your network adapter. We’re concerned with two options here. The first is the Wake From Shutdown entry near the end of the list. Scroll down to it and change the value to enable.

Done

Restart your computer, boot in ubuntu (Do n0t forget to attache your  internet cable), open your browser and enjoy the browsing.

cheers !!

Maddy & Varun

Open Mind, Open Source

How To Create Hibernate Mapping Files Using Ant and PostgreSQL Database?

Hi Guys,

So At last my First blog about technology is here….. :)

For a web application project, i need to create the hibernate mapping files (.hbm.xml, .java). First i tried  to create the files by using “Hibernate Tool” plug-in for eclipse, it is good and provide a nice UI to create the files. I tried lots of tutorial, but i don’t know what went wrong and i totally screwed by the “HibernateTool”. I spend my 2 days to generate the files by using it, but fail. So i drooped the plan to use “HibernateTool” UI. I was looking for some other way to generate the files, I was googling (that’s what m always doing in trouble….like others) and i found a tutorial to generate the files using by ANT build and “Hibernate Tool” jar files. But that is for MySQL data base. so after doing some R&D on it m successfully able to create the mapping files.

:)

Q: How To Create Hibernate Mapping Files Using Ant and PostgreSQL Database?
A: By following the blow steps.

1.  Create Directories:

first u need to create a directory structure like this.

HibernateToolProject
|____/src
|            |____hibernate.cfg.xml
|
|____/lib(contains jar files)
|
|____build.xml

2. Add required .jar files:

For generate mapping file using postgreSQL database and ANT build, u need to add below jar files in your lib directory.

* commons-collections.jar
* commons-lang.jar
* commons-logging.jar
* dom4j-1.6.1.jar
* ehcache-1.2.3.jar
* freemarker.jar
* hibernate-3.1beta3.jar
* hibernate-tools.jar
* jtidy-r8-20060801.jar
* log4j-1.2.11.jar
* postgresal-8.3-603.jdbc2ee.jar
* postgresal-8.3-603.jdbc4.jar
* velocity-1.5.jar
to get all the jar just google them by name and u will get all of them(this is what i did and i got all the files from different different locations)

3.  hibernate.cfg.xml:

Add the following code and change the “hibernate.connection.url”,  “hibernate.connection.password”,  “hibernate.connection.username” according to your database.

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD 3.0//EN”
“http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>
<hibernate-configuration>
<session-factory name=”HibernateProject”>
<property name=”hibernate.connection.driver_class”>org.postgresql.Driver</property>
<property name=”hibernate.connection.password”>password</property>
<property name=”hibernate.connection.url”>jdbc:postgresql://localhost:5432/TestDb</property>
<property name=”hibernate.connection.username”>admin</property>
<property name=”hibernate.dialect”>org.hibernate.dialect.PostgreSQLDialect</property>
</session-factory>
</hibernate-configuration>

4.  build.xml:

Add the following code in your build.xml
<project name=”springapp” basedir=”.” default=”gen_hibernate”>

<taskdef name=”hibernatetool”
classname=”org.hibernate.tool.ant.HibernateToolTask”>
<classpath>
<fileset dir=”lib”>
<include name=”**/*.jar”/>
</fileset>
</classpath>
</taskdef>

<target name=”gen_hibernate”
description=”generate hibernate classes”>
<hibernatetool>

<jdbcconfiguration
configurationfile=”src/hibernate.cfg.xml”
packagename=”com.maddy.db”
/>
<hbm2hbmxml destdir=”src” />
<hbm2java  destdir=”src” />
</hibernatetool>
</target>

</project>

5.  Run it:

there is two way to run it.
First through eclipse: select build.xml and right click on it…Select RunAs–>AntBuild. And     it will create a new directory in your srcdirectory “com/maddy/db”. Refresh the project  and you will find the mapping files inside this directory.
Second install ANT build in ur system. set ANT_HOME and JAVA_HOME, in your
enviroment variable, then go to inside “HibernateToolProject” directory througn command  line and run command ANT.  This will do the same thing and create the same directory(as   mention above) and give you all mapping files(.hbm.xml and .java).

:)

Thats all guys. cheers !!
Open Mind, Open Source.

Earth Hour 2009

Earth Hours

Earth Hours

Today i just found a small caption for earth hour in a mail signature, sent by one of my friend working in a software company. Curiously i Google the word “earth hours” and found a complete web site and the great peoples behind that. They are simply great cause, i also want to do something for my planet, for my motherland for my earth. But the thig which makes these guys great is they are doing it.

The good thing is i am also participating in this global event. :) . Which is really making me very happy. I was always trying to do lil lil for all these climate changes daily, like trying to saving water, use less light, keep clean the things. I dn’t know what other people doing or thinking about this, But it giving me a “feel good” feeling. I am not a great person, i am not a millionaire, I am not a politically powerful person. I am just a normal men. Who have a sense to understand his responsibility. And i think this is my responcibility to keep clean my earth, keep safe for all, keep it from global warming, for our predecessor, for our child’s, for our self.

Click on above pic or Click Here for visit the WebSiite.

Turn off the lights, turn on hope…

Follow

Get every new post delivered to your Inbox.