Management.Projects.java Source code

Java tutorial

Introduction

Here is the source code for Management.Projects.java

Source

package Management;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.poi.xwpf.usermodel.Borders;
import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import sun.misc.BASE64Decoder;

/*
 * 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.
 */
/**
 *
 * @author hilsierivan - juan carlos core
 */
public class Projects {

    Conexion con;
    Users user;

    public Projects() {
        con = new Conexion();

        con.Connect();
        user = new Users();
    }

    public String getNameProject(int idProject) {

        String nameProject = "";

        ResultSet set = con.Search("select*from Proyectos where idProyecto=" + idProject + "");

        try {
            while (set.next()) {
                nameProject = set.getString("Nombre_Proyecto");

            }
        } catch (SQLException ex) {
            Logger.getLogger(Projects.class.getName()).log(Level.SEVERE, null, ex);
        }

        return nameProject;
    }

    public String getStyleOptionProject(int idProject) {

        String styleOptionProject = "";

        ResultSet set = con.Search("select*from Proyectos where idProyecto=" + idProject + "");

        try {
            while (set.next()) {
                styleOptionProject = set.getString("idEstilo_opcion_proyecto");

            }
        } catch (SQLException ex) {
            Logger.getLogger(Projects.class.getName()).log(Level.SEVERE, null, ex);
        }

        return styleOptionProject;
    }

    public boolean isAdmin(int idUser, int idProject) {

        boolean answer = false;
        ResultSet set = con.Search(
                "select*from administradores where idUsuario=" + idUser + " and idProyecto=" + idProject + "");

        try {
            while (set.next()) {
                answer = true;
            }
        } catch (SQLException ex) {
            Logger.getLogger(Projects.class.getName()).log(Level.SEVERE, null, ex);
        }

        return answer;
    }

    public boolean isParticipant(int idUser, int idProject) {

        boolean r = false;
        ResultSet set = con.Search(
                "select*from usuarios_proyectos where idUsuario=" + idUser + " and idProyecto=" + idProject);
        try {
            while (set.next()) {
                r = true;
            }
        } catch (SQLException ex) {
            Logger.getLogger(Projects.class.getName()).log(Level.SEVERE, null, ex);
        }

        return r;
    }

    public String AddUsersToProject(int idUser, int idProject) {

        if (con.Insert(
                "insert into usuarios_proyectos(idUsuario,idProyecto)values(" + idUser + "," + idProject + ")")) {

            return "usuario agregado al proyecto con exito";
        } else {
            return "fallo";
        }

    }

    public ResultSet getAllProjects(int idUser) {
        ResultSet set = null;

        set = con.Search("SELECT *\n" + "FROM usuarios u\n"
                + "INNER JOIN usuarios_proyectos up ON u.idUsuario = up.idUsuario\n"
                + "INNER JOIN proyectos p ON up.idProyecto = p.idProyecto\n" + "WHERE up.idUsuario =" + idUser);

        return set;
    }

    public ResultSet getAllStylesProject() {
        ResultSet set = null;

        set = con.Search("SELECT * FROM estilo_proyecto");

        return set;
    }

    public ResultSet getAllStylesProjectOptions() {
        ResultSet set = null;

        set = con.Search("SELECT * FROM opciones_estilo_proyecto");

        return set;
    }

    public ResultSet getProjectsAdmin(int idUser) {

        ResultSet set = null;

        set = con.Search("SELECT *\n" + "FROM administradores a\n"
                + "INNER JOIN usuarios u ON a.idUsuario = u.idUsuario\n"
                + "INNER JOIN proyectos p ON a.idProyecto = p.idProyecto\n" + "WHERE a.idUsuario =" + idUser);

        return set;
    }

    public int getIdProject(String name) {
        int idProject = 0;

        ResultSet set = con.Search("select idProyecto from Proyectos where Nombre_Proyecto='" + name + "'");

        try {
            while (set.next()) {

                idProject = set.getInt(1);

            }
        } catch (SQLException ex) {
            System.out.println(ex.toString());
        }

        return idProject;
    }

    public int getIdStyleProject(String name) {
        int idStyleProject = 0;

        ResultSet set = con.Search("select id from estilo_proyecto where nombre='" + name + "'");

        try {
            while (set.next()) {

                idStyleProject = set.getInt(1);

            }
        } catch (SQLException ex) {
            System.out.println(ex.toString());
        }

        return idStyleProject;
    }

    public int getIdStyleOptionProject(String name) {
        int idStyleOptionProject = 0;

        ResultSet set = con.Search("select id from opciones_estilo_proyecto where nombre='" + name + "'");

        try {
            while (set.next()) {

                idStyleOptionProject = set.getInt(1);

            }
        } catch (SQLException ex) {
            System.out.println(ex.toString());
        }

        return idStyleOptionProject;
    }

    public String NewProject(int ProjectAdmin, String ProjectName, String idEstilo, String idEstilo_opcion,
            String Category, String Description, String CreatedDate) {
        String resul = "";

        int idProject = 0;
        int idStyle = getIdStyleProject(idEstilo);
        int idStyleOption = getIdStyleOptionProject(idEstilo_opcion);
        System.err.println(idStyle);

        if (con.Insert(
                "insert into proyectos(idProyecto,Nombre_Proyecto,idEstilo_proyecto,idEstilo_opcion_proyecto,Categoria,Descripcion,Fecha_Creacion)"
                        + "values(NULL,'" + ProjectName + "','" + idStyle + "','"
                        + (idStyle == 1 ? 0 : idStyleOption) + "','" + Category + "','" + Description + "','"
                        + CreatedDate + "')")) {

            try {
                ResultSet set = con
                        .Search("select idProyecto from Proyectos where Nombre_Proyecto='" + ProjectName + "'");

                while (set.next()) {
                    idProject = set.getInt(1);

                }

            } catch (SQLException ex) {
                System.out.println(ex.toString());
            }
            if (con.Insert("insert into Administradores(idAdministrador,idUsuario,idProyecto)values(NULL,"
                    + ProjectAdmin + "," + idProject + ")")) {

                resul = "El proyecto fue agregado exitosamente";
            }

        } else {

            resul = "fallo";
        }

        return resul;
    }

    public String UpdateProject(int idProject, String ProjectName, String Category, String Description) {
        String r = "";

        if (con.Update("update Proyectos set Nombre_Proyecto='" + ProjectName + "',Categoria='" + Category
                + "',Descripcion='" + Description + "'where idProyecto=" + idProject)) {

            r = "Proyecto Actualizado con exito";

        } else {

            r = "no se pudo actualizar";
        }

        return r;
    }

    public String DeleteProject(int idProject) {

        String d = "";
        boolean exito = false;
        File fileProject = new File(
                "C:\\Users\\hilsierivan\\Documents\\NetBeansProjects\\StickMaps\\web\\Proyectos\\Proyecto"
                        + idProject + ".txt");

        boolean res = con.Delete("delete from Proyectos where idProyecto=" + idProject);

        try {

            if (fileProject.exists()) {

                if (fileProject.delete()) {
                    exito = true;

                }
            }

        } catch (Exception ex) {
            System.out.println(ex.toString());
        }

        if (res || exito) {

            d = "el proyecto fue elimindado con exito";
        }

        return d;
    }

    public String saveProject(int idProject, String json) {
        FileWriter fichero = null;

        String datos = "Proyecto" + idProject;
        try {
            // Creas la instancia del fichero
            fichero = new FileWriter(System.getProperty("user.home")
                    + "/Documents/NetBeansProjects/StickMaps/web/Proyectos/Proyecto" + idProject + ".txt");
            // El carcter \r\n es el que hace que salte una linia en el fichero despus de escribir
            fichero.write(json + "\r\n");
            // Cierras el fichero
            fichero.close();
        } catch (IOException ioe) {
            System.out.println(ioe.toString());
            return ioe.toString();
            // Aqui pones lo que quieres que haga cuando se da una excepcin de escritura
        }

        return "exito";
    }

    public String ShowProject(int idProject) {

        String cadena = "", json = "";
        FileReader fr = null;
        File f = new File(System.getProperty("user.home")
                + "/Documents/NetBeansProjects/StickMaps/web/Proyectos/Proyecto" + idProject + ".txt");

        System.out.println(System.getProperty("user.home"));

        if (f.exists()) {

            try {
                fr = new FileReader(f);
                BufferedReader bf = new BufferedReader(fr);

                while ((cadena = bf.readLine()) != null) {
                    json += cadena;

                }
            } catch (FileNotFoundException ex) {
                return ex.toString();
            } catch (IOException ex) {
                return ex.toString();
            }
            try {
                fr.close();
            } catch (IOException ex) {
                return ex.toString();
            }

        } else {
            json = "{\"File\":\"No\"}";
        }

        return json;
    }

    public String CreateImage(int idProject, String base64) {
        String res = "";

        String basearray[] = base64.split(",");
        System.out.println(basearray[1]);

        String base = basearray[1];

        byte[] btDataFile = null;
        try {
            btDataFile = new sun.misc.BASE64Decoder().decodeBuffer(base);
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
        File of = new File(System.getProperty("user.home")
                + "/Documents/NetBeansProjects/StickMaps/web/MapImages/Proyecto" + idProject + ".png");

        FileOutputStream osf = null;
        try {
            osf = new FileOutputStream(of);
        } catch (FileNotFoundException ex) {
            System.out.println(ex.toString());
        }
        try {
            osf.write(btDataFile);
            res = "archivo creado correctamente";
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
        try {
            osf.flush();
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }

        return res;
    }

    public String CrearMinuta(String datos[], int idProject, String[] Asistentes, String[] puntos)
            throws IOException {
        String result = "";
        ArrayList<XWPFParagraph> listfecha = new ArrayList<>();
        ArrayList<XWPFParagraph> listasistentes = new ArrayList<>();
        ArrayList<XWPFParagraph> listpuntos = new ArrayList<>();
        XWPFDocument doc = new XWPFDocument();
        int i;
        XWPFParagraph p3;
        XWPFParagraph p1 = doc.createParagraph();
        p1.setAlignment(ParagraphAlignment.CENTER);
        p1.setBorderBottom(Borders.DOUBLE);
        p1.setBorderTop(Borders.DOUBLE);
        XWPFRun r1 = p1.createRun();
        r1.setBold(true);
        r1.setText("Datos de la minuta");
        r1.setBold(true);
        for (i = 0; i < datos.length; i++) {
            p3 = doc.createParagraph();
            listfecha.add(p3);

        }
        i = 0;
        for (XWPFParagraph para : listfecha) {
            XWPFRun r2 = para.createRun();
            r2.setText(datos[i]);
            r2.setFontSize(20);
            i++;
        }

        XWPFParagraph parrafoAsistentes = doc.createParagraph();
        parrafoAsistentes.setAlignment(ParagraphAlignment.CENTER);
        parrafoAsistentes.setBorderBottom(Borders.DOUBLE);
        parrafoAsistentes.setBorderTop(Borders.DOUBLE);
        XWPFRun r2 = parrafoAsistentes.createRun();
        r2.setBold(true);
        r2.setText("Asistentes:");
        r2.setBold(true);

        XWPFParagraph p4;
        for (i = 0; i < Asistentes.length; i++) {
            p4 = doc.createParagraph();
            listasistentes.add(p4);

        }

        i = 0;
        for (XWPFParagraph para : listasistentes) {
            XWPFRun r3 = para.createRun();
            r3.setText(Asistentes[i]);
            r3.setFontSize(20);
            i++;
        }

        XWPFParagraph parrafoPuntos = doc.createParagraph();
        parrafoPuntos.setAlignment(ParagraphAlignment.CENTER);
        parrafoPuntos.setBorderBottom(Borders.DOUBLE);
        parrafoPuntos.setBorderTop(Borders.DOUBLE);
        XWPFRun r3 = parrafoPuntos.createRun();
        r3.setBold(true);
        r3.setText("Puntos a Tratar:");
        r3.setBold(true);

        XWPFParagraph p5;
        for (i = 0; i < puntos.length; i++) {
            p5 = doc.createParagraph();
            listpuntos.add(p5);

        }
        i = 0;
        for (XWPFParagraph para : listpuntos) {
            XWPFRun r4 = para.createRun();
            r4.setText(puntos[i]);
            r4.setFontSize(20);
            i++;
        }

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(System.getProperty("user.home")
                    + "/Documents/NetBeansProjects/StickMaps/web/Minutas/Minuta" + idProject + ".docx");
        } catch (FileNotFoundException ex) {
            System.out.println(ex.toString());
            return ex.toString();
        }
        doc.write(out);
        result = "bien";
        out.close();

        return result;
    }

    public boolean SendEmailToUser(String from, String to, String subject, String message) {

        //Instance class Properties who will have contain the session properties
        Properties props = new Properties();
        // Mail host name, is smtp.gmail.com
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        // Transport Layer Security (TLS) if it able
        props.setProperty("mail.smtp.starttls.enable", "true");
        // Gmail port for send mails
        props.setProperty("mail.smtp.port", "587");
        //User Name
        props.setProperty("mail.smtp.user", from);
        // If it requieres user and password for connecting
        props.setProperty("mail.smtp.auth", "true");
        //Instance class Session and give the previous properties 
        Session session = Session.getDefaultInstance(props);
        //We've to put setDebug(true) in order to get more information in Output about what's happening.
        session.setDebug(true);

        MimeMessage nMessage = new MimeMessage(session);
        try {
            // Quien envia el correo
            nMessage.setFrom(new InternetAddress(from));
            // A quien va dirigido
            nMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            nMessage.setSubject(subject);
            //nMessage.setText(message, "ISO-8859-1", "html");

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(message);

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            //addAtachments(attachments, multipart);
            nMessage.setContent(multipart);

            Transport t = session.getTransport("smtp");
            t.connect("faddupchiapas@gmail.com", "CTvPacXjMM56yMjR");
            t.sendMessage(nMessage, nMessage.getAllRecipients());
            t.close();
            return true;
        } catch (Exception ex) {
            System.out.println("Error: " + ex.getMessage());
            return false;
        }
    }

}