Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, June 9, 2017

Installation and Create Simple Spring Boot Project on Eclipse

Filled under:

Assalamualaykum wr. wb.
Konbanwa, minna san!
Kali ini saya ingin berbagi tutorial untuk membuat aplikasi dengan menggunakan Spring Boot yang di run pada IDE Eclipse. Sebenarnya tutorial ini terinspirasi penuh dari mata kuliah saya di Semester 2 di salah satu universitas negeri di Depok :D, Pemrograman Skala Perusahaan (Enterprise Programming) yang diajar langsung oleh Bapak Samuel Louvan. Kalau boleh cerita sedikit, saya sangat suka sekali dengan dosen satu ini, karena selain pintar (ya jelas lah ya), beliau sangat cakap, wawasannya luas, dan pernah bekerja di luar negri yang memproduksi tidak hanya software, tapi juga hardware. Selain itu cara memberikan tutorial juga sangat sistematis, sehingga siapapun juga pasti bias menguasai Spring Boot dengan baik setelahnya.

SEE THIS TUTORIAL IN ENGLISH


Three Tired Web Layers

Anda pasti mungkin belum atau sudah tahu konsep pemrograman web dengan memanfaatkan 3 layer ini:

http://martinfowler.com/bliki/PresentationDomainDataLayering.html

  1. Presentation Layer, adalah layer yang akan melakukan http request dan merender halaman HTML
  2. Domain Layer, adalah layer yang digunakan untuk meletakkan semua logika bisnis (business logic) yang memiliki validasi dan kalkulasi
  3. Data Layer, adalah layer yang digunakan untuk mengelola data di dalam database atau remote services

Presentation Layer

Presentation layer bertanggung jawab untuk menampilkan informasi kepada user dan menginterpretasikan perintah yang diberikan oleh user, dan selanjutnya diserahkan kepada domain dan data layer. Presentation layer biasanya ditunjukkan dengan menggunakan Graphical User Interface yang dapat dipahami oleh manusia sebagai user.
Adapun ciri-ciri spesifik dari presentation layer adalah:
  • Melakukan penanganan interaksi yang dilakukan antara user dan aplikasi
  • Dalam bentuk sederhana dapat berupa command-line atau text-based menu system
  • Dalam era saat ini, bentuknya berupa GUI atau HTML-based browser UI

Data Layer

Data layer bertanggung jawab dalam berkomunikasi dengan layer-layer lain sesuai dengan tugas-tugasnya terhadap aplikasi.
Adapun ciri-ciri spesifik dari data layer adalah:
  • berkomunikasi dengan database engine yang digunakan bersamaan dengan aplikasi
  • berkomunikasi dengan aplikasi lain
  • berkomunikasi dengan system Messaging
  • berkomunikasi dengan Transaction Manager

Domain Layer

Domain layer bertanggung jawab dalam pekerjaan yang dibutuhkan oleh aplikasi agar memenuhi kebutuhan atau requirement.
Adapun ciri-ciri spesifik dari Domain layer adalah:
  • Biasanya dikenal dengan sebutan business logic
  • melakukan kalkulasi terhadap input dan menyimpannya ke data
  • memberikan validasi terhadap data yang dilempar oleh presentation layer
  • Menggambarkan bagaimana sebuah data diformasikan dan dikirim ke data layer

Biasanya tujuan dibuatnya domain layer di tengah-tengah layer adalah untuk benar-benar menyembunyikan data dari presentation layer, sehingga dimungkinkan user pada presentation layer tidak dapat mengakses langsung data yang disimpan.

Bagaimana untuk memisahkan layer-layer tersebut?

Hal itu sangat bergantung pada kompleksitas aplikasi yang akan kita kembangkan. Semakin kompleks, 3 layer tersebut biasanya dibagi lagi menjadi kelas-kelas. Dan semakin tinggi kompleksitasnya, kelas-kelas tersebut juga akan dibedakan ke dalam beberapa package juga.

Pastikan bahwa anda melakukan pemisahan terhadap layer, setidaknya pada tingkat subroutine!

Rules

Domain layer dan data layer seharusnya tidak bergantung terhadap presentation layer.
Itu artinya, tidak boleh ada pemanggilan subroutine untuk kode domain layer dan data layer kedalam presentation layer.

Contoh penerapan dari dari Three tired ini adalah Spring Boot Framework. Dan sebentar lagi kita akan belajar untuk membuat project, supaya anda paham bagaimana Three tired dapat diaplikasikan.

OK! Untuk dapat membuat program Spring Boot dengan menggunakan Eclipse, berikut ini tools yang harus dipersiapkan:
  • Download JDK (Java Development Kit) di sini
  • Set path JAVA_HOME seperti ini
  • Install Eclipse yang sudah terinstall Maven dengan menggunakan Eclipse versi Neon di sini
  • Install Spring Tool Suite (STS) disini, atau dengan melalui Help -> Market Place dan install melalui page tersebut

Setelah semua tools siap, silakan buka Eclipse anda dan ikuti langkah-langkah berikut ini:

Membuat Project baru

  • Buka Eclipse

  • Install STS melalui Eclipse Market Place

  • Setelah semua yang berkaitan dengan STS finish, anda akan diminta untuk restart Eclipse, maka silakan untuk melakukan restart Eclipse
  • Untuk membuka project Spring Boot, silakan pilih menu File -> New -> Other...
  • Silakan memilih Spring Starter Project yang berada di dalam folder Spring

  • Biarkan saja secara default Eclipse akan mengisi properti yang dibutukan

  • Pilih Next, dan kemudian pilih Web dependency

  • Pilih Finish

Mengubah Port

  • Secara default, server yang digunakan Spring Boot memiliki port 8080. Jika anda ingin mengubahnya, anda bisa pergi src/main/resource untuk mengakses application.properties. Kemudian tambahkan kode berikut:
server.port = 9090
  • Pada src/main/java buatlah file baru dan beri nama HelloWorldController.java, lebih baik lagi jika anda telah terlebih dahulu memiliki package
  • Pada HelloWorldController.java, tambahkan kode sebagai berikut:
package com.example; 

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController public class HelloWorldController { 
   
@RequestMapping("/") 
   
public String index ()  { 
       
return "Hello World!"; 
   
} }


  • Jalankan project, Run As Java Application



Menggunakan Page Controller

  • Ubah pom.xml Tambahkan kode berikut ini:

<dependency>   
   
<groupId>org.springframework.boot</groupId>
   
<artifactId>spring-boot-starter-thymeleaf</artifactId> 

</dependency>



  • Membuat halaman HTML pada src/main/resources/templates/hello.html

<!DOCTYPE   html>   <html   xmlns:th="http://www.thymeleaf.org">                   
   
<head>                                 
       
<title>First    Page</title>                   
   
</head>                
   
<body>                                 
       
<h1>Hello,  world!</h1>                
   
</body> </html>









  • Membuat halaman controller untuk halaman HTML pada src/main/java/PageController.java


package com.example;   
   
import  org.springframework.stereotype.Controller;  import  org.springframework.web.bind.annotation.RequestMapping;
   
@Controller public  class   PageController  {  
   
@RequestMapping("/hello")                  
   
public  String  index(){                                   
       
return  "hello";                   
   
}   }



Posted By Novida10:37 AM

Sunday, November 27, 2016

Create Simple Calculator using JAVA GUI

Filled under:

Here I give you a simple program to create Calculator using Java GUI. Please use this website as a reference link if you want to copy and paste this program.
If any question, don't be hesitate to leave a comment or contact my email.



package week09;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;

/**@author Novida Wayan Sari (1606954930)
 * @version 20161127 07:35PM
 * This class is Calculator class which is used to count a simple mathematics operation
 * such as plus, minus, multiply and divide.
 * This application is created to complete weekly task of Dasar-Dasar Pemrograman lecturing subject.
 * This application uses JPanel as for the main component of GUI
 * */

public class Calculator extends JPanel implements ActionListener {
    private static final int WIDTH = 420; //constant of frame width
    private static final int HEIGHT = 252; //constant of frame height
    private JMenuBar menuBar; //Menu Bar (File, Help) <-- I do not have any idea to fill up the content
    private JMenu fileMenu, helpMenu; //Referring Menu Bar, the content of menu bar
   
    //mainPanel is a JPanel contains of main components except Menu Bar
    //bottomPanel is a JPanel container of angkaPanel and operatorPanel
    //angkaPanel is a JPanel container of all number button and "+" and "-" [Grid Layout]
    //operatolPanel is a JPanel container of all operators button except "+" and "-" [Grid Layout]
    private JPanel mainPanel, bottomPanel, angkaPanel, operatorPanel;
    //-------------------------------------------------------------------------------------------------
    private JButton[] btnAngka; //Array of number button {"0","1","2","3","4","5","6","7","8","9"}
    private JButton[] btnControl; //Arrays of control button {"Backspace","C"}
    private JButton[] btnOperator; //Array of operator button {"+","-","/","*","="}
    private JTextField input; //Text field of input
    private Color bckColor, mainColor, inputColor, textColor; //Colors used to make background, foreground color in this application
    private float numb1 = 0; //variable which is used to save temporary value inputed by user
    private String oldOperator = ""; //variable which is used to save temporary operator inputed by user
    private boolean status = false; //the status to show if the operation is end
   
    /*constructor
     * */
    public Calculator(){
        this.bckColor = new Color(205,92,92); //Background Color
        this.mainColor = new Color(128,0,0); //Button Color
        this.inputColor = new Color(255,182,193); //Textfield background color
        this.textColor = new Color(255,182,193); //Text of text field color
       
        /*Main Panel uses Flow Layout which contains of Menu Bar and Main Panel*/
        super.setLayout(new FlowLayout());
        super.setPreferredSize(new Dimension(this.WIDTH, this.HEIGHT));
        super.setBackground(bckColor);
        super.setForeground(Color.WHITE);
       
        /*----------------- Menu Bar ------------------------------------------------*/
        this.menuBar = new JMenuBar();
        this.menuBar.setPreferredSize(new Dimension(this.WIDTH-20, 30));
        this.menuBar.setLocation(10, 0);
        this.menuBar.setBackground(bckColor);
        this.menuBar.setForeground(Color.white);
        this.fileMenu = new JMenu("File");
        this.helpMenu = new JMenu("Help");
        this.menuBar.add(fileMenu);
        this.menuBar.add(helpMenu);
        /*----------------- End of Menu Bar -----------------------------------------*/
       
        /*----------------- Input -----------------------------------------------------------------------------*/
        this.input = new JTextField();
        this.input.setPreferredSize(new Dimension(this.WIDTH-20, 30));
        this.input.setBackground(inputColor);
        this.input.setForeground(bckColor);
        this.input.setHorizontalAlignment(JLabel.RIGHT);
        this.input.setBorder(new LineBorder(bckColor));
        this.input.setBorder(BorderFactory.createCompoundBorder(this.input.getBorder(), BorderFactory.createEmptyBorder(5, 5, 5, 5)));
        this.input.setFont(new Font(this.input.getFont().getName(),Font.BOLD,this.input.getFont().getSize()));
        this.input.setEditable(false);
        this.input.setText("0");
        /*---------------- End of Input-------------------------------------------------------------------------*/
       
        /*---------------- Number Button -----------------------------------------------------------*/
        this.btnAngka = new JButton[10];
        this.btnControl = new JButton[2];
        this.btnOperator = new JButton[6];
       
        int colNum = 4;
        for(int i=0;i<10;i++){
            this.btnAngka[i] = new JButton(""+i);
            this.btnAngka[i].setPreferredSize(new Dimension((this.WIDTH-20)/colNum,30));
            this.btnAngka[i].setBackground(mainColor);
            this.btnAngka[i].setForeground(textColor);
            this.btnAngka[i].setBorder(new LineBorder(bckColor));
            this.btnAngka[i].addActionListener(this);
        }
        /*--------------- End of Number Button ----------------------------------------------------*/
       
        /*--------------- Control Button ----------------------------------------------------------*/
        this.btnControl[0] = new JButton("Backspace");
        this.btnControl[1] = new JButton("C");
       
        for(int i=0;i<2;i++){
            this.btnControl[i].setPreferredSize(new Dimension((this.WIDTH-20)/colNum,30));
            this.btnControl[i].setBackground(mainColor);
            this.btnControl[i].setForeground(textColor);
            this.btnControl[i].setBorder(new LineBorder(bckColor));
            this.btnControl[i].addActionListener(this);
        }
        /*--------------- End of Control Button ---------------------------------------------------*/
       
        /*--------------- Operator Button ---------------------------------------------------------*/
        this.btnOperator[0] = new JButton("+");
        this.btnOperator[1] = new JButton("-");
        this.btnOperator[2] = new JButton("/");
        this.btnOperator[3] = new JButton("*");
        this.btnOperator[4] = new JButton(".");
        this.btnOperator[5] = new JButton("=");
       
        for(int i=0;i<6;i++){
            this.btnOperator[i].setPreferredSize(new Dimension((this.WIDTH-20)/colNum,30));
            this.btnOperator[i].setBackground(mainColor);
            this.btnOperator[i].setForeground(textColor);
            this.btnOperator[i].setBorder(new LineBorder(bckColor));
            this.btnOperator[i].addActionListener(this);
        }
        /*-------------- End of Operator Button --------------------------------------------------*/
       
        //------------ BACKSPACE BUTTON -----------------------------------------------------------
        this.btnControl[0].setPreferredSize(new Dimension((2*(this.WIDTH-20))/colNum,30));
        this.btnControl[0].setLocation(10,70);
        this.btnControl[0].setBackground(mainColor);
        this.btnControl[0].setForeground(textColor);
        this.btnControl[0].setBorder(new LineBorder(bckColor));
        //------------ END OF BACKSPACE -----------------------------------------------------------
       
        //------------ C BUTTON -----------------------------------------------------------
        this.btnControl[1].setPreferredSize(new Dimension((this.WIDTH-20)/colNum,30));
        this.btnControl[1].setBackground(mainColor);
        this.btnControl[1].setForeground(textColor);
        this.btnControl[1].setBorder(new LineBorder(bckColor));
        //------------ END OF C BUTTON -----------------------------------------------------------
       
        /*------------ Bottom Panel -------------------------------------------------------------*/
        this.bottomPanel = new JPanel();
        this.bottomPanel.setPreferredSize(new Dimension(this.WIDTH-20,120));
        this.bottomPanel.setLayout(new BorderLayout());
        /*------------ of Bottom Panel ----------------------------------------------------------*/
       
        /*------------ Panel of number button -----------------------------------------------------*/
        this.angkaPanel = new JPanel();
        this.angkaPanel.setPreferredSize(new Dimension((3*(this.WIDTH-20))/4,120));
        this.angkaPanel.setLayout(new GridLayout(4,3));
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                this.angkaPanel.add(this.btnAngka[(2-i)*3+1+j]);
            }
        }
   
        this.angkaPanel.add(this.btnOperator[0]);
        this.angkaPanel.add(this.btnAngka[0]);
        this.angkaPanel.add(this.btnOperator[1]);
        /*------------ End of Panel of number button ---------------------------------------------------*/
       
        this.bottomPanel.add(this.angkaPanel, BorderLayout.WEST);
       
        this.operatorPanel = new JPanel();
        this.operatorPanel.setPreferredSize(new Dimension((this.WIDTH-20)/4,120));
        this.operatorPanel.setLayout(new GridLayout(4,1));
       
        for(int i=0;i<4;i++){
            this.operatorPanel.add(this.btnOperator[i+2]);
        }
       
        this.bottomPanel.add(this.operatorPanel, BorderLayout.EAST);
       
        /*------------ insert all components to main Panel and add it to this class ---------------------*/
        this.mainPanel = new JPanel();
        this.mainPanel.setLayout(new BorderLayout());
        this.mainPanel.setBackground(bckColor);
            /*---------------------- Main Panel uses Border Layout ------------*/
        this.mainPanel.add(this.input, BorderLayout.NORTH);
        this.mainPanel.add(this.btnControl[0], BorderLayout.WEST);
        this.mainPanel.add(this.btnControl[1], BorderLayout.EAST);
        this.mainPanel.add(this.bottomPanel, BorderLayout.SOUTH);
            /*-----------------------------------------------------------------*/
        super.add(menuBar);
        super.add(mainPanel);
        /*-----------------------------------------------------------------------------------------------*/
    }
   
   
    @Override
    public void actionPerformed(ActionEvent evt) {
        // TODO Auto-generated method stub
        if(evt.getSource() instanceof JButton){
            String btnText = ((JButton)evt.getSource()).getText();
            String pattern = "[0-9]|[.]";
            if(btnText == "Backspace"){
                /*If the button pressed is backspace, then it will erase the last digit of shown inputed number*/
                if(!this.input.getText().equals("")){
                    /*if there is digit in the last, then system should check if it is not zero (integer or decimal)*/
                    if(this.input.getText().equals("0.")){
                        this.input.setText("0");
                    }else{
                        /*if there is digit in the last, then system should check if previous digit is exist*/
                        if(this.input.getText().substring(0, this.input.getText().length()-1).equals("")){
                            this.input.setText("0");
                        }else{
                            this.input.setText(this.input.getText().substring(0, this.input.getText().length()-1));
                        }
                    }
                }
                this.status = false; //it shows that there is no temporary operation, backspace doesn't make any calculation process
            }else if(btnText == "C"){
                /*C will clear all shown number and change it into zero ------------------
                 * it also will clean up the history of number and operator inputed by the user
                 * */
                this.input.setText("0");
                this.numb1 = 0;
                this.oldOperator = "";
                this.status = false;
            }else if(btnText.matches(pattern)){
                if(btnText.equals(".") && this.input.getText().equals("0")){
                    /*If only zero shown in screen, and the user presses point to input decimal number -------------*/
                    this.input.setText("0.");
                }else{
                    if(this.status == false){
                        if(this.input.getText().equals("0")){
                            /*If only zero show in screen, and the user presses any number, the zero in the first character shouldn't be shown*/
                            this.input.setText(btnText);
                        }else{
                            /*If the first number isn't zero, then the system only append pressed number*/
                            this.input.setText(this.input.getText()+btnText);
                        }
                    }else{
                        this.input.setText(btnText);
                    }
                }
               
                this.status = false;
            }else{
                try{
                    /*Every single time the user presses operator button, then the system should do calculation based on
                     *history of number and operator user pressed
                     **/
                    float result = this.count();
                    if(result == Math.floor(result)){
                        /*If the result of calculation can be figured out into integer form, then the system prioritize it first */
                        this.input.setText(""+(int)result);
                    }else{
                        this.input.setText(""+result);
                    }
                    this.status = true;
                }catch(NumberFormatException e){
                    JOptionPane.showMessageDialog(null, "There was an error occured. Please restart the application and then try again!");
                }
               
                if(btnText.equals("=")){
                    /*= button will shows the result and erase the history of number and operator inputed by the user such C button does */
                    this.oldOperator = "";
                    this.numb1 = 0;
                }else{
                    /*The system saves the operator as temporary operator to be executed in next operator pressed*/
                    this.oldOperator = btnText;
                }
            }
        }
    }
   
    public float count(){
        switch(this.oldOperator){
            case "+":this.numb1=this.numb1+Float.valueOf((this.input.getText()));break;
            case "-":this.numb1=this.numb1-Float.valueOf((this.input.getText()));break;
            case "/":this.numb1=this.numb1/Float.valueOf((this.input.getText()));break;
            case "*":this.numb1=this.numb1*Float.valueOf((this.input.getText()));break;
            case "":this.numb1=Float.valueOf((this.input.getText()));break;
        }
        return this.numb1;
    }
   
    public static void main(String[] arg){
        JFrame frame = new JFrame("Calculator");
        frame.setSize(Calculator.WIDTH, Calculator.HEIGHT);
        frame.setLocation(150, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
        Calculator calc = new Calculator();
        frame.add(calc);
        frame.setVisible(true);
    }

}

Posted By Novida10:33 PM

Thursday, September 18, 2014

Build Web Application Using Spring Java MVC - Hello World

Filled under:

Hello guys! How are you?
Okay, I am a beginner for Spring Web Application Development. I will share my knowledge and experience and also to practice my English Written skill.

What will you need to develop web application using spring? yeah, there are 4 elements that you must downloaded. those are:

  • Eclipse IDE for EE programming, eg: KEPLER, JUNO, LUNA, etc.
  • Apache Tomcat jar (in this practice I use version 6.0.3)
  • Spring Framework jar (in this practice I use version 3.1.1.RELEASE)
  • Apache common logging jar (in this practice I use version 1.2)
The first time,  you must understand about Model View and Controller programming concept, because Spring Framework is a Java Web Application framework which uses Model View and Controller programming Concept. Model includes service classes, Domain objects and all data access objects. View includes all data with *.jsp extension, and controller only need to be written in java class.

bellow are the simple example for developing MVC Web programming using Spring.
  • please set up the server Runtime Environment in your Eclipse IDE using apache tomcat like bellow:
  • create the new Dynamic Web Project using Apache Tomcat server
  • create simple greeting sentence in index.jsp file
  • set a welcome - file to be index.jsp file in the web.xml
  • create servlet name inweb.xml

Posted By Unknown12:07 PM

Sunday, April 13, 2014

Java Network Programming - Identifying a machine

Filled under:

Assalamualaikum warahmatullah.

Sudah pasti, untuk dapat berkomunikasi satu sama lain sebuah mesin memiliki cara yang unik untuk mengidentifikasi dirinya di dalam sebuah jaringan. Program di bawah ini menggunakan InetAddress.getByName() untuk menemukan alamat IP yang digunakan komputer kita.Untuk menggunakannya, kita harus tahu terlebih dahulu nama dari komputer kita. Pada Windows, kita pergi ke "Control Panel","Network" kemudian pilih tab "Identification". "Computer name" adalah nama komputer yang akan diletakkan pada command line.

package network;
//Find out our network address when you're connected to the internet

import java.net.*;
public class WhoAmI {
public static void main(String[] args) throws Exception{
if(args.length!=1){
System.err.println("Usage : WhoAmI Machine Name");
System.exit(1);
}
InetAddress a=InetAddress.getByName(args[0]);
System.out.println(a);
}
}

Posted By Unknown9:26 PM