finale.year.stage.utility.Util.java Source code

Java tutorial

Introduction

Here is the source code for finale.year.stage.utility.Util.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package finale.year.stage.utility;

import com.gottibujiku.httpjsonexchange.main.HttpJSONExchange;
import finale.year.stage.main.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PipedWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import javax.swing.*;
import javax.xml.bind.DatatypeConverter;
import org.json.*;

/**
 *
 * @author philipchicco
 */
public class Util {
    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    private final static String SHA_256 = "SHA-256";
    public static File userFile = null;
    public static boolean CHECK = false;
    //public static final String ROOT   = "https://stage-intellix.rhcloud.com/";
    public static final String ROOT = "http://192.168.1.33:8080/";
    private static mainF mainFrame = null;

    public static boolean isAv(JFrame frame) {
        //Try to access the server 
        try {
            final URL url = new URL(ROOT);
            final URLConnection con = url.openConnection();
            con.connect();

        } catch (MalformedURLException e) {
            JOptionPane.showMessageDialog(frame, "Check Internet Connection");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(frame, "Check Internet Connection");
            return false;
        }
        return true;
    }

    public static boolean validateEmail(String hex) {
        Matcher matcher;
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        matcher = pattern.matcher(hex);

        return matcher.matches();
    }

    public static JSONObject login(String email, String password) {
        HttpJSONExchange exchange = new HttpJSONExchange();

        HashMap<String, String> headers = new HashMap<String, String>();
        HashMap<String, String> params = new HashMap<String, String>();
        //Path  of Server on Machine
        //String url = LOCAL+"login"; 
        String url = ROOT + "login";

        headers.put("User-Agent", "desktop");
        params.put("email", email);
        try {
            if (CHECK == false) //Not Encrypted of Existing config.txt with Pass
                params.put("password", encryptPassword(password));
            else
                params.put("password", password);

        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        //Handle Unknown Host
        JSONObject json = null;

        if (isAv(mainF.mainFrame)) //Check Internet Connection 
            json = exchange.sendPOSTRequest(url, params, headers);

        //Return Result to LoginWindow
        return json;
    }

    public static JSONObject signUp(String email, String password, String id) {
        HttpJSONExchange exchange = new HttpJSONExchange();

        HashMap<String, String> headers = new HashMap<>();
        HashMap<String, String> params = new HashMap<>();
        String url = ROOT + "register";

        headers.put("User-Agent", "desktop");
        params.put("email", email);
        try {
            params.put("password", encryptPassword(password));
        } catch (NoSuchAlgorithmException ex) {
            Inscription.updateStatus("Sign Up Error : " + ex.getMessage());
        }
        params.put("id", id);

        JSONObject json = null;
        if (isAv(mainF.mainFrame)) //Check Internet Connection 
            json = exchange.sendPOSTRequest(url, params, headers);

        //Return Result to InscriptionWindow
        return json;
    }

    //Encrypt password before sending
    public static String encryptPassword(String unencrypted) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(SHA_256);
        md.update(unencrypted.getBytes());
        return DatatypeConverter.printHexBinary(md.digest()).toLowerCase();
    }

    /**
     * @param noparams
     * Called when user wants to login without entering credentials
     * We must  read from config.txt 
     */
    public static void openLogin() {
        mainF.mainFrame.dispose();
        mainFrame = new mainF();
        mainFrame.launchFrame(new Authentification(), mainFrame);
    }

    public static void emptyFile() {
        //Empty the File after User Has Logged Out
        //userFile.delete();

        String response = null;
        ObjectOutputStream writer = null;
        userFile = new File("config.txt");

        //Write to File
        try {

            writer = new ObjectOutputStream(new FileOutputStream(userFile));
            writer.writeObject(""); //Write Empty to File
            writer.writeObject(""); //Write Empty to File
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();

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

        } finally {
            if (writer != null) {
                try {
                    writer.close(); //Close the Reader
                } catch (IOException ex) {
                    ex.printStackTrace();
                    return;
                }
            }
        } //End of If Block

    }

    public static void rememberLogin() {
        ObjectInputStream reader = null;
        userFile = new File("config.txt");
        //User already has a file on the System with Credentials
        //Check for Existance of config.txt
        try {
            //Open File
            reader = new ObjectInputStream(new FileInputStream(userFile));
            String email_Object = (String) reader.readObject();
            String passw_Object = (String) reader.readObject();
            if (!email_Object.equals("")) {
                //Login in Directly
                System.out.println("email :" + email_Object);
                try {
                    Authentification.handleResponse(login(email_Object, passw_Object));
                } catch (Exception e) {
                    Authentification.updateStatus("No Internet : Server Connnection failed " + e.getMessage());
                }
            } else {
                openLogin();
            }

        } catch (FileNotFoundException ex) {
            //Call AUthentification

            System.out.println("Config.txt Missing");
            openLogin();
            return;
        } catch (IOException ex) {

        } catch (ClassNotFoundException ex) {

        } finally {
            if (reader != null) {
                try {
                    reader.close(); //Close the Reader
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    /**
     * User wishes to save credentials on current system directory
     * First time instance , provided he supplies his credentials
     * Only checking for one user at present
     * @param email
     * @param password 
     */
    public static void rememberLogin(String email, String password) {
        //If user is has checked Remember me for first time
        String response = null;
        ObjectOutputStream writer = null;
        userFile = new File("config.txt");

        //Write to File
        try {

            writer = new ObjectOutputStream(new FileOutputStream(userFile));
            writer.writeObject(email); //Write Email to File
            writer.writeObject(encryptPassword(password)); //Write Password to File
            Authentification.handleResponse(login(email, encryptPassword(password)));
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();

        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close(); //Close the Reader
                } catch (IOException ex) {
                    ex.printStackTrace();
                    return;
                }
            }
        } //End of If Block
    }

    public static boolean fileExists(File f) {
        f = new File("config.txt");
        try {
            if (f.exists())
                return true;

        } catch (NullPointerException e) {
            Authentification.updateStatus(e.getMessage());
            return false;
        }
        return false;
    }

    //Send Request to Server to get new Login credentials
    public static JSONObject forgotLogin(String email) {

        HttpJSONExchange exchange = new HttpJSONExchange();

        HashMap<String, String> headers = new HashMap<>();
        HashMap<String, String> params = new HashMap<>();
        //Server URL on Network
        String url = ROOT + "forgot-password";

        headers.put("User-Agent", "desktop");
        headers.put("demand", "yes");
        params.put("email", email);

        JSONObject json = null;
        if (isAv(mainF.mainFrame)) //Check Internet Connection 
            json = exchange.sendPOSTRequest(url, params, headers);

        //Send Result to forgotLogin Handler
        return json;
    }

    public static JSONObject forgotLogin(String email, String password, String id) {
        HttpJSONExchange exchange = new HttpJSONExchange();

        HashMap<String, String> headers = new HashMap<>();
        HashMap<String, String> params = new HashMap<>();
        String url = ROOT + "forgot-password";

        headers.put("User-Agent", "desktop");
        headers.put("demand", "yes");
        params.put("email", email);
        try {
            params.put("password", encryptPassword(password));
        } catch (NoSuchAlgorithmException ex) {
            forgotLogin.updateStatus("Error Occured : " + ex.getCause());
        }
        params.put("id", id);

        JSONObject json = null;
        if (isAv(mainF.mainFrame)) //Check Internet Connection 
            json = exchange.sendPOSTRequest(url, params, headers);

        //Return Result to InscriptionWindow
        return json;
    }

    /**
     * Responsable proposes a theme to add to the Internship program
     * @param theme 
     */
    public static JSONObject addTheme(String title, String descritption, String email, int type) {
        HttpJSONExchange exchange = new HttpJSONExchange();

        HashMap<String, String> params = new HashMap<String, String>();
        HashMap<String, String> headers = new HashMap<String, String>();
        String url = ROOT + "manage-theme";

        params.put("title", title); //Theme title
        params.put("description", descritption); //Description of Theme
        params.put("type", Integer.toString(type)); //Type
        params.put("email", email); //Email

        headers.put("User-Agent", "desktop");
        params.put("action", "add"); //Header action for adding theme

        JSONObject json = null;
        if (isAv(mainF.mainFrame)) //Check Internet Connection 
            json = exchange.sendPOSTRequest(url, params, headers);

        return json;
    }

    public static JSONObject listThemes() {
        HttpJSONExchange exchange = new HttpJSONExchange();

        HashMap<String, String> params = new HashMap<String, String>();
        HashMap<String, String> headers = new HashMap<String, String>();
        String url = ROOT + "manage-theme";

        headers.put("User-Agent", "desktop");
        params.put("action", "list"); //Header action for listing themes

        JSONObject json = null;
        if (isAv(mainF.mainFrame)) //Check Internet Connection 
            json = exchange.sendPOSTRequest(url, params, headers);

        return json;
    }

    public static JSONObject modifyTheme(String title, String description, int type, String idTheme) {
        HttpJSONExchange exchange = new HttpJSONExchange();

        HashMap<String, String> params = new HashMap<String, String>();
        HashMap<String, String> headers = new HashMap<String, String>();
        String url = ROOT + "manage-theme";

        headers.put("User-Agent", "desktop");
        params.put("action", "modify"); //Header action for modifying themes
        params.put("title", title); //Theme title
        params.put("description", description); //Description of Theme
        params.put("type", Integer.toString(type)); //Type
        params.put("id", idTheme);

        JSONObject json = null;
        if (isAv(mainF.mainFrame)) //Check Internet Connection 
            json = exchange.sendPOSTRequest(url, params, headers);

        return json;
    }

    public static JSONObject deleteTheme(String id, int type) {

        HttpJSONExchange exchange = new HttpJSONExchange();

        HashMap<String, String> params = new HashMap<String, String>();
        HashMap<String, String> headers = new HashMap<String, String>();
        String url = ROOT + "manage-theme";
        headers.put("User-Agent", "desktop");
        params.put("action", "delete"); //Header action for delete themes
        params.put("id", id); //Theme id
        params.put("type", Integer.toString(type));

        JSONObject json = null;
        if (isAv(mainF.mainFrame)) //Check Internet Connection 
            json = exchange.sendPOSTRequest(url, params, headers);
        ;

        return json;
    }

    /**
     * Methods handling the deliberation process 
     */
    public static JSONObject listReclammations() {
        HttpJSONExchange exchange = new HttpJSONExchange();

        HashMap<String, String> params = new HashMap<String, String>();
        HashMap<String, String> headers = new HashMap<String, String>();
        String url = ROOT + "manage-reclammation";

        params.put("action", "list"); //Header action for listing themes
        headers.put("User-Agent", "desktop");

        JSONObject json = null;
        if (isAv(mainF.mainFrame)) //Check Internet Connection 
            json = exchange.sendPOSTRequest(url, params, headers);

        return json;

    }

    public static JSONObject transferReclammation(String id) {
        HttpJSONExchange exchange = new HttpJSONExchange();

        HashMap<String, String> params = new HashMap<String, String>();
        HashMap<String, String> headers = new HashMap<String, String>();
        String url = ROOT + "manage-reclammation";

        headers.put("User-Agent", "desktop");
        params.put("action", "transfer"); //parameter action for listing transfering reclammation
        params.put("id", id); // id of reclammation to transfer

        JSONObject json = null;
        if (isAv(mainF.mainFrame)) //Check Internet Connection 
            json = exchange.sendPOSTRequest(url, params, headers);

        return json;

    }

    public static JSONObject viewReclammation(String id) {
        HttpJSONExchange exchange = new HttpJSONExchange();

        HashMap<String, String> params = new HashMap<String, String>();
        HashMap<String, String> headers = new HashMap<String, String>();
        String url = ROOT + "manage-reclammation";

        headers.put("User-Agent", "desktop");
        params.put("action", "transfer"); //parameter action for listing transfering reclammation
        params.put("id", id); // id of reclammation to transfer

        JSONObject json = null;
        if (isAv(mainF.mainFrame)) //Check Internet Connection 
            json = exchange.sendPOSTRequest(url, params, headers);

        return json;

    }

    public static JSONObject deleteRec(String id) {
        HttpJSONExchange exchange = new HttpJSONExchange();

        HashMap<String, String> params = new HashMap<String, String>();
        HashMap<String, String> headers = new HashMap<String, String>();
        String url = ROOT + "manage-reclammation";

        headers.put("User-Agent", "desktop");

        params.put("action", "delete"); //parameter action for listing transfering reclammation
        params.put("id", id); // id of reclammation to transfer

        JSONObject json = null;
        if (isAv(mainF.mainFrame)) //Check Internet Connection 
            json = exchange.sendPOSTRequest(url, params, headers);

        return json;

    }

    public static JSONObject lancerDeliberation() {
        HttpJSONExchange exchange = new HttpJSONExchange();

        HashMap<String, String> params = new HashMap<String, String>();
        HashMap<String, String> headers = new HashMap<String, String>();
        String url = ROOT + "manage-deliberations";

        headers.put("User-Agent", "desktop");

        params.put("action", "lancer"); //parameter starting deliberations

        JSONObject json = null;
        if (isAv(mainF.mainFrame)) //Check Internet Connection 
            json = exchange.sendPOSTRequest(url, params, headers);

        return json;
    }

    public static JSONObject modify() {
        return null;
    }

    public static JSONObject supprimer() {
        return null;
    }

}