Java

From Sinfronteras
Revision as of 20:27, 11 October 2017 by Adelo Vieira (talk | contribs) (Threads)
Jump to: navigation, search

Dining philosophers problem: https://en.wikipedia.org/wiki/Dining_philosophers_problem

Atomicity (database systems): https://en.wikipedia.org/wiki/Atomicity_(database_systems)

Instalación de Java

https://www.digitalocean.com/community/tutorials/how-to-install-java-with-apt-get-on-ubuntu-16-04

Puede ser necesario la instalación de Oracle JDK. Para GUI Programming, por ejemplo, se necesitan librerías que se encuentran en Oracle JDK.

Eclipse

Instalación de Eclipse

Para estar seguro de que estamos instalando la última versión, es apropiado descargar el paquete desde la página oficial, y no instalar la versión que se encuentra en los repositorios de Ubuntu a través de apt-get (pues estar versiones generalmente están desactualizadas).

Página oficial de Eclipse: http://www.eclipse.org/downloads/

En la siguiente página se explica como instalar eclipse en Ubuntu 16.04: http://ubuntuhandbook.org/index.php/2016/01/how-to-install-the-latest-eclipse-in-ubuntu-16-04-15-10/

Para instalarlo hay que simplemente ejecutar el instalador y seguir las instrucciones (como si se tratara de una instalación en Windows).

Luego, para agregar el ejecutable a la lista de comandos, he agregado la siguiente línea en el .bashrc:

PATH=$PATH:/home/adelo/.archivos_programas-ubuntu/eclipse/eclipse:

Combinaciones de teclas

  • Para que coloque los import (luego de haber ingresado un comando que necesite una librería en particular): Ctrl Shif o
  • Run: Ctrl 11
  • Comentar: Ctrl 7
  • Rastrea la variable seleccionada: CTRL k

Connecting to a MySQL database using Java

La conección a la base de datos MySQL a través de Java la haremos mediante la clase Register.class. Esta clase utiliza la librería Connector/J, la cual no se encuentra por defecto en las librerías de Java y debemos por lo tanto agregarla a nuestro proyecto Java.

Entonces, para realizar la conección debemos:

  1. Crear la base de datos MySQL a la cual queremos conectarnos
  2. Create an Eclipse Java project
  3. Agregar la librería externa Connector/J a nuestro proyecto
  4. Crear la clase Register.class

Creación de la base de datos MySQL

Luego de haber instalado y configurado MySQL (Instalación de MySQL) debemos crear la base de datos a la cual queremos conectarnos con Java. Para más detalles ver Database#MySQL

En este caso vamos a crear la base de datos "graham" y la tabla "samplelogin".

CREATE DATABASE graham;

USE graham;

CREATE TABLE samplelogin
  (
  id	 	int(10)		NOT NULL AUTO_INCREMENT,
  username 	VARCHAR(15)	NOT NULL,
  password 	VARCHAR(15)	NOT NULL,
  CONSTRAINT pk_samplelogin PRIMARY KEY (id)
  );
INSERT INTO samplelogin VALUES('001','Adelo Vieira','a2930');
INSERT INTO samplelogin VALUES('002','Rachel Smith','r1039');

Creating an Eclipse Java Project to use Connector/J

Before we make a connection to the database we first must create a new Eclipse project.

Creación de un proyecto Java en Eclipse:

  • File > New > Java Project: enter Project name
    • Esto creará una carpeta con el nombre del proyecto y dentro de ésta la carpeta srs
    • ...

Agregar la librería externa Connector/J a nuestro proyecto

Connector/J

We will need one additional library to allow us to make a connection from Java to the MySQL database. Java does not come with this library by default so it is important that we include this ourselves.

Para descargar Connector/J: https://dev.mysql.com/downloads/connector/j/

You will then be brought to a page where you will be asked if you would like to signup or login. This step is not needed, at the end of the page you will see a link that says "No thanks, just start my download". Click this link to skip ahead and begin the download.

Inside this folder you will see lots of different files, but we only need one file from this folder. The file we are interested in is the mysql-connector-java.bin.jar file. This is a single jar file that contains all the compiled source code we need to connect to a database.

Making a reference to Connector/J

  • Now that we have a new project, we can begin the process of adding the new library into the eclipse project. Right click on the project name and click "Properties". This will open a window showing you all of the project specific settings for the application you are developing.
  • Inside the properties dialog that opens, click on the Java Build Path option.
  • Once you have opened the Java Build Path option, next click the Libraries tab. This will show you a list of additional libraries you have already referenced. But because this is a new project, you will not see any libraries yet!
  • On the right hand side of this window click "Add External Jar" and a dialog window will open. Use this window to locate the mysql-connector.bin.jar file that you extracted earlier.
  • After you have found the jar file, you will see a new entry will be made under the libraries tab. This is telling you that when you go to compile the software you are building, it will also look for the .jar file you have just pointed to.
  • Click Ok to finish this step.
  • When you have finished making a reference to the library you will see that inside of your project under the Referenced Libraries menu, there will be a reference to the JAR file that you just pointed to in the previous step. You are now ready to start adding some code into your project to connect to the database.

Creación de la clase Register.class

Luego de haber creado el proyecto Java:

  • src folder (clic d) > New > Class: enter name and click the checkbox beside "public static void main" to generate this for you.

En este caso vamos a crear la clase Register.java, la cual permite ingresar datos a una base de datos MySQL utilizando la librería Connector/J.

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;


public class Register extends JFrame implements ActionListener{
	
	// make the fields global so we can see them!!
	JTextField username = null;
	JTextField password = null;
	
	public Register(){		

		setSize(400,400);
		setVisible(true);
		this.setLayout(new GridLayout(3,1));

		JLabel un = new JLabel("Username:");
		this.add(un);
		username = new JTextField(20);
		this.add(username);
		
		JLabel pw = new JLabel("Password:");
		this.add(pw);
		password = new JTextField(20);
		this.add(password);
		
		JButton register = new JButton("Register");
		
		register.addActionListener(this);
		
		this.add(register);
		
		
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Register();
	}
	
	public void registerNewUser(){
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		}
		
		catch(Exception e ){}
		
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		
		try {
			// En esta linea debemos ajustar: 
			// El IP (127.0.0.1 si es localhost) y el Port (generalmente el 3306) en donde corre MySQL.
			// El nombre de la base de datos a la cual queremos conectarnos: graham en nuestro ej.
			// El usuario y la clave de MySQL.
			conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/graham?user=root&password=a1640774200");
	    	
			// Do something with the Connection
			stmt = conn.createStatement();
			
			// or alternatively, if you don't know ahead of time that
			// the query will be a SELECT...
			String un = username.getText();
			String pw = password.getText();
			
			// En esta linea debemos ajustar el nombre de la base de datos y la tabla
			// en donde queremos agragar datos. En nuestro ejemplo: graham, samplelogin.
			if (stmt.execute("INSERT INTO `graham`.`samplelogin` (`username`, `password`) VALUES ('"+un+"', '"+pw+"');")) {
			}
		}
		
		// loop over results
		catch (SQLException ex) {
			// handle any errors
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("VendorError: " + ex.getErrorCode());
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		registerNewUser();
	}
}

Threads

Threads are used to allow our program to do more than one thing at any one time.

We picture a process which has two tasks that aren’t necessarily dependent on each other. They can occur at the same time, each handled by a “thread”

Thread.jpg

So, a process (think program) can contain a number of different threads. As the program is running, the processor switches between each of the threads allowing each of them to have some CPU time to run.

For dual (or more) core machines, each thread can be executed on a separate core, so no switching is neceessary. The threads truly run concurrently.

In the previous picture you can also see that Thread number 2 has died off and thread 1 continued on. This is ok.

Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.

Threads exist within a process — every process has at least one. Threads share the process's resources, including memory and open files.

Every application has at least one thread — or several, if you count "system" threads that do things like memory management and signal handling. From the programmer’s point of view, you start with just one thread, called the main thread. This thread has the ability to create additional threads

The difficulty with threads

  • Threads can be difficult to work with because their behavior can be unpredictable.
  • The order in which they are running may change unless synchronized.

Methods available in the Thread class

// Changes the name of this thread to be equal to the argument name.
setName(String name) 

// Changes the priority of this thread. Valid values are 1 through 10.
setPriority(int newPriority)

// Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds
sleep(long millis)

// Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
start()

// Causes the current thread to block (pause) until the specified thread terminates.
Thread.join()

// Causes the current thread to block until the specified thread terminates or the specified number of milliseconds passes
Thread.join(long millis)

Creating Threads

When we want to create threads, two options are available to us:

  • Extend the thread class, or
  • We can implement the Runnable interface

Extend the thread class

We need to extend the thread class and add a run method:

public class MyThread extends Thread {

	public void run(){

                // This is the code that is executed when the thread is started
                // Este es s'olo un c'odigo ejemplo. Aqu'i podr'ia haber cualquier c'odigo
		for (int i=0 ; i < 100000 ; i++){
			System.out.println("Eating...." + this.getName() + ":---" + i);
			
		}
		
	}
	
}


Then, in our standard class, when we want to use our thread, we create an instance of the thread, then start it:

import javax.swing.JFrame;

public class MyProgram extends JFrame{
	
	public MyProgram(){

		setSize(500,500);
		setVisible(true);
		
		MyThread t = new MyThread();
		t.setName("t1");
		t.setPriority(10);
		t.start();
		
	}
	public static void main(String[] args) {
		new MyProgram();
	}

}

GUI Programming

GUI stands for Graphical User Interface.

Swing:

It's a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes (JFC) – an API (Application programming interface) for providing a graphical user interface (GUI) for Java programs. Swing is currently the main user interface package which is used for creating desktop applications.

AWT (Abstract Window toolkit):

It's the user-interface widget toolkit preceding Swing. The AWT is part of the Java Foundation Classes (JFC) — the standard API for providing a graphical user interface (GUI) for a Java program. Some elements of this are still used.

  • On the Oracle website you can find a wealth of examples covering everything you will ever need to do using a Swing interface.
  • You can find full tutorials and also API documentation for each component.
  • The Oracle website contains so many examples, it really is worth taking the time to have a look through the website to get a feel for what can be done.


Introduction to Swing components

The JFrame can be considered to be base to which every other component is added.

Therefore if we wanted to create a simple interface with a text field and a button we would first need to create a JFrame to hold everything and then we would add the JTextField and the JButton to the JFrame.

Some of the components are:

Events

How do we make things happen?

  • In graphical user interfaces things happen and change because of events.
  • During this example we will create a button click event which means a message will be sent internally to say that a specific button has been clicked.
  • For our simple example, we want some text to be printed out to the console once a button has been clicked.
  • In order for this to happen, we need create an event generator and register a listener for the button in question.

Listeners

How do we make things happen?

  • Listeners are used to allow our program to "listen" for certain events in our program, e.g. when a button has been clicked.
  • The job of the listener is to wait for an event to happen, and once it has happened, to cause an event to happen.
  • For our example, we said that when a button is clicked an event will be "triggered". We will need to register a listener to wait and listen for this event to happen and then it will do what we tell it to do!

Making a Jar File

When developing an application we often need a method to package our software to give it to the users of our software.

A typical extension to files that we have always seen when working in a Windows environment is the .exe file extension. These files are a single binary executable file that when double clicked will open the program for the user.

In the Java world however things are a little different. There is no native .exe file in Java and we must use the .jar file extension instead. A jar file works exactly the same as a .exe file and when double clicked will run the program.

Jar files come in two different varieties:

  • Simple archive folder
  • Runnable archive folder

A jar file is an acronym for the title Java Archive, which is a filetype similar to that of the .zip extension. If we want, we can open up a jar file using a program such as WinZip or WinRar and check the contents inside of the jar.

The second variant of this is the ​runnable archive folder​. This type of file is exactly the same as the archive folder, just with one additional file. This extra file is used to define what happens when the user double clicks on the icon. In our case, we will point to the main method in our class file that we want to run. This will qick start the program to run when it is double clicked.