Creating a data management system using Java - 2

in #utopian-io7 years ago (edited)

What Will I Learn?

  • You will learn to Create a School Data management system using SQlite and Netbeans IDE

Requirements

  • Java Knowlege
  • SQLite and Netbeans IDE

Difficulty

  • Intermediate

Tutorial Contents

In the last tutorial, we have created an interface for the program and also the database for the program.
Functions including; Adding data, Pulling data from database into table and Creating Data Card from databse.

For this tutorial, we will be doing the following:

  1. Arranging the Items in the Data Card Dynamically and Adding Image
  2. Editing Data in the database.
  3. Sending datacard over mail

Dynamic Arrangement of Datacard and Adding Image
   try {
            Document doc = new Document();
            PdfWriter write = PdfWriter.getInstance(doc, new FileOutputStream("StudentData.pdf"));

            doc.open();

            com.itextpdf.text.Image passport = com.itextpdf.text.Image.getInstance("pass.jpg");
            passport.scaleToFit(100, 100);

            Paragraph x = new Paragraph("Student Data Card", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 24, Font.BOLD, BaseColor.CYAN));
            x.setAlignment(Paragraph.ALIGN_CENTER);
            doc.add(x);
            doc.add(new Paragraph(" "));

            doc.add(new Paragraph(" "));
            doc.add(passport);
            PdfContentByte over = write.getDirectContent();
            over.saveState();
            BaseFont bf = BaseFont.createFont();
            over.beginText();
            over.setFontAndSize(bf, 14);
            over.setTextMatrix(150, 680);
            over.showText("Student Name:               " + fullname.getText());
            over.endText();
            over.restoreState();

            over.saveState();

            over.beginText();
            over.setFontAndSize(bf, 14);
            over.setTextMatrix(150, 660);
            over.showText("Registration Number:         " + regnum.getText());
            over.endText();
            over.restoreState();

            over.saveState();

            over.beginText();
            over.setFontAndSize(bf, 14);
            over.setTextMatrix(150, 640);
            over.showText("Student Year:                 " + year.getText());
            over.endText();
            over.restoreState();

            doc.close();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }

The code above is a little bit differnet from what we used in creating the reoprt fromlast tutorial, this is because we have added PdfContentByte method in the process. This method allows more graphical manipulations, giving room to a more firendly data card.
com.itextpdf.text.Image passport = com.itextpdf.text.Image.getInstance("pass.jpg"); This line creates an Image from the selected image, pass.jpg. com.itextpdf.text.Image was used to avoid multiple imports for Image processing, this is because we have previously imported java.awt.Image which was used for uploading the image into the program before it is being stored in the database, having one more import for image woulld cause cross refrencing which would not allow our program work.

passport.scaleToFit(100, 100); This gives the image a scaled limit of 100X100, This method would not affect the image by strecthing, it will only keep it in a 100X100 scale, if increased, the Image would also increase in display size on the document.

doc.add(new Paragraph(" "));

doc.add(new Paragraph(" "));

These two lines were used to add spacing in the document, ther are other ways to but this is easier to understand.

BaseFont bf = BaseFont.createFont(); This line creates a font from the default font of your pc.

over.saveState();This here saves the current graphic properties of the document, before it's state in now changed. First we use over.beginText(); to start the text editing process, this method allows you to carry out all the graphic effects you can on the text, after which over.endText(); is used to conclude the editing.

over.setTextMatrix(150, 640); This line sets the location of the text dynamically as specified by the points selected in the parenthesis.

over.showText("Student Year: " + year.getText()); This adds the text to the ContentByte space.

Your report should look like this now:
report.png


Editing Data in database

To edit data from the program, first create a new Jframe in source packages to hold same data as in the section where we add information.

Edit data Frame

The edit frame is then set to receive a string upon called. Using a methodpublic editdata(String data) {what the method should do}, in this case I have created the method to pull data from the database and add to the fields in the frame.

public editdata(String data) {

        initComponents();

        conn = databaseconnection.Connect();
        try {
            String sql = "Select * from Student where RegistrationNumber = '" + data + "'";
            pst = conn.prepareStatement(sql);
            rs = pst.executeQuery();
            if (rs.next()) {
                fulnametxt.setText(rs.getString("Fullname"));
                regisnum.setText(rs.getString("RegistrationNumber"));
                yeartxt.setSelectedItem(rs.getString("Year"));
                depttxt.setText(rs.getString("Department"));
                byte[] image = rs.getBytes("Passport");
                format = new ImageIcon(image);
                Image img = format.getImage();
                Image newimage = img.getScaledInstance(photo.getWidth(), photo.getHeight(), Image.SCALE_SMOOTH);
                ImageIcon images = new ImageIcon(newimage);
                photo.setIcon(images);
            }
            rs.close();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }

Most of this has been explained in the previous tutorial, but here's what this method does.

It simply starts with a string that could be from another frame and then uses this string to search for information from the database.

Now set the Edit button from the Home screen to Pass the student registration number to the edit frame on click. Under the actionperformed event of the edit button in the home screen add this

    private void editbtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
     
        editdata s = new editdata(regnum.getText());
        s.setVisible(true);

        // TODO add your handling code here:
    }    

Because we have created a string variable to be able to hold data from another frame, regnum.getText() pulls the string which is the registration number in the label and passes it into String regnum in the editdata frame before the frame is opened using .setVisible();.

Finally to Update the data;

    String sql = "Update Student set "
                + "`Fullname` = '" + fulnametxt.getText() + "', `Year` = '" + yeartxt.getSelectedItem().toString() + "',"
                + " `Department` = '" + depttxt.getText() + "', `Passport` = '" + Imagedata + "' where RegistrationNumber = '" + regisnum.getText() + "'";
        try {
            pst = conn.prepareStatement(sql);

            pst.execute();

            JOptionPane.showMessageDialog(null, "Information Saved");
            dispose();

            rs.close();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }

First the SQL Query, we have used the Update Query because that is the required here's the syntax:
Update 'tablename' Set 'Columnname' = 'data' where 'Column name' = 'data' This is basically all you need.

In the previous tutorial I explained you can easily add the data into the sql statement directly by concatenating strings using '+' sign before and after the method used, this might make your work a little bit scattered but it's faster.

JOptionPane.showMessageDialog(null, "Information Saved"); This line is displayed once the information has been saved, null here keeps the information display pane in the middle of the screen.

dispose(); This exits the edit frame without closing the main frame, if the exit button on the frame is clicked it will close the main frame also.

Now that is all about editing the data in the database, we move to mail.


Sending data through mail
  Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthenticati("email", "password");

            }

        }
        );
        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("email"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(jTextField1.getText()));
            message.setSubject(jTextField3.getText());

            MimeBodyPart messagebodypart = new MimeBodyPart();
            messagebodypart.setText(jTextArea1.getText());
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messagebodypart);

            messagebodypart = new MimeBodyPart();
            DataSource source = new FileDataSource("StudentData.pdf");
            messagebodypart.setDataHandler(new DataHandler(source));
            messagebodypart.setFileName("Student Data");
            multipart.addBodyPart(messagebodypart);
            message.setContent(multipart);

            Transport.send(message);
            JOptionPane.showMessageDialog(null, "Message Sent");

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }


To be able to access mail, first we have to add the java mail library and create a new jframe to hold the delivery address, message body and Subject, which I have also added in the Repository for this tutorial.

Mail Interface:
mailinterface.png

After adding the mail API we then have to configure the host, in this tutorial, I have configured for Gmail, This can be seen in these section

props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

After which authentication is carried out using the email address and password of the account to be used for the mail transfer. Here; return new PasswordAuthentication("email", "password");

This section adds the body of the message to be sent to the specified email using MimeBodyPart and MultiPart.

  MimeBodyPart messagebodypart = new MimeBodyPart();
            messagebodypart.setText(jTextArea1.getText());
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messagebodypart);

And Finally the file is uploaded to the message as an attached document using;

 messagebodypart = new MimeBodyPart();
            DataSource source = new FileDataSource("StudentData.pdf");
            messagebodypart.setDataHandler(new DataHandler(source));
            messagebodypart.setFileName("Student Data");
            multipart.addBodyPart(messagebodypart);
            message.setContent(multipart);

The whole message is then added to the mail to be sent using message.setContent(); without this, the message will still be null or empty.

After the message has been added, it is required that the send button is pressed, this is where Transport.send(message); comes in, as it is in charge for sending the whole message. After which I have used a Jframe to tell if the message has been sent or not.
The message would not sent for now because Gmail See's the program as insecure so it would not allow Login, this issue can be addressed by contacting the mail provider. But for now to show that we have successfully connected to Gmail then your program should show an error as in the error screenshot and You should also get an email showing that you tried accessing your mail from a machine that isn't trusted.

Error

Mail


Curriculum


Thanks for following, Kindly drop your question in the comment section.

The full code and libraries can be accessed from the GitHub Repository

Sort:  

Hey official-hord! Thanks for the contribution. Interesting system you made there. Looking forward for part #3!

Your contribution has been evaluated according to Utopian rules and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post,Click here


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thanks @deathwing will improve on the quality.

Hey @official-hord
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Even if i dont understand this, its a good work

Lol you’re a microbiologist just stick to your organisms and leave coding for us 😁