Saturday 25 June 2016

How to remove "This copy of windows is not genuine" error.

Steps of fix using Command Prompt:
  1. Open Control Panel in your Windows from Start menu.
  2. Click on System & Security. (If you are a Windows XP user, then there is no need to click on System & Security).
  3. Click on Windows Update.
  4. Click on View Installed updates. (See below screenshot for reference)fix this copy of windows is not genuine 2015
  5. Now, look for KB971033 update. Right click on it.
  6. Click on Uninstall.uninstall
  7. It will show a popup. Simply, click on Yes.
Restart your computer and you will find that you have got rid of this error now.

Sunday 6 March 2016

How to mock your php Curl request as if coming from a user's Web browser?

There are times when we want to make http request to some other third party website to download or access some data/url. Well, it looks strange at first look as if why would we need to worry about it, we can directly call the url from php code using CUrl.

Till now things look simple. Yes, it is easy to access url using Curl. But sometimes, we face issue while accessing the url. There is no problem when we access the same url from browser, but it fails when we try to access the same url from our php code on server.

The reason being, some third party websites whose url/data you want to access would like to provide data only to users using web browser and not to any webservers. So, in such cases the CUrl fails.

So, what is the solution?
Its very simple. If you think logically, we just need to make our http request mock as if it is coming from and users browser and not through any server.

To do this, we will set few header parameters that will mock the request as request from any web browser.

Here is the addition that you need to add in your existing php code.

 $url = 'http://www.xyz.com/';  
 $ch = curl_init($url);  
 curl_setopt_array($ch, array(  
   CURLOPT_HTTPHEADER => array('Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1'),  
   CURLOPT_RETURNTRANSFER =>true,  
   CURLOPT_VERBOSE   => 1  
 ));  
 $out = curl_exec($ch);  
 curl_close($ch);  
 echo $out;  

Hope this will help you.
Thanks for arriving at this page.

Thursday 25 February 2016

Create web browser with JavaFX 2.0 WebView

JavaFX 2.0 provide WebView, a full function web browser based on WebKit, an open source web browser engine. It supports Cascading Style Sheets (CSS), JavaScript, Document Object Model (DOM), and HTML5 features of rendering canvas and timed media playback.

 /*  
 * To change this template, choose Tools | Templates  
 * and open the template in the editor.  
 */  
 package javafx_webview;  
 import javafx.application.Application;  
 import javafx.scene.Scene;  
 import javafx.scene.layout.StackPane;  
 import javafx.scene.web.WebEngine;  
 import javafx.scene.web.WebView;  
 import javafx.stage.Stage;  
 /**  
 *  
 * @web https://java-tech-world.blogspot.com  
 */  
 public class JavaFX_Browser extends Application {  
  /**  
   * @param args the command line arguments  
   */  
  public static void main(String[] args) {  
    launch(args);  
  }  
  @Override  
  public void start(Stage primaryStage) {  
    primaryStage.setTitle("https://java-tech-world.blogspot.com/");  
    WebView myBrowser = new WebView();  
    WebEngine myWebEngine = myBrowser.getEngine();  
    myWebEngine.load("https://java-tech-world.blogspot.com/");  
    StackPane root = new StackPane();  
    root.getChildren().add(myBrowser);  
    primaryStage.setScene(new Scene(root, 640, 480));  
    primaryStage.show();  
  }  
 }  

Wednesday 24 February 2016

How to Switch Excel Columns and Rows

Everyone looks at information in a slightly different way. Some people create Excel spreadsheets where the data is useful, but it doesn’t work with the way you view or interact with the data. One common example is where you want to transpose or switch Excel row or column data so Row A data becomes Column A data and so on.
I recently was given a large Microsoft Excel spreadsheet that contained vendor evaluation information. The information was useful, but because of the way the data was structured, I couldn’t use tools like Auto Filter. I would also have issues if I needed to import the information to a database. A simple example of such a spreadsheet is shown below.

highlighted row to swap 

Instead, I want to have the Company names display vertically in Column A and the attributes display horizontally in Row 1. This would make it easier for me to do comparisons. For example, I can’t easily filter the spreadsheet for vendors in CA. I also didn’t want to re-enter the data. The fix is rather easy using Excel’s transpose feature.

To switch Excel columns and rows,

  1. Open the spreadsheet you need to change.
  2. If needed, insert a blank worksheet.
  3. Click the first cell of your data range such as A1.
  4. Shift-click the last cell of the range. Your selection should highlight.
  5. From the Home tab menu, select Copy.
  6. At the bottom of the page, click the tab for the blank worksheet such as Sheet2.
  7. In the blank worksheet, click cell A1.
  8. From the Home tab menu, select Paste. The Paste dialog should appear.
 transpose button on paste dialog
  1. Click the box for Transpose.
Once you transpose the data, your company names will show in Column A. I can now sort or filter the data in many ways.



transpose Excel column



























Wednesday 20 January 2016

How to load HTTPS url from Java FX Webview component?

JavaFx has WebView component that can be used to load the Http & Https Url.
The basic steps to load any url using WebView is

WebView view = new WebView();
engine = view.getEngine();
engine.load(new URL("http://www.google.com));
engine.load(new URL("https://mail.google.com));

The problem comes when we have Https url to be loaded.
If the https url that we want to load have signed certificate, we can easily load it.
But if https url that we want to load does not have a signed certificate, it becomes difficult to load the Url.

To solve this, we disable the certificate check and mark the connection object to trust all the certificates.

Below is the code snippet that you should write just before loading the URL.

 TrustManager[] trustAllCerts = new TrustManager[] {  
         new X509TrustManager() {  
           public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
             return null;  
           }  
           public void checkClientTrusted(  
               java.security.cert.X509Certificate[] certs, String authType) {  
           }  
           public void checkServerTrusted(  
               java.security.cert.X509Certificate[] certs, String authType) {  
           }  
         }  
     };  
     // Install the all-trusting trust manager  
     try {  
       SSLContext sc = SSLContext.getInstance("SSL");  
       sc.init(null, trustAllCerts, new java.security.SecureRandom());  
       HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
     } catch (GeneralSecurityException e) {  
     }  

To create a full embeded browser that is able to load urls having self signed certificates.

 package utility;  
 import javafx.application.Platform;  
 import javafx.beans.value.ChangeListener;  
 import javafx.beans.value.ObservableValue;  
 import javafx.concurrent.Worker;  
 import javafx.embed.swing.JFXPanel;  
 import javafx.event.EventHandler;  
 import javafx.scene.Scene;  
 import javafx.scene.web.WebEngine;  
 import javafx.scene.web.WebEvent;  
 import javafx.scene.web.WebView;  
 import javax.net.ssl.HttpsURLConnection;  
 import javax.net.ssl.SSLContext;  
 import javax.net.ssl.TrustManager;  
 import javax.net.ssl.X509TrustManager;  
 import javax.swing.*;  
 import java.awt.*;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 import java.security.GeneralSecurityException;  
 import static javafx.concurrent.Worker.State.FAILED;  
 public class SimpleWebBrowser extends JFrame {  
   private final JFXPanel jfxPanel = new JFXPanel();  
   private WebEngine engine;  
   private final JPanel panel = new JPanel(new BorderLayout());  
   private final JLabel lblStatus = new JLabel();  
   private final JProgressBar progressBar = new JProgressBar();  
   public SimpleWebBrowser() {  
     super();  
     initComponents();  
   }  
   private void initComponents() {  
     createScene();  
     progressBar.setPreferredSize(new Dimension(150, 18));  
     progressBar.setStringPainted(true);  
     JPanel topBar = new JPanel(new BorderLayout(5, 0));  
     topBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));  
     JPanel statusBar = new JPanel(new BorderLayout(5, 0));  
     statusBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));  
     statusBar.add(lblStatus, BorderLayout.CENTER);  
     statusBar.add(progressBar, BorderLayout.EAST);  
     panel.add(topBar, BorderLayout.NORTH);  
     panel.add(jfxPanel, BorderLayout.CENTER);  
     panel.add(statusBar, BorderLayout.SOUTH);  
     getContentPane().add(panel);  
     setPreferredSize(new Dimension(1024, 600));  
     pack();  
   }  
   private void createScene() {  
     Platform.runLater(new Runnable() {  
       @Override  
       public void run() {  
         WebView view = new WebView();  
         engine = view.getEngine();  
         engine.titleProperty().addListener(new ChangeListener<String>() {  
           @Override  
           public void changed(ObservableValue<? extends String> observable, String oldValue, final String newValue) {  
             SwingUtilities.invokeLater(new Runnable() {  
               @Override  
               public void run() {  
                 SimpleWebBrowser.this.setTitle(newValue);  
               }  
             });  
           }  
         });  
         engine.setOnStatusChanged(new EventHandler<WebEvent<String>>() {  
           @Override  
           public void handle(final WebEvent<String> event) {  
             SwingUtilities.invokeLater(new Runnable() {  
               @Override  
               public void run() {  
                 lblStatus.setText(event.getData());  
               }  
             });  
           }  
         });  
         engine.getLoadWorker().workDoneProperty().addListener(new ChangeListener<Number>() {  
           @Override  
           public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, final Number newValue) {  
             SwingUtilities.invokeLater(new Runnable() {  
               @Override  
               public void run() {  
                 progressBar.setValue(newValue.intValue());  
               }  
             });  
           }  
         });  
         engine.getLoadWorker()  
             .stateProperty()  
             .addListener(new ChangeListener<Worker.State>() {  
               @Override  
               public void changed(ObservableValue<? extends Worker.State> observableValue, Worker.State state, Worker.State state2) {  
                 if(state2 == Worker.State.SUCCEEDED){  
                   System.out.println("Completed");  
                 }  
               }  
             });  
         engine.getLoadWorker()  
             .exceptionProperty()  
             .addListener(new ChangeListener<Throwable>() {  
               public void changed(ObservableValue<? extends Throwable> o, Throwable old, final Throwable value) {  
                 if (engine.getLoadWorker().getState() == FAILED) {  
                   SwingUtilities.invokeLater(new Runnable() {  
                     @Override public void run() {  
                       JOptionPane.showMessageDialog(  
                           panel,  
                           (value != null) ?  
                               engine.getLocation() + "\n" + value.getMessage() :  
                               engine.getLocation() + "\nUnexpected error.",  
                           "Loading error...",  
                           JOptionPane.ERROR_MESSAGE);  
                     }  
                   });  
                 }  
               }  
             });  
         jfxPanel.setScene(new Scene(view));  
       }  
     });  
   }  
   public void loadURL(final String url) {  
     TrustManager[] trustAllCerts = new TrustManager[] {  
         new X509TrustManager() {  
           public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
             return null;  
           }  
           public void checkClientTrusted(  
               java.security.cert.X509Certificate[] certs, String authType) {  
           }  
           public void checkServerTrusted(  
               java.security.cert.X509Certificate[] certs, String authType) {  
           }  
         }  
     };  
     // Install the all-trusting trust manager  
     try {  
       SSLContext sc = SSLContext.getInstance("SSL");  
       sc.init(null, trustAllCerts, new java.security.SecureRandom());  
       HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
     } catch (GeneralSecurityException e) {  
     }  
     Platform.runLater(new Runnable() {  
       @Override  
       public void run() {  
         String tmp = toURL(url);  
         if (tmp == null) {  
           tmp = toURL("http://" + url);  
         }  
         engine.load(tmp);  
       }  
     });  
   }  
   private static String toURL(String str) {  
     try {  
       return new URL(str).toExternalForm();  
     } catch (MalformedURLException exception) {  
       return null;  
     }  
   }  
   public static void main(String[] args) {  
     SwingUtilities.invokeLater(new Runnable() {  
       public void run() {  
         SimpleWebBrowser browser = new SimpleWebBrowser();  
         browser.setVisible(true);  
         browser.loadURL("https://self-sgned-url.com");  
         try {  
           Thread.sleep(5000);  
         } catch (InterruptedException e) {  
           e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.  
         }  
       }  
     });  
   }  
 }  

Done.

Saturday 5 December 2015

How to programmatically extract the zip file using Java ?

This article is about how to write a utility class for extracting files and directories in a compressed zip archive, using built-in Java API.
The java.util.zip package provides the following classes for extracting files and directories from a ZIP archive:
    • ZipInputStream: this is the main class which can be used for reading zip file and extracting files and directories (entries) within the archive. Here are some important usages of this class:
      • read a zip via its constructor ZipInputStream(FileInputStream)
      • read entries of files and directories via method getNextEntry()
      • read binary data of current entry via method read(byte)
      • close current entry via method closeEntry()
      • close the zip file via method close()
       
    • ZipEntry: this class represents an entry in the zip file. Each file or directory is represented as a ZipEntry object. Its method getName() returns a String which represents path of the file/directory. The path is in the following form:
      folder_1/subfolder_1/subfolder_2/…/subfolder_n/file.ext
       
Based on the path of a ZipEntry, we re-create directory structure when extracting the zip file. In addition, the BufferedOutputStream class is used to write content of the current ZipEntry to a file on disk, via its method write(byte[] bytes, int offset, int length). Following is source code of UnzipUtility.java class:

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
 
/**
 * This utility extracts files and directories of a standard zip file to
 * a destination directory.
 * @author www.codejava.net
 *
 */
public class UnzipUtility {
    /**
     * Size of the buffer to read/write data
     */
    private static final int BUFFER_SIZE = 4096;
    /**
     * Extracts a zip file specified by the zipFilePath to a directory specified by
     * destDirectory (will be created if does not exists)
     * @param zipFilePath
     * @param destDirectory
     * @throws IOException
     */
    public void unzip(String zipFilePath, String destDirectory) throws IOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry entry = zipIn.getNextEntry();
        // iterates over entries in the zip file
        while (entry != null) {
            String filePath = destDirectory + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                // if the entry is a file, extracts it
                extractFile(zipIn, filePath);
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    }
    /**
     * Extracts a zip entry (file entry)
     * @param zipIn
     * @param filePath
     * @throws IOException
     */
    private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] bytesIn = new byte[BUFFER_SIZE];
        int read = 0;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
        bos.close();
    }
}

How to download a zip file using Java code?

Below is the code snippet that will show you how to download the zip file from any url and save it to your local machine using java code.


import java.net.*;
import java.io.*;
 
public class URLConnectionReader {
    public void download_zip_file(String save_to) {
        URL url = new URL("http://pc-2011.com/downloads/test.zip");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        InputStream in = connection.getInputStream();
        FileOutputStream out = new FileOutputStream("test.zip");
        copy(in, out, 1024);
        out.close();
    }
 
    public static void copy(InputStream input, OutputStream output, int bufferSize) throws IOException {
        byte[] buf = new byte[bufferSize];
        int n = input.read(buf);
        while (n >= 0) {
            output.write(buf, 0, n);
            n = input.read(buf);
        }
        output.flush();
    }
}