October 15, 2013

Sending screenshot from client to Server through socket in java


How to send screen shot from client to server automatically in java

Did you ever think of getting screen shot from all computers in a network to a server. This code will helps you to do so....This code will capture the current desktop screen shot and sent it to server computer. This application is very useful to network administrator to track what other are doing in the computer at your organization.

ClientApp.java : is a client program that takes screen shot in regular interval.  The sendScreen function will help you to know how java program takes screen shot at intervals and sends to server machine. Here i used ImageIO class to create image buffer. There are other options too... The file is sent through a socket. the port number i used here is 1729. Server Name here used is loop back ip, where you need to specify the server computer name or ip  address.

On the Other hand
SeverApp.java will always listen to the port 1729. if any request comes there, it will catch request and save to the folder 


ClientApp.java


import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;


import javax.imageio.ImageIO;


/**
 * @author lou reed
 *
 */
public class ClientApp implements Runnable {

    private static long nextTime = 0;
    private static ClientApp clientApp = null;
    private String serverName = "127.0.0.1"; //loop back ip
    private int portNo = 1729;
    //private Socket serverSocket = null;
   
    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        clientApp = new ClientApp();
        clientApp.getNextFreq();
        Thread thread = new Thread(clientApp);
        thread.start();
    }

    private void getNextFreq() {
        long currentTime = System.currentTimeMillis();
        Random random = new Random();
        long value = random.nextInt(180000); //1800000
        nextTime = currentTime + value;
        //return currentTime+value;
    }

    @Override
    public void run() {
        while(true){
            if(nextTime < System.currentTimeMillis()){
                System.out.println(" get screen shot ");
                try {
                    clientApp.sendScreen();
                    clientApp.getNextFreq();
                } catch (AWTException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch(Exception e){
                    e.printStackTrace();
                }
               
            }
            //System.out.println(" statrted ....");
        }
       
    }

    private void sendScreen()throws AWTException, IOException {
           Socket serverSocket = new Socket(serverName, portNo);
             Toolkit toolkit = Toolkit.getDefaultToolkit();
             Dimension dimensions = toolkit.getScreenSize();
                 Robot robot = new Robot();  // Robot class
                 BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));
                 ImageIO.write(screenshot,"png",serverSocket.getOutputStream());
                 serverSocket.close();
    }
}




Web Browsers Tips and Tricks

How to remove or hide an address bar from a web browser

cómo quitar la barra de direcciones de un navegador web

كيفية إزالة شريط العنوان من مستعرض الويب

wie Adressleiste von einem Webbrowser entfernen

como remover barra de endereços do navegador de internet

как удалить адресную строку из веб-браузера

วิธีการเอาแถบที่อยู่จากเว็บเบราว์เซอร์

如何从Web浏览器中删除地址栏

How to remove address bar from Internet Explorer web browser

  • Open run (win + r) then type " regedit " to open registry editor
  • Navigate to HKEY_LOCAL_MACHINE >> software >> policies >> Microsoft , Right click then select New >> Key to create a subkey named " Internet Explorer " under " Microsoft "
  • Right click on "Internet Explorer" then select New >> Key to create another key named " Toolbars " under " Internet Explorer "
  • Right click on " Toolbars " then select New >> Key to create another key named " Restrictions " under " Toolbars "
  • The hierarchy looks as follows HKEY_LOCAL_MACHINE >> software >> policies >> Microsoft >> Internet Explorer >> Toolbars >> Restrictions
  • On the right side you can two columns name and type. right click in the open area select New >> DWORD value create the name " NoAddressBar "
  • Right click on " NoAddressBar " then select Modify and Enter the value 1 in the Textbox and click "OK"

How to remove address bar from Google chrome web browser

  • Type "about:flag" in the address bar of google chrome and hit enter
  • Scroll down to "compact navigation" and enable it
  • Once browser restarted, click on the tab and select " hide the tool bar " from context menu

+Vipin Cp

http://javabelazy.blogspot.in/

October 10, 2013

Example in java to read and write an excel sheet

How to read and write an excel sheet in java



/**
* Developed for ..... Account Section (For ...),
*/

package reader;

import java.io.File;

import java.io.IOException;

import java.security.acl.LastOwnerException;

import java.util.Vector;

import writer.WriteExcel;

import jxl.Cell;

import jxl.CellType;

import jxl.Sheet;

import jxl.Workbook;

import jxl.read.biff.BiffException;

import jxl.write.WriteException;

public class ReadExcel {

  private String inputFile;

  private double openingBalDL =130.95;

  private double openingBalCL =0.00; // Credit Last

  private double openingBalDN =0.00; // Debit New

  private double openingBalCN =0.00;

  private double allDebits = 0.00;

  private double allCredits = 0.00;

  private String dateLast = "4/3/12";

  private String dateNew = null;

  private Vector array = new Vector();

  public void setInputFile(String inputFile) {
    this.inputFile = inputFile;
  }

  public void read() throws IOException  {
    File inputWorkbook = new File(inputFile);
    Workbook w;
    try {
      w = Workbook.getWorkbook(inputWorkbook);
      // Get the first sheet
      Sheet sheet = w.getSheet(0);
      // Loop over first 10 column and lines
      System.out.println(" no of rows "+sheet.getRows());
      System.out.println(" no of col "+sheet.getColumns());
      int totCols = sheet.getColumns();
      int totRows = sheet.getRows();
      Cell cell = sheet.getCell(0, 1);  // col,row
      System.out.println(cell.getContents());
      if(cell.getContents().equalsIgnoreCase("Opening Balance B/D")){
          System.out.println(" --------------- true ---------------- ");
      }
    
              double debit = 0.00;
              double credit = 0.00;
              double openingBalDb = 130.95;
              double openingBalCr = 0.00;
              double balanceTotDb = 0.00;
              double balanceTotCr = 0.00;
              double closingBalCr = 0.00;
              double closingBalDb = 0.00;
              Vector value = null;
          for(int row =1; row               value = new Vector();
              Cell dateCell = sheet.getCell(0, row);
              Cell refCell = sheet.getCell(1, row);
              Cell partCell = sheet.getCell(2, row);
              Cell debCell = sheet.getCell(3, row);
              Cell crdCell = sheet.getCell(4, row);
              value.add(dateCell.getContents());
              value.add(refCell.getContents());
              value.add(partCell.getContents());
              if(!dateCell.getContents().equalsIgnoreCase("")){  // date ( all debit, credit0
                   debit = debit + Double.parseDouble(debCell.getContents());
                   credit = credit + Double.parseDouble(crdCell.getContents());
                   value.add(debCell.getContents());
                   value.add(crdCell.getContents());
                   System.out.println(" Row : "+row + " Debit : "+debit + " Credit : "+credit);
              } else{ // Balance total , closing balance , grant total, Opeining bala
                      if(partCell.getContents().equalsIgnoreCase("Balance Total")){
                          balanceTotDb = openingBalDb + debit;
                          balanceTotCr = credit;
                          System.out.println(" Balance Total Db : "+balanceTotDb + " Balance Total Cr :"+balanceTotCr);
                          openingBalDb = balanceTotDb;
                          value.add(balanceTotDb);
                          value.add(balanceTotCr);
                      }
                      if(partCell.getContents().equalsIgnoreCase("Closing Balance C/D")){
                          closingBalCr = 0.00;
                          closingBalDb = 0.00;
                        
                          if(balanceTotDb >= balanceTotCr){ //+ credit
                              closingBalCr = balanceTotDb - balanceTotCr;
                          }else{ // - debit
                              closingBalDb = balanceTotCr - balanceTotDb;
                          }
                          System.out.println(" Closing Balance Db "+closingBalDb + " Closing Balance Cr "+closingBalCr);
                          value.add(closingBalDb);
                          value.add(closingBalCr);
                      }if(partCell.getContents().equalsIgnoreCase("Grand Total")){
                          double grantTotalDb = balanceTotDb + closingBalDb;
                          double grantTotalCr = balanceTotCr + closingBalCr;
                          System.out.println(" Grant Total Db : "+grantTotalDb + " Grant Total Cr : "+grantTotalCr);
                          value.add(grantTotalDb);
                          value.add(grantTotalCr);
                      }
                      if(partCell.getContents().equalsIgnoreCase("Opening Balance B/D")){
                          double opBalDb = closingBalCr;
                          double opBalCr = closingBalDb;
                          System.out.println(" Opening Balance Db : " + opBalDb + " Opening Balance Cr : "+opBalCr);
                          value.add(opBalDb);
                          value.add(opBalCr);
                          debit = 0.00;
                        credit = 0.00;  
                        balanceTotDb = 0.00;
                        balanceTotCr = 0.00;
                        closingBalDb = 0.00;
                        closingBalCr = 0.00;
                      }
              }
              array.add(value);
              //Cell cell = sheet.getCell(col, row);
             // System.out.println(cell.getContents());
          }
  
       System.out.println(" array size "+array.size());
       WriteExcel test = new WriteExcel();
       test.setOutputFile("D:/Nijesh/Report.xls",array);
       try {
        test.write();
    } catch (WriteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 
    } catch (BiffException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) throws IOException {
    ReadExcel test = new ReadExcel();
    test.setInputFile("D:/Jerin/Ultron/CashBook.xls");
    test.read();
  }

}

-----------------------

package writer;

import java.io.File;

import java.io.IOException;

import java.util.Locale;

import java.util.Vector;

import jxl.CellView;

import jxl.Workbook;

import jxl.WorkbookSettings;

import jxl.format.UnderlineStyle;

import jxl.write.Formula;

import jxl.write.Label;

import jxl.write.Number;

import jxl.write.WritableCellFormat;

import jxl.write.WritableFont;

import jxl.write.WritableSheet;

import jxl.write.WritableWorkbook;

import jxl.write.WriteException;

import jxl.write.biff.RowsExceededException;

public class WriteExcel {

  private WritableCellFormat timesBoldUnderline;

  private WritableCellFormat times;

  private String inputFile;

  private Vector array = null;


  public void setOutputFile(String inputFile) {
      this.inputFile = inputFile;
  }

  public void setOutputFile(String inputFile, Vector array) {
      this.inputFile = inputFile;
      this.array = array;  
    }

  public void write() throws IOException, WriteException {
    File file = new File(inputFile);
    WorkbookSettings wbSettings = new WorkbookSettings();

    wbSettings.setLocale(new Locale("en", "EN"));

    WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
    workbook.createSheet("Report", 0);
    WritableSheet excelSheet = workbook.getSheet(0);
    createLabel(excelSheet);
    createContent(excelSheet);

    workbook.write();
    workbook.close();
  }

  private void createLabel(WritableSheet sheet)
      throws WriteException {
    // Lets create a times font
    WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
    // Define the cell format
    times = new WritableCellFormat(times10pt);
    // Lets automatically wrap the cells
    times.setWrap(true);

    // Create create a bold font with unterlines
    WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false,
        UnderlineStyle.SINGLE);
    timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
    // Lets automatically wrap the cells
    timesBoldUnderline.setWrap(true);

    CellView cv = new CellView();
    cv.setFormat(times);
    cv.setFormat(timesBoldUnderline);
    cv.setAutosize(true);

    // Write a few headers
    addCaption(sheet, 0, 0, "Date");
    addCaption(sheet, 1, 0, "Reference");
    addCaption(sheet, 2, 0, "Particulars");
    addCaption(sheet, 3, 0, "Debit");
    addCaption(sheet, 4, 0, "Credit");
  

  }

  private void createContent(WritableSheet sheet) throws WriteException,
      RowsExceededException {
    
      int size = array.size();
    
      for(int row = 0; row < size; row ++){
          Vector val = array.get(row);
          for(int col =0; col<5 data-blogger-escaped-br="" data-blogger-escaped-col="">              addValues(sheet,col, row, val.get(col));
          }
        }
    
    
    
    
      /*
    for (int i = 1; i < 10; i++) {
      // First column
      addNumber(sheet, 0, i, i + 10);
      // Second column
      addNumber(sheet, 1, i, i * i);
    }
    */

  }

  private void addCaption(WritableSheet sheet, int column, int row, String s)
      throws RowsExceededException, WriteException {
    Label label;
    label = new Label(column, row, s, timesBoldUnderline);
    sheet.addCell(label);
  }

  private void addNumber(WritableSheet sheet, int column, int row,
      Integer integer    ) throws WriteException, RowsExceededException {
  
    Number number;
    number = new Number(column, row, integer, times);
    sheet.addCell(number);
  
  
  }

  private void addValues(WritableSheet sheet, int column, int row, Object obj)
          throws WriteException, RowsExceededException {
        Label label;
        label = new Label(column, row, obj.toString(), times);
        sheet.addCell(label);
      }

  private void addLabel(WritableSheet sheet, int column, int row, String s)
      throws WriteException, RowsExceededException {
    Label label;
    label = new Label(column, row, s, times);
    sheet.addCell(label);
  }

  public static void main(String[] args) throws WriteException, IOException {
    WriteExcel test = new WriteExcel();
    test.setOutputFile("D:/Akshara/Report.xls");
    test.write();
    System.out
        .println("Please check the result file under E:/Bithesh/consumerfed.xls ");
  }


}

--------------

You have to download jxl.jar to download this apps

The above program calculate balance total, closing balance, opening balance, grant total from given ledger entries in excels sheet...



Read : How to copy all images (resource) from ms word document?

October 07, 2013

How to redirect to second page from first page through servlet

Servlet Mapping example in deployment descriptor


This java server page (jsp) example shows how to redirect from a page another page in jsp, the request from jsp page will pass through a servlet and from the servlet to second . the following java code will decide which page the request should be directed : page.response.sendRedirect("secondPage.jsp");

web.xml file



<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Artificial intelligence</display-name>
  <welcome-file-list>
    <welcome-file>newPage.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description>An example for servlet mapping in jsp servlet</description>
    <display-name>Beyonce superbowl</display-name>
    <servlet-name>Beyonce</servlet-name>
    <servlet-class>com.NeuralNetwork.servlet.EvasiOn</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Beyonce</servlet-name>
    <url-pattern>/NeuralNetwork.jsp</url-pattern>
  </servlet-mapping>
</web-app>



October 04, 2013

Java code to get screen shot

How to get screen shot in java



 /**
 * @author Jim Brown
 *
 */

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ScreenShotCapture {
   
    private static final String DIR_NAME = "SouthPark";

    public static void main(String[] shutdown)  {
        ScreenShotCapture captureSS = new ScreenShotCapture();
        captureSS.createDirectory(DIR_NAME);
        try {
            captureSS.getScreen();
        } catch (AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void createDirectory(String dirName) {
        File newDir = new File("D:\\"+dirName);
        if(!newDir.exists()){
            boolean isCreated = newDir.mkdir();
        }
}

    private void getScreen()throws AWTException, IOException {
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension dimensions = toolkit.getScreenSize();
        Robot robot = new Robot();  // Robot class
        BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));
        ImageIO.write(screenshot, "png", new File("D:\\"+DIR_NAME+"\\Gravity.png"));
   
   }
}

Hi Friends,

         This is a small program named Xkeycode  that enables you to capture system screen. Once you run the code it will capture the screen and save  and png image in your system. so please try it out..


Facebook comments