Posts

Showing posts with the label java

How to send email in java - example

Image
This is a example code to send email in java. This example will use 3rd party library JavaMail   . The Code Example import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /**  *  * @author zulkamal  */ public class sendEmail {     public static void main(String[] args) {         final String username = "yourgmailaddress@gmail.com";         final String password = "your password gmail";         Properties props = new Properties();         props.put("mail.smtp.auth", "true");         props.put("mail.smtp.starttls.enable", "true");         props.put("mail.smtp.host", "smtp.gmail.com");         props.put("mail.smtp.port", "587");         Session session = Session.getInstance

How to create XML File In Java

This is a example of creating XML file in java application. The Main Class Code import java.io.File; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; public class CreateXml {     public static void main(String[] args) throws TransformerException {         ArrayList<String> arrayOne = new ArrayList<String>();         ArrayList<String> arrayTwo = new ArrayList<String>();         ArrayList<String> arrayThree = new ArrayList<String>();                 for(int i = 0; i

Java - Get Visitor/Client ip address : JSP : Servlet

The previous post show how to get Visitor or client ip address in C# / ASP.NET . This post will show how to get ip address of client / visitor from jsp / servlet application. In order to make this method work, you need to test this method on the server and you are accessing the server from your computer. Otherwise you will get your local ipaddress or ::1 value. The getClientIpAddr Method      public static String getClientIpAddr(HttpServletRequest request) {          String ip = request.getHeader("X-FORWARDED-FOR");          if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {              ip = request.getHeader("Proxy-Client-IP");          }          if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {              ip = request.getHeader("WL-Proxy-Client-IP");          }          if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {              ip = request.getHeader(&

Netbean : java.lang.OutOfMemoryError: Java heap space - Solutions

Image
In java application development, sometimes your application will throw an exception run: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space     at com.classpackage.MainConsole.main(MainConsole.java:24) Java Result: 1 This is because your program consuming a lot of memory. One of the solutions is to increase the Xms and Xmx argument on the project. Lets see the example : The Main Class import java.util.ArrayList; import java.util.List; public class MainConsole {     public static void main(String[] args){         List<PhoneContacts> phoneContacts = new ArrayList<PhoneContacts>();         // You can use diamond inference in JDK 7 like example below         //List<PhoneContacts> phoneContacts = new ArrayList<>();                 for(int index = 0;index< 10000000;index++ ){             PhoneContacts p = new PhoneContacts();             p.setFirstName("developersnote" + Integer.toString(index));             p.setLastName(&qu

How to upload csv file into MySQL Database Example

Comma-Seperated-Value(CSV) file is a common file that used by most developers to extract data from database. Today i want to show how to upload or insert CSV file into database MySQL directly without need to read line by line in the CSV file. Let say this is the example of CSV file CSV File Content,Example 1 NO;DATE;TIME;ACCNO;STATUS 1;20131211;100856;12345;ACTIVE 2;20131211;095625;25896;NOT ACTIVE CSV File Content, Example 2 "NO";"DATE";"TIME";"ACCNO";"STATUS" "1";"20131211";"100856";"12345";"ACTIVE" "2";"20131211";"095625";"25896";"NOT ACTIVE" The above csv file are two example of csv files content. Lets start learn how to upload this file into MySQL Database. MySQL have a powerful sql statement to read this file and insert into database as batch. This statement is the fastest way to insert into database. You can read more about LOAD

JDBC PrepareStatement Insert Data As A Batch - JAVA(MySQL)

In this tutorial i will show example to add data into database MySQL as a batch. The idea is to prepare the batch data to pump into database one time only. This approach is a best solution if you more than 1 records to insert into database. If you insert one by one data to database, the process will be slow, hence batch process will inprove application performance. Take a look on the example and try it by your self. =) The Batch Update Example public void insertAsBatch()     {         String strsql = "INSERT INTO sysusers(UserID,UserEmail,Password) VALUES(?,?,?)";         PreparedStatement prepStatement = null;         Connection dbConn = TestConnectionDb();         int batchSize = 100;//set the batch size to commit intodatabase(optional)         int IndexCounterBatch = 0;         try         {                        dbConn.setAutoCommit(false);             prepStatement = dbConn.prepareStatement(strsql);             for(int i=0; i < 200;i++)             {                 

JDBC Prepare Statement to select data from database MySQL

In this tutorial i will show how to read data from database MySQl using PrepareStatement. You can read in this tutorial to create connection to database MySQL Full Example :  public void readDatabase()     {         String strsql = "SELECT * FROM sysusers WHERE UserID=?";         PreparedStatement prepStatement = null;         Connection dbConn = TestConnectionDb();         String uid = "";         String uemail = "";         try         {                        prepStatement = dbConn.prepareStatement(strsql);             prepStatement.setString(1, "developersnote");             ResultSet rs = prepStatement.executeQuery();             while (rs.next()) {                 uid = rs.getString("UserID");                 uemail = rs.getString("UserEmail");             }             System.out.println(uid);             System.out.println(uemail);         }         catch (SQLException se) {             System.out.println(se.getMessage

JDBC create connection or test connection to MySQL database

Here is a example how to make connection to database MySQL using ( J ava D ata B ase C onnectivity)JDBC driver. In your project you must include MySQL JDBC Driver, otherwise you will get error "MySQL JDBC Driver not found" . This is the full Method to check or test connection to MySQL Database using JDBC driver. The TestConnectionDb Method public static boolean TestConnectionDb() {                 String DbConnectionString ="jdbc:mysql://localhost:3306/";         //or you can directly connecto to your database schema like this :         //String DbConnectionString ="jdbc:mysql://localhost:3306/<schema name>";                 String User = "root";         String Password = "P@ssw0rd";                 Connection connection = null;         try {                        Class.forName("com.mysql.jdbc.Driver");             connection = DriverManager.getConnection(DbConnectionString, User, Password);         } catch (ClassNotFou

Encrypt And Decrypt Example in JAVA

Security is the first concern when you develope application what have sensitive data such as account number, passport number , etc . Today i want to show example how to do simple encrypt and decrypt method in JAVA. In this tutorial i will use 3rd party library, you can download the library by the following link :  Common-Codecs-1.8 The import library : import org.apache.commons.codec.binary.Base64; import java.io.*; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import javax.swing.JOptionPane; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; The SharedVector   private static byte[] sharedvector = {     0x01, 0x02, 0x03, 0x05, 0x07, 0x0B, 0x0D, 0x11     }; The Encr

How to add dynamically rows number in jTable - Java

Most of the programming now a days required dynamically create controller such as button, textbox and also table. Today i want to show how to dynamically set rows number in jTable Swing Controls. Firstly is to set the DefaultTableModel and assign to jTable. Here is the example : The DefaultTableModel import javax.swing.table.DefaultTableModel;   : : String colNames[] = {"Name", "Edit", "View"};  DefaultTableModel dtm = new DefaultTableModel(null,colNames);  Do looping to add rows in jTable for(int i=0; i < listOfString .size();i++){             dtm.addRow(new String[3]); } Assign to jTable  jTable2.setModel(dtm); The full Code :  String colNames[] = {"Name", "Edit", "View"};   DefaultTableModel dtm = new DefaultTableModel(null,colNames);  List<String> listOfString = new ArrayList<>();         listOfString.add("1");         listOfString.add("2");         listOfString.add("3");      

How to add button in JTable - Java

Image
How to works with JTable in java and want to insert button in the JTable column. Let say you want to add button in JTable column like in this pic :    First step is to get the column of the button and set the CellRenderer for the column :  jTable2.getColumn("Edit").setCellRenderer(new ButtonRenderer());  jTable2.getColumn("Edit").setCellEditor(new ButtonEditor(new JCheckBox()));              jTable2.getColumn("View").setCellRenderer(new ButtonRenderer());  jTable2.getColumn("View").setCellEditor(new ButtonEditor(new JCheckBox())); The Class ButtonRenderer import java.awt.Component; import javax.swing.JButton; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.table.TableCellRenderer; /**  *  * @author hp1  */ public class ButtonRenderer extends JButton implements TableCellRenderer {     public ButtonRenderer() {         setOpaque(true);     }     @Override     public Component getTableCellRendererComponent(JTable table, O

How to create zip file to download in JSP- Servlet

Image
Hye, my previous post show that how to download zip file in ASP.NET ,. In this tutorial i will show the same thing, but in Jsp-Servlet. Note : In this tutorial i will use this library :- JSTL 1.1  The JSP File  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html>     <head>         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">         <title>Download File As ZIP File</title>     </head>     <body>        <h1>Download File As ZIP File</h1>         ${DownloadMessage}         <br/>         <form action="<c:url value="/downloadFileServletZip" />" method="post" >             Default Path is server to download is D:\JAVA\dist\Output\             <input type="submit" name="bDownload"

Date Time Conversion utility Java

In this post, I will like to share a sample code snippet for date-time manipulation in Java. Convert hour from integer to string Scenario: Converts hour from integer to String. If the hour is a single digit, the leading zero will be added. public static String getHourString(int localHourNumber) {         if ((localHourNumber > 23) || (localHourNumber < 0)) {             return "";         }         if ((localHourNumber >= 0) && (localHourNumber <= 9)) {             return "0" + localHourNumber;         }         return String.valueOf(localHourNumber);     } Convert minute from integer to string  Scenario: Converts minute from integer to String. If the minute is a single digit, the leading zero will be added. public static String getMinuteString(int localMinuteNumber) {         if ((localMinuteNumber > 59) || (localMinuteNumber < 0)) {             return "";         }         if ((localMinuteNumber >= 0) && (localMinute

How to check leap year using java and C#

Image
Hi there, it's quite complicated to check using the if-else statement the year is a leap year or not. Today I will show the example of how to check if the year is a leap year or not. Leap Year A Normal day for a year is 365 days Leap year have 366 days (29 days in February) How to know if the year is a leap year A leap year can be any year that can be divided by 4 without any balance. WHY leap year occur This is because according to research, The earth rotates about 365.242375 but in one year only have 365 days. So something has to be done to handle the remaining 0.242375 balance. that is why the leap year occurs only once in 4 years. The example is pretty easy to follow. The Java Application package leapyear; import java.util.Scanner; public class LeapYear {         public static void main(String[] args) {         String Cont = "Y";         Scanner input = new Scanner(System.in);         LeapYear lYear = new LeapYear();                 System.out.println("---------

Multiple button in one form JSP - Servlet

Image
Hi there, today I will show one simple tutorial to show which button is clicked in one form. The idea after I read this post on the forum how to find which button is clicked Note : In this tutorial i will use this library :- JSTL 1.1 Here is the example The JSP File <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html>     <head>         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">         <title>Multiple Buttom In Form</title>     </head>     <body>         <h1>Multiple Button In Form</h1>         ${message}         <br/>         <form action="<c:url value="/servletMultipleButton" />" method="POST">            <input type="submit" name="BModify" value="Modify" >&l