Wednesday 29 January 2014

Linux simple Command

Command
Usage
Alias
To create the shortcut for the Command
To go the path /root/user/test 
 Linux command is  cd  /root/user/test  .
alias   alias_name  = ’ cd /root/user/test’
We can use alias_name  as command to go mentioned path

bc
To Perform the simple mathematical operation in terminal itself
bzip2
Compress the files .
Bzip2  -c -9  old_file_name.mp3> new_file_name.bz.2.
-c—standard output.
-9 for best compression result
Cat
used for the create , view , concatenate the file
Cat > testFile.txt – To create the new file.
Cat testFile.txt   - To view the testFile.txt.
Cat >>testFile.txt to append data in testFile1.txt file
Cat testFile.txt testFile2.txt >output.txt
Chmod
To change  the file rights
Chmod     user group other;

                0             none
               1             execute only
               2             write only
               3             write and execute
               4             read only
               5             read and execute
               6             read and write
               7             set all permissions
chmod  700—all rights for user . none of rights for group and others.
Chmod  600 – only read and write for user  rest of no rights.
6=read+write =4+2=6;

Copy
Cp  file1.txt  file 2.txt – To copy the content file1 to file2
Cp –r  folder1  folder2   used to copy folder and subfolder
scp- copy in remote system 

Crontab
command used to add jobs in cron.jobs calls itself
chrontab –e * * * * *  jobname;
1st * -- minute
2nd * – hour
3rd  *– day
4th * -  month
5th *-  weak
Grep
to search the word in file.
grep  searchwordfilename;
It will show the searched word in terminal.
grep searchwordfilename>newFile.txt
It will create a new file contains the searched word
   

Halt
shutdown the system

head
To view the content of file.
Head  filename ---- show the first 10 lines
Head -45 filename --show the first 45 lines
Head -5 filename>test.txt
  -First 5 lines of filename will copied to test.txt file.


Paste
Paste the content
Paste file1.txt file2.txt  -- to paste the file1.txt content to file2.txt

Pwd
Path of current working directory.
link
This command is used to link the file. We cannot link already present file.
Link test1.txt test2.txt .
If we change the test1.txt  it will reflect  in  test2.txt file also.
tail
Like head command.
To view the content of file.
tail filename ---- show the last 10 lines
tail -45 filename --show the last 45 lines
tail -5 filename>test.txt
  -First 5 lines of filename will copy to test.txt file.

man
It is used to know about command
Man cp—To know about the copy command
ls
List out the list of files


VI Editor commands
http://www.cs.rit.edu/~cslab/vi.html

Mount Windows shared folder in Linux machine at LAN connection
This for Temporary mount
Step 1: Create the folder  at Linux machine .
Step 2: Share your windows folder in Network
Step 2: Execute following command
mount -t cifs //windows IP/windows sharefolder name -o
windowsUsername=<USERNAME>,password=<PASSWORD> Linux folder created path



mount -t cifs //192.168.2.196/MyFile -o username=admin,password=123 /root/Desktop/MyFile


For Permanent Mount:

By using vi editor open the fstab under etc.

vi /etc/fstab 

And add the following code 

//windows IP/windowsSharefolderName  LinuxFolderCreatedPathFile FilesystemName  permission windowsUsername=<USERNAME> ,password=<PASSWORD>

 //192.168.2.196/MyFile   /root/Desktop/MyFile cifs  rw  username=admin,password=123

online Linux command practice

http://bellard.org/jslinux/




Java Jquery Ajax Sample

/**
Prerequest Sets
       Please download  jquery.js and add it in  your js folder
*/
HTML Page:
<html>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
function callAjax(){

$.ajax({
            var userName=$( "#uname" ).val();
            var formData = {uname:userName};
            url : 'LoginIDActivityHandler',
            type: "POST",
            data : formData,
            success: function(responseText)
            {
                     
                      if(responseText=='y'){
                             alert('valid user');
                           document.login.submit();
                      }else {
                          alert('invalid user');
                            return false;
                      }
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert(errorThrown);
                return;
            }
        });
}
</script>

<form name="jqueryajax">
<input type="text" class="form-control"  id="uname" name="uname"/ >
<input type='button' onClick='callAjax();'>
</form>
</html>
web.xml

<servlet>
    <description></description>
    <display-name>LoginIDActivityHandler</display-name>
    <servlet-name>LoginIDActivityHandler</servlet-name>
    <servlet-class>LoginIDActivityHandler</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginIDActivityHandler</servlet-name>
    <url-pattern>/LoginIDActivityHandler</url-pattern>
  </servlet-mapping>

Servlet File

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created By B.Balamurugan
 */
public class LoginIDActivityHandler extends HttpServlet {
 private static final long serialVersionUID = 1L;

 @Override
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  String userid = request.getParameter("uname");
  if (userid.equals("bala")) {
   response.getWriter().write("y");
   return;// to avoid illegal statement exception

  } else {
   response.getWriter().write("n");
   return;// to avoid illegal statement exception
  }
 }

}


Wednesday 22 January 2014

MySql queries

Oracle Function
http://docs.oracle.com/html/A95915_01/sqfunc.htm#i1005521

Following Link shows My sql date Format

my sql date format

You can't specify target table table name  for update in FROM clause

The above mentioned error occur when you try to execute the update statement with condition get from same table

Error Query


update employee_details set salary=10000
where salary =(select max(salary)
from employee_details be);

To solve the by using temp table

Solved Query


update employee_details set salary='10000'
where salary =(select sal from (select max(salary) as sal
from employee_details be) as temp);

 Mysql Query  Serial Number select statement


SELECT  @a:=@a+1 serial_number, 
        e.name.e,age
FROM    employee_details e,
        (SELECT @a:= 0) AS a;


MySql Show columns

SHOW COLUMNS FROM tableName where field like '%emp%';

Here field is column name of table



MySql  queries For Replace special Character into HTML tags  and   change content to  UTF8


 SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
                                                                         (REPLACE
                                                                            (REPLACE
                                                                               (REPLACE
                                                                                  (REPLACE
                                                                                     (REPLACE
                                                                                        (REPLACE
                                                                                           (REPLACE
                                                                                              (REPLACE
                                                                                                 (REPLACE
                                                                                                    (REPLACE
                                                                                                       (REPLACE(CONVERT
                                                                                                                  (REPLACE
                                                                                                                     (REPLACE(CONVERT(columnName USING utf8),'\r\n','<br>'),' ','&nbsp;')USING 'UTF8'),':','&colon;'),'~','&tilde;'),'!','&excl;'),'@','&commat;'),'#','&num;'),'$','&dollar;'),'%','&percnt;'),'*','&ast;'),'(','&lpar;'),')','&rpar;'),'_','&lowbar;'),'+','&plus;'),'{','&lbrace;'),'}','&rbrace;'),'[','&lbrack;'),']','&rbrack;'),'^','&circ;'),':','&colon;'),'','&quot;'),'?','&quest;') AS instruction
FROM tablename

Mysql 3rd maximum salary 

SELECT e.salary
FROM salary_details e
ORDER BY empid DESC LIMIT 2,1 ;


Insert values into table, value get from  another table

insert into employee(name,age)  select name,age from master_employee;

My sql insert many row in single query
Below query is used for  insert the 3 row in single insert statement
INSERT INTO TABLE_NAME (column1,column2,column3,column4,)
VALUES 
(v1, v2,v3,v4), 
(v1,v2,v3,v4), 
(v1,v2,v3,v4);

Restart mysql

service mysql restart

Get table backup or create table with select query.
create table my_table_back
as select * from my_table;

insert  with select query.

insert into workflow.conversion_check_list_details (check_list_name, workflow_id, sas_id, product_type_id)
select instruction_name,'7' as workflow_id,'479' as sasid,'15' as product_ID from  workflow.instruction_deliverable_mapping  ind ,workflow.cfg_instruction_catalog cic where workflow_id = 17
and ind.instruction_id = cic.instruction_id
and is_prerequisite='n'
and deliverables_id = 438;

Java Useful Codes and Useful links

Java EE  Vs Spring 

http://www.slideshare.net/reza_rahman/java-ee-and-spring-sidebyside

Java Basic
http://docs.oracle.com/javase/tutorial/extra/certification/index.html
java  report in spring
http://lagivan.blogspot.in/2011/11/dynamicreports-and-spring-mvc.html

Excel Creation in java

http://poi.apache.org/spreadsheet/examples.html

http://poi.apache.org/spreadsheet/quick-guide.html

Java Null Pointer Check  Code
/**
The Following method is used  for check whether string is null or not
return true -- if string is null
false  -- if string not null
*/

public boolean isNullValue( String  stringVal){

     if(stringVal ==null || "".equals(stringVal) || "null".equalsIgnoreCase(stringVal)){

       return true;

      }else{

       return false;

     }

}


Drag and drop files jquery.
http://hayageek.com/drag-and-drop-file-upload-jquery/


Run bat file from java.
Process proc = Runtime.getRuntime().exec(new String[] {"bat file path",arguments to bat file});
BufferedReader b = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = "";

            while ((line = b.readLine()) != null) {
            System.out.println(line);
            }

Example 
Process proc = Runtime.getRuntime().exec(new String[] {"d:\\batchFile.bat",arguments to bat file});


By using bat file send arguments to java program.

In bat file:
java fileName %1 %2
First argument %1
second argument %2;

Append String in comma for as separator
int count=0
StringBuffer fileIds= new StringBuffer();

while(rsFileDetails.next()){
  if (count != 0) {
   fileIds.append(",");
  }
  fileIds.append(rsFileDetails.getString(1));
  count++;
}


Java schedule task

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 
 * @author B.Balamurugan This file is used for the schedule the task(Job) using
 *         in java Once this class get run as this example it will continues run
 *         every 5 min
 * 
 */
public class JavaScheduleTask extends TimerTask {

 @Override
 public void run() {
  // Here we have to mention the task
  System.out.println(new Date());

 }

 public static void main(String args[]) {
  int initialDelay = 5000; // start after 5 seconds
  int period = 5 * 60 * 1000; // repeat every 5 minutes
  TimerTask timerTask = new JavaScheduleTask();
  // running timer task as daemon thread
  Timer timer = new Timer();

  timer.scheduleAtFixedRate(timerTask, initialDelay, period);

 }

}
Java Folder contains File
/**
     * This method is used for the specified folder contains the file or not
     * 
     * @param filePath
     * @param fileName
     * @return true folder contains the file false folder not contains the file
     */
    public boolean isFolderContainsFile(String folderPath, String fileName) {
        File file = new File(filePath);
        List<String> fileNames = new ArrayList<String>();
        if (file.isDirectory()) {
 
            for (File fileName1 : file.listFiles()) {
                fileNames.add(fileName1.getName());
 
            }
 
        }
        return fileNames.contains(fileName);
    }


Java to generate alphanumeric  random  number 6 digit

Random rand = new Random();
  String ranNo="";
    for (int j = 0; j<3; j++){
       int pick = (int) (Math.random() * 10);
       double randomNumberSetup = (pick * 2 + 'a');
       char randomCharacter = (char) randomNumberSetup;
      ranNo=ranNo+pick+randomCharacter;       
     }
 System.out.println("randam Number"+ranNo); 


File Name Renameing

String fileName = fileName.substring(0, fileName.lastIndexOf("epub"))+"doc";
Java To Find current week start date and end date

        Calendar currentDate    = Calendar.getInstance();
 Calendar startOFweek    = Calendar.getInstance();
 Calendar endDateOFWeek  = Calendar.getInstance();
 
        int dayOfWeek = currentDate.get(Calendar.DAY_OF_WEEK);
 int endDateDiff = 7-dayOfWeek;
 
 startOFweek.add(Calendar.DATE, -(dayOfWeek-1));
 endDateOFWeek.add(Calendar.DATE, endDateDiff);
 
 System.out.println("Start date Of week "+startOFweek.getTime());
 System.out.println("End date of week "+endDateOFWeek.getTime());