Day: November 1, 2021

aula5TProxy

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

class ClientHanlder extends Thread {
    Socket sockIn;
    Socket sockOut;

    public ClientHanlder(Socket s1, Socket s2) {
        sockIn = s1;
        sockOut = s2;
    }

    @Override
    public void run() {
        int c;

        System.out.println(Thread.currentThread().getName() + " iniciada.");
        try {
            InputStream in = sockIn.getInputStream();
            OutputStream out = sockOut.getOutputStream();

            while ((c = in.read()) != -1) {
                out.write(c);

            }
        } catch (IOException e) {
            System.out.println(Thread.currentThread().getName() + " : " + e);
        } finally {
            try {
                sockIn.close();
            } catch (Exception e) {
            }
            try {
                sockOut.close();
            } catch (Exception e) {
            }
        }

    }
}

class Proxy {
    static final int LISTENING_PORT = 5001;
    static final String POP_ADR = "pop.isec.pt";
    static final int POP_PORT = 110;

    private int listeningPort;
    private int destinationPort;
    private String destinationAddr;
    ServerSocket listeningSocket;

    public Proxy() {
        listeningPort = -1;
        destinationAddr = null;
        destinationPort = -1;
    }

    public void processArguments(String args[]) {

        if (args.length == 3) {
            try {
                listeningPort = Integer.parseInt(args[0]);
                destinationAddr = args[1];
                destinationPort = Integer.parseInt(args[2]);
            } catch (NumberFormatException e) {
                listeningPort = -1;
            }
        }

        if (listeningPort == -1) {
            listeningPort = LISTENING_PORT;
            destinationAddr = POP_ADR;
            destinationPort = POP_PORT;
        }

    }

    public void processaPedidos(String args[]) throws IOException {
        Socket cliScket, socketToPopServer;
        Thread t1, t2;

        processArguments(args);
        System.out.println("porto de escuta: " + listeningPort + " ; destino " + destinationAddr + " ; Porto de destino: " + destinationPort);

        while (true) {
            cliScket = listeningSocket.accept();
            System.out.println("Novo cliente: " + cliScket.getInetAddress().getHostName() + ":" + cliScket.getPort());

            try {
                socketToPopServer = new Socket(destinationAddr, destinationPort);

            } catch (IOException e) {
                System.out.println(e);
                cliScket.close();
                continue;
            }

            t1 = new ClientHanlder(socketToPopServer, cliScket);
            t2 = new ClientHanlder(cliScket, socketToPopServer);

            t1.setName("Thread " + socketToPopServer.getInetAddress().getHostAddress() + ":" + socketToPopServer.getPort() + "->" + cliScket.getInetAddress().getHostAddress() + ":" + cliScket.getPort() + "]");
            t2.setName("Thread " + socketToPopServer.getInetAddress().getHostAddress() + ":" + socketToPopServer.getPort() + "->" + cliScket.getInetAddress().getHostAddress() + ":" + cliScket.getPort() + "]");

            t1.start();
            t2.start();
        }

    }
}


public class aula05TProxy {
    public static void main(String[] args) throws IOException {
        Proxy p;
        p = new Proxy();
        p.processaPedidos(args);
    }
}
Tags : ,

aula5TJDBC

import java.sql.*;

class aula5TJDBC {

    static final String JDBC_DRIVEr = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/pd";

    static final String USER = "root";
    static final String PASS = "";
    static final String QUERY = "SELECT * FROM testepd";

    public static void main(String[] args) {
        // Open a connection
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            System.out.println("Ligar à base de dados..");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            System.out.println("Concretizar uma operação..");
            stmt = conn.createStatement();
            String sql = "SELECT * FROM testepd;";
            rs = stmt.executeQuery(sql);

            while (rs.next()) {
                int id = rs.getInt("id");
                String nome = rs.getString("nome");
                String localidade = rs.getString("localidade");
                int idade = rs.getInt("idade");

                System.out.print("ID: " + id);
                System.out.print(", nome: " + nome);
                System.out.print(", localidade: " + localidade);
                System.out.println(", idade: " + idade);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try{
                if(stmt != null){
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try{
                if(conn != null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try{
                if(rs != null){
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Terminou");
    }
}

//versão google
/*
import java.sql.*;

public class FirstExample {
    static final String DB_URL = "jdbc:mysql://localhost/pd";
    static final String USER = "root";
    static final String PASS = "";
    static final String QUERY = "SELECT * FROM testepd";

    public static void main(String[] args) {
        // Open a connection
        try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(QUERY);) {
            // Extract data from result set
            while (rs.next()) {
                // Retrieve by column name
                System.out.print("ID: " + rs.getInt("id"));
                System.out.print(", nome: " + rs.getString("nome"));
                System.out.print(", localidade: " + rs.getString("localidade"));
                System.out.println(", idade: " + rs.getInt("idade"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
*/
Tags : ,

aula11tRESTApi

Aula11tRestApiApplication.java

package pd.aula11tRESTApi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Aula11tRestApiApplication {

	public static void main(String[] args) {
		SpringApplication.run(Aula11tRestApiApplication.class, args);
	}

}

Country.java

package pd.aula11tRESTApi;

public class Country {
    private String nome;
    private int population;

    public Country(String nome, int population) {
        this.nome = nome;
        this.population = population;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }
}

HelloWorld.java

package pd.aula11tRESTApi;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("hello-world")
public class HelloWorld {
//http://localhost:8080/hello-world?name=pedro
//curl -i http://localhost:8080/hello-world?name=pedro
    /*
    //v1
    @GetMapping("")
    public String get1(@RequestParam(value="name", required = false)String req_name){
        if(req_name != null){
            return "Hello " + req_name + "!";
        }else{
            return "Hello world";
        }
    }

    @GetMapping("{name}")
    public String get2(@PathVariable("name") String provided_name){
        return "Hello " + provided_name + "!";
    }
*/
    /*
    //v2
    @GetMapping(value = {"","{name}"})
    public String get1(@RequestParam(value="name", required = false)String req_name, @PathVariable(value = "name", required = false) String path_name){
        if(path_name != null){
            return  "Hello " + path_name + "!";
        }else if(req_name != null){
            return "Hello " + req_name + "!";
        }else{
            return "Hello world";
        }
    }
    */
}

HelloWorldDB.java

package pd.aula11tRESTApi;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;


public class HelloWorldDB {

    @GetMapping("world/countries")
    public List<String> getCountries(@RequestParam(value="name", required=false) String name,
                                     @RequestParam(value="min-pop", required=false) String min_population) throws SQLException {

        List<String> countries = new ArrayList<>();

        try( Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/world", "root", "");
             Statement st = conn.createStatement()){

            String query = "select name, population from country";

            if(name!=null){
                query += " where name like '%" + name +"%'";

                if (min_population!=null){
                    query += " and population>=" + min_population;
                }
            }else if(min_population!=null){
                query += " where population>=" + min_population;
            }

            ResultSet rs = st.executeQuery(query);

            while(rs.next()){
                countries.add(rs.getString("name"));
            }

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

        return countries;

    }

    @GetMapping("world/countries/{name}")
    public ResponseEntity getCountries(@PathVariable("name") String name){

        Country result;

        try( Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/world", "root", "");
             Statement st = conn.createStatement()){

            String query = "select name, population from country where name='"+name+"'";

            ResultSet rs = st.executeQuery(query);

            if(rs.next()){
                result = new Country(rs.getString("name"), rs.getInt("population"));
            }else{
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Country " + name + " not found!");
            }

        }catch(SQLException ex){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.toString());
        }

        return ResponseEntity.status(HttpStatus.OK).body(result);

    }
}
Tags : ,

aula10Thttp

fetchURL.java

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

 class FetchURL
{
    /*
    public static void main(String args[]) throws Exception
    {
        int argc = args.length;

        if (argc != 1){
            System.out.println ("Syntax: java FetchURL url");
            return;
        }
        try {
            URL myURL = new URL( args[0] );
            InputStream in = myURL.openStream();
            BufferedInputStream bufIn = new BufferedInputStream(in);
            while((data = bufIn.read())!= -1){ //!EOF
                System.out.print ((char)data);
            }
            System.out.println ("\nHit <Enter> to continue");
            System.in.read();
        }catch (MalformedURLException e){
            System.err.println ("Unable to parse URL!");
            return;
        }catch (IOException ioe){
            System.err.println ("I/O Error : " + ioe);
            return;
        }
    }

     */
}

SingleQuoteConsumer.java

import java.io.*;
import java.net.*;
import com.google.gson.*;
import javax.json.*;
public class SingleQuoteConsumer {
    public static void main(String args[]) throws MalformedURLException,
            IOException {
        String quoteId = args.length >0 ? args[0] : "random";
        getQuoteFromQuoteService(quoteId);
    }
    public static void getQuoteFromQuoteService(String quoteId) throws
            MalformedURLException, IOException {
        String uri = "http://gturnquist-quoters.cfapps.io/api/"+quoteId;
        URL url = new URL(uri);
        HttpURLConnection connection;
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/xml, */*");
        InputStream in = connection.getInputStream();
        JsonReader jsonReader = Json.createReader(in);
        JsonObject object = jsonReader.readObject();
        jsonReader.close(); connection.disconnect();
        Gson gson = new GsonBuilder().create();
        Quote q = gson.fromJson(object.toString(), Quote.class);
        System.out.println("Tipo: " + q.getType());
        System.out.println("Id: " + q.getValue().getId());
        System.out.println("Citacao: " + q.getValue().getQuote());
    }
}

url.java

import java.net.MalformedURLException;
import java.net.URL;

public class url {
    public static void main(String args[])
    {
        int argc = args.length;
        if (argc != 1){
            System.out.println ("Syntax : java URLParser url ");
            return;
        }
        try {
            URL myURL = new URL( args[0] );
            System.out.println ("Protocol : " + myURL.getProtocol() );
            System.out.println ("Hostname : " + myURL.getHost() );
            System.out.println ("Port     : " + myURL.getPort() );
            System.out.println ("Filename : " + myURL.getFile() );
        }catch (MalformedURLException e){
            System.err.println ("Unable to parse URL!");
            return;
        }
    }
}

URLConnection.java

import java.net.*;
import java.io.*;

public class URLConnection {

    public static void main(String args[]) throws Exception {
        int argc = args.length;
        if (argc != 1) {
            System.out.println("Syntax: java FetchURLConnection url");
            return;
        }
        try {
            java.net.URL myURL = new URL(args[0]);
            URLConnection connection = myURL.openConnection();
            connection.connect();

            // DISPLAY THE MIME CONTENT-TYPE (E.G. TEXT/HTML)
            String MIME = ((java.net.URLConnection) connection).getContentType();
            System.out.println("Content-type: " + MIME);

            // DISPLAY, IF AVAILABLE, THE CONTENT LENGTH
            int contentLength = connection.getContentLength();
            if (contentLength != -1) {
                System.out.println("Content-length: " + contentLength);
            }

            // Pause for user
            System.out.println("Hit enter to continue");
            System.in.read();

            // READ THE CONTENTS OF THE RESOURCE FROM THE CONNECTION
            InputStream in = connection.getInputStream();

            // BUFFER THE STREAM, FOR BETTER PERFORMANCE
            BufferedInputStream bufIn = new BufferedInputStream(in);
            while ((data = bufIn.read()) > 0) {
                System.out.print((char) data);
            }
        } catch (MalformedURLException e) {
            System.err.println("Unable to parse URL!");
            return;
        } catch (IOException e) {
            System.err.println("I/O Error : " + ioe);
            return;
        }
    }
}
Tags : ,

aula08tRMICallbacks

TemperatureListener.java

import java.rmi.Remote;
import java.rmi.RemoteException;

//A interface remota associada aos listeners define apenas o método temperatureChanged()
interface TemperatureListener extends Remote {
    public void temperatureChanged(double temperature) throws RemoteException;
}

TemperatureMonitorCliente.java

import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

//Monitor de mudança de temperatura (listener)
public class TemperatureMonitorCliente extends UnicastRemoteObject implements TemperatureListener {

    public TemperatureMonitorCliente() throws RemoteException {
        // NO CODE REQUIRED
        //nao precisamos do construtor mas todos os serviços RMi precisam por causa do throws RemoteException
    }

    public static void main(String args[]) {
        System.out.println("Looking for temperature sensor");

        // ONLY REQUIRED FOR DYNAMIC CLASS LOADING
        // SYSTEM.SETSECURITYMANAGER ( NEW RMISECURITYMANAGER() );
        try {
            String registry = "localhost";
            if (args.length >= 1) {
                registry = args[0];
            }
            // LOOKUP THE SERVICE IN THE REGISTRY, AND OBTAIN A REMOTE SERVICE
            String registration = "rmi://" + registry + "/TemperatureSensor";
            Remote remoteService = Naming.lookup(registration);
            TemperatureSensor sensor = (TemperatureSensor) remoteService;

            // GET AND DISPLAY CURRENT TEMPERATURE
            double reading = sensor.getTemperature();
            System.out.println("Original temp : " + reading);

            // CREATE A NEW MONITOR AND REGISTER IT AS A LISTENER WITH REMOTE SENSOR
            TemperatureMonitorCliente monitor = new TemperatureMonitorCliente(); //criar o serviço
            sensor.addTemperatureListener(monitor); //registo o sensor
        } catch (NotBoundException e) {
            System.out.println("No sensors available");
        } catch (RemoteException e) {
            System.out.println("RMI Error - " + e);
        } catch (Exception e) {
            System.out.println("Error - " + e);
        }
    } //MAIN

    public void temperatureChanged(double temperature) throws java.rmi.RemoteException {
        System.out.println("Temperature change event : " + temperature);
    }
}

TemperatureSensor.java

//Interface associada ao serviço de medição de temperatura (i.e., fonte do evento mudança de temperatura)
interface TemperatureSensor extends java.rmi.Remote {
    public double getTemperature() throws java.rmi.RemoteException;

    public void addTemperatureListener(TemperatureListener listener) throws java.rmi.RemoteException;

    public void removeTemperatureListener(TemperatureListener listener) throws java.rmi.RemoteException;
}

TemperatureSensorServer.java

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

//Serviço + Servidor sensor de temperatura
public class TemperatureSensorServer extends UnicastRemoteObject implements TemperatureSensor, Runnable {
    private volatile double temp; //THE VALUE OF THIS VARIABLE WILL NEVER BE

    //CACHED THREAD-LOCALLY
    private List<TemperatureListener> list;

    public TemperatureSensorServer() throws java.rmi.RemoteException {
        temp = 20.0;
        list = new ArrayList<TemperatureListener>();
    }

    //parte de comunicação gerada autmaticamente
    public synchronized double getTemperature() throws java.rmi.RemoteException {
        return temp;
    }

    public synchronized void addTemperatureListener(TemperatureListener listener) throws RemoteException {
        System.out.println("adding listener -" + listener);
        list.add(listener);
    }

    public synchronized void removeTemperatureListener(TemperatureListener listener) throws java.rmi.RemoteException {
        System.out.println("removing listener -" + listener);
        list.remove(listener);
    }

    public synchronized void changeTemp(Random r) {
        int num = r.nextInt();
        if (num < 0) temp += 0.5;
        else temp -= 0.5;

        // NOTIFY REGISTERED LISTENERS
        notifyListeners();
    }

    //run é acessorio
    public void run() {
        Random r = new Random();
        while (true) {
            try {
                // SLEEP FOR A RANDOM AMOUNT OF TIME
                int duration = r.nextInt() % 10000 + 2000;
                if (duration < 0)
                    duration = -1 * duration;
                Thread.sleep(duration);
            } catch (InterruptedException e) {

            }
            // COMPUTE NEW VALUE FOR TEMP
            changeTemp(r);
        }
    } //WHILE

    private synchronized void notifyListeners() {
        for (int i = 0; i < list.size(); i++) {
            TemperatureListener listener = list.get(i);
            try {
                listener.temperatureChanged(temp);
                //temperatureChanged vai ser executado do lado do cliente
            } catch (RemoteException e) { //UNABLE TO CONTACT LISTENER
                System.out.println("removing listener -" + listener);
                list.remove(listener);
                i--;
            }
        }
    }

    public static void main(String args[]) {
        System.out.println("Loading temperature service");
        // ONLY REQUIRED FOR DYNAMIC CLASS LOADING
        //System.setSecurityManager ( new RMISecurityManager() );
        try {
            // LOAD THE SERVICE
            TemperatureSensorServer sensor = new TemperatureSensorServer(); //criar o serviço

            // REGISTER WITH SERVICE SO THAT CLIENTS CAN FIND US
            String registry = "localhost";
            if (args.length >= 1) {
                registry = args[0];
            }

            String registration = "rmi://" + registry + "/TemperatureSensor";
            Naming.rebind(registration, sensor); //referencia remota ficar registada no registry
            //para os clientes depois obterem essa referencia remota

            // CREATE A THREAD TO TRIGGER REGULAR TEMPERATURE CHANGES
            //serve apenas para simular as diferentes temperaturas
            Thread thread = new Thread(sensor);
            thread.start();

        } catch (RemoteException re) {
            System.err.println("Remote Error - " + re);
        } catch (Exception e) {
            System.err.println("Error - " + e);
        }
    } //MAIN
}
Tags : ,

aula07tRMi

clienteRMi.java

import java.rmi.*;
public class clienteRMi
{
    public static void main(String args[])
    {
        System.out.println ("Looking for light bulb service");
        try {
            String registry = "localhost";
            if (args.length >=1){ registry = args[0]; }
            String registration = "rmi://" + registry + "/registryRMInterfaceRemotaImplements";

            Remote remoteService = Naming.lookup ( registration ); //cria a ligação TCP

            // CAST TO A RMILIGHTBULB INTERFACE
            registryRMInterfaceRemota bulbService = (registryRMInterfaceRemota) remoteService; //fazemos o cast para aceder aos métodos da interface

            bulbService.on();
            System.out.println ("Bulb state : " + bulbService.isOn() );
            bulbService.off();
            System.out.println ("Bulb state : " + bulbService.isOn() );
        }catch (NotBoundException e){
            System.out.println ("No light bulb service available!");
        }catch (RemoteException e){
            System.out.println ("RMI Error - " + e);
        }catch (Exception e){
            System.out.println ("Error - " + e);
        }
    }
}

registryRMInterfaceRemota.java

//Interfaces Remotas
public interface registryRMInterfaceRemota extends java.rmi.Remote
{
    public void on() throws java.rmi.RemoteException;
    public void off() throws java.rmi.RemoteException;
    public boolean isOn() throws java.rmi.RemoteException;
}

registryRMInterfaceRemoteImplements.java


//implements
//public class registryRMInterfaceRemoteImplements extends java.rmi.server.UnicastRemoteObject implements registryRMInterfaceRemota
public class registryRMInterfaceRemoteImplements extends java.rmi.server.UnicastRemoteObject implements registryRMInterfaceRemota
{
    private boolean lightOn;
    // A CONSTRUCTOR MUST BE PROVIDED FOR THE REMOTE OBJECT
    public registryRMInterfaceRemoteImplements() throws java.rmi.RemoteException
    {
        setBulb(false);
    }
    // REMOTELY ACCESSIBLE "ON" METHOD - TURNS ON THE LIGHT
    public void on() throws java.rmi.RemoteException
    {
        setBulb(true);
    }
    public void off() throws java.rmi.RemoteException
    {
        setBulb (false);
    }
    public boolean isOn() throws java.rmi.RemoteException
    {
        return getBulb();
    }
    public void setBulb (boolean value)
    {
        lightOn = value;
    }
    public boolean getBulb ()
    {
        return lightOn;
    }
}

RMIServer.java

import java.rmi.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.*;

public class RMIServer
{
    public static void main(String args[])
    {
        System.out.println ("Loading RMI service");


        System.out.println ("Loading RMI service");
        try {
            //v1
            // LOAD THE SERVICE
            registryRMInterfaceRemoteImplements bulbService = new registryRMInterfaceRemoteImplements();

            // EXAMINE THE SERVICE TO SEE WHERE IT IS STORED
            RemoteRef location = bulbService.getRef();
            System.out.println (location.remoteToString());
//v2
            Registry r1;
            try {
                r1 = LocateRegistry.createRegistry(Registry.REGISTRY_PORT); //HOST LOCAL
            }catch (RemoteException e) {
                System.out.println("jรก existe" + e);
                e.printStackTrace();
                r1 = LocateRegistry.getRegistry();
            }
            r1.rebind("registryRMInterfaceRemotaImplements", bulbService);

            Registry r2 = LocateRegistry.getRegistry(Registry.REGISTRY_PORT);
            r2.rebind("registryRMInterfaceRemotaImplements", new registryRMInterfaceRemoteImplements());
/*
//v1
            // CHECK TO SEE IF A REGISTRY WAS SPECIFIED
            String registry = "localhost";
            if (args.length >= 1){ registry = args[0]; }

            // REGISTRATION FORMAT: //REGISTRY_HOSTNAME[:PORT]/SERVICE_NAME
            String registration = "rmi://" + registry + "/RMILightBulb";

            // REGISTER WITH SERVICE SO THAT CLIENTS CAN FIND US
            // AN ALREADY REGISTERED SERVICE WILL BE REPLACED
            Naming.rebind( registration, bulbService );
            */

        }catch (RemoteException e){
            System.err.println ("Remote Error - " + e);
        }catch (Exception e){
            System.err.println ("Error - " + e);
        }
    }
}

Tags : ,

aula05ThreadsMultiplasParalelas

class ParallelPi extends Thread {
    private int myId, nThreads, nIntervals, myIntervals;
    private double dX;
    private double myResult;

    public ParallelPi(int myId, int nThreads, int nIntervals) {
        this.myId = myId;
        this.nThreads = nThreads;
        this.nIntervals = nIntervals;
        //calculo do uso da largura
        dX = 1.0 / (double) nIntervals;
        myResult = 0;
        myIntervals = 0;
    }

    public double getMyResult() {
        return myResult;
    }

    public int getMyIntervals() {
        return myIntervals;
    }

    //o que a thread executa
    @Override
    public void run() {
        double i, xi;
        myResult = 0;

        //verificações relacionadas com as threadas e ids das threads
        if (nIntervals < 1 || nThreads < 1 || myId < 1 || myId > nThreads) {
            return;
        }
        for (i = myId - 1; i < nIntervals; i += nThreads) {
            xi = dX * (i + 0.5);
            myResult += (4.0 / (1.0 + xi * xi));
            myIntervals++;
        }
        myResult *= dX;
    }
}

public class aula05ThreadsMultiplasParalelas {
    public static void main(String[] args) throws InterruptedException {
        ParallelPi[] t; //Working threads
        int i, nThreads;
        long nIntervals;
        double pi = 0.0;
        if (args.length != 2) {
            System.out.println("Sintaxe: java ParallelPi <número de intervalos > < número de threads>");
            return;
        }
        nIntervals = Integer.parseInt(args[0]);
        nThreads = Integer.parseInt(args[1]);
        t = new ParallelPi[nThreads];
        for (i = 0; i < nThreads; i++) {
            t[i] = new ParallelPi(i + 1, nThreads, (int) nIntervals);
            t[i].start();
        }

        pi = 0;
        for (i = 0; i < nThreads; i++) {
            t[i].join();
            pi += t[i].getMyResult();
        }
        System.out.println("Valor aproximado de pi: " + pi);
    } //main
} //class ParallelPi
Tags : ,

aula04TSincronizacaoII

//java -cp . aula04TSincronizacaoII
class SynchBlock implements Runnable {
// A STRING WHICH CAN BE MODIFIED.
// ACCESS TO BUFFER AIMS AT BEING SYNCHRONIZED
// WITHOUT MODIFYING STRINGBUFFER.
    StringBuffer buffer; //acumulador
    int counter;

    public SynchBlock() {
        buffer = new StringBuffer();
        counter = 1;
    }

    //a thread
    public void run() {
       // { //sem sincronized
        synchronized (buffer) { // sincronização..
            System.out.println("Starting synchronized block [ "+ Thread.currentThread().getName() +"]");
            int tempVariable = counter++; //variavel temp= 0, mas o counter=1

// CREATE MESSAGE TO ADD TO BUFFER, INCLUDING LINE FEED
            String message = "Count value is : " + tempVariable + System.lineSeparator();
            try {
                // SIMULATE TIME NEEDED FOR SOME TASK
                Thread.sleep(100);
            } catch (InterruptedException ie) {
            }
            buffer.append(message);
            System.out.println("... ending synchronized block "+ Thread.currentThread().getName() +"]");
        }
    }
}
//java -cp . aula04TSincronizacaoII
public class aula04TSincronizacaoII {
    public static void main(String args[]) throws Exception {
// CREATE A NEW RUNNABLE INSTANCE
        SynchBlock block = new SynchBlock();
        Thread t1 = new Thread(block);
        Thread t2 = new Thread(block);
        Thread t3 = new Thread(block);
        Thread t4 = new Thread(block);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
// WAIT FOR ALL THREE THREADS TO FINISH
        t1.join();
        t2.join();
        t3.join();
        t4.join();
// COUNT SHOULD APPEAR IN THE CORRECT ORDER
        System.out.println(block.buffer);
    }
}
Tags : ,

aula04TSincronizacao

class Counter {
    private int countValue;

    public Counter() {
        countValue = 0;
    }

    public Counter(int start) {
        countValue = start;
    }

    //public void increaseCount() {
    public synchronized void increaseCount() {
        int count = countValue;
        // SIMULATE SLOW DATA PROCESSING AND MODIFICATION.
        // REMOVE THE SYNCHRONIZED KEYWORD AND SEE WHAT HAPPENS...
        try {
            Thread.sleep(5);
        } catch (InterruptedException ie) {
        }
        count = count + 1;
        countValue = count;

        System.out.println("<" + Thread.currentThread().getName() + " >: cout = " + countValue);
    }

    public synchronized int getCount() {
        return countValue;
    }
}

class CountingThread implements Runnable {
    Counter myCounter;
    int countAmount;

    // CONSTRUCT A COUNTING THREAD TO USE THE SPECIFIED COUNTER
    public CountingThread(Counter counter, int amount) {
        myCounter = counter;
        countAmount = amount;
    }

    public void run() {
         // INCREASE THE COUNTER THE SPECIFIED NUMBER OF TIMES
        for (int i = 1; i <= countAmount; i++) {
            // INCREASE THE COUNTER
            myCounter.increaseCount(); //SYNCHRONIZED METHOD
        }
    }
}

public class aula04TSincronizacao {
    public static void main(String[] args) throws InterruptedException {

        // CREATE A NEW, THREAD-SAFE COUNTER
        Counter c = new Counter();

        // OUR RUNNABLE INSTANCE WILL INCREASE THE COUNTER
        // TEN TIMES, FOR EACH THREAD THAT RUNS IT
        Runnable runner = new CountingThread(c, 10);
        System.out.println("Starting counting threads");
        Thread t1 = new Thread(runner);
        Thread t2 = new Thread(runner);
        Thread t3 = new Thread(runner);
        t1.start();
        t2.start();
        t3.start();

        // WAIT FOR ALL THREE THREADS TO FINISH
        t1.join();
        t2.join();
        t3.join();

        //aguardo que as threads terminem
        System.out.println("Counter value is " + c.getCount());
    }
}
Tags : ,

aula04ThreadsComunicacao


public class aula04ThreadsComunicacao extends Thread{
    public static void main(String args[]) throws Exception
    {
// START THE ADDITIONAL NEW THREAD THE MAIN THREAD WILL BE AINTING FOR.
        Thread notificationThread = new aula04ThreadsComunicacao();
        notificationThread.start();

// WAIT FOR THE NOTIFICATION THREAD TO TRIGGER EVENT
        synchronized (notificationThread){
            notificationThread.wait();
        }

// NOTIFY USER THAT THE WAIT() METHOD HAS RETURNED
        System.out.println ("The wait is over");
    }
    public void run()
    {

//THIS IS THE ADDITONAL THREAD WHICH WAS CREATED+STARTED BY THE MAIN THREAD
        System.out.println ("Hit enter to stop waiting thread");
        try {
            System.in.read();
        }catch (java.io.IOException e){}

// NOTIFY ANY THREADS WAITING ON THIS THREAD
        synchronized (this){
            this.notifyAll();
        }
    }
}
Tags : ,

aula03TPararThreads

import java.io.IOException;

class StopMe extends Thread {
    private boolean stopRunning = false;

    public void setStop(boolean stopRunning) {
        this.stopRunning = stopRunning;
    }

    public void run() {
        int count = 1;
        System.out.println("I can count. Watch me go!");
        for (; ; ) {
            if (stopRunning) return;
            System.out.print(count++ + " ");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
            }
        }
    }
}

//sem forçar a terminar uma thread, abordagem correta
public class aula03PararThreads {

    public static void main(String[] args) throws IOException {
        Thread counter = new StopMe();
        counter.start();
        System.out.println ("Press any enter to stop the thread counting");
        System.in.read();
        ((StopMe) counter).setStop(true);
    }
}
Tags : ,

aula03ThreadSleepy

class SleepyHead extends Thread {
    // RUN METHOD IS EXECUTED WHEN THREAD FIRST STARTED
    public void run() {
        System.out.println("I feel sleepy. Wake me in eight hours");
        try {
            // SLEEP FOR EIGHT HOURS
            Thread.sleep(1000 * 60 * 60 * 8);
            System.out.println("That was a nice nap");
        } catch (InterruptedException e) {
            System.err.println("Just five more minutes....");
        }
    }
}

public class aula03ThreadSleepy {

    public static void main(String args[]) throws java.io.IOException {
        // CREATE A 'SLEEPY' THREAD
        Thread sleepy = new SleepyHead();

        // START THREAD SLEEPING
        sleepy.start();

        // PROMPT USER AND WAIT FOR INPUT
        System.out.println("Press enter to interrupt the thread");
        System.in.read();

        // INTERRUPT THE THREAD (DEPRECATED: TO SAFELY TERMINATE A THREAD LET IT DIE
        // OR MAKE IT EXIT ITS METHOD RUN())
        sleepy.interrupt(); //RESUME() METHOD TO RESUME THE THREAD
    }
}
Tags : ,

Aula03ThreadII

class RunnableThreadDemo implements java.lang.Runnable {
    // RUN METHOD IS EXECUTED WHEN THREAD FIRST STARTED
    public void run() {
        System.out.println("I am an instance of the java.lang.Runnable  interface ");
    }

}

public class aula03ThreadII {
    public static void main(String[] args) {
        System.out.println("Creating runnable object");

        // CREATE RUNNABLE OBJECT
        Runnable run = new RunnableThreadDemo();

        // CREATE A THREAD, AND PASS THE RUNNABLE OBJECT
        System.out.println("Creating first thread");
        Thread t1 = new Thread(run, "Thread 1");

        // CREATE A SECOND THREAD, AND PASS THE RUNNABLE OBJECT
        System.out.println("Creating second thread");
        Thread t2 = new Thread(run, "Thread 2");

        // START BOTH THREADS
        System.out.println("Starting both threads");
        t1.start();
        t2.start();
    }
}
Tags : ,

aula02TCliente

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

//ligação TCP
public class aula02TCliente {
    public static final int SERVICE_PORT = 5001;
    static Socket daytime = null;

    public static void main(String args[]) throws IOException {
        if (args.length != 1){
            System.out.println ("Syntax – java DaytimeClient host");
            return;
        }

        // GET THE HOSTNAME OF SERVER
        String hostname = args[0];
        try {
            daytime = new Socket (hostname, SERVICE_PORT);
            System.out.println ("Connection established");

            // SET THE SOCKET OPTION JUST IN CASE SERVER STALLS
            daytime.setSoTimeout( 2000 ); //ms

            // READ FROM THE SERVER
            BufferedReader reader = new BufferedReader(new InputStreamReader(daytime.getInputStream()));
            System.out.println ("Results : " + reader.readLine()); //mudança de linha ou receber um socket fechar

            // CLOSE THE CONNECTION
            daytime.close();
        }catch (IOException e){ //catches also InterruptedIOException
            System.err.println ("Error " + e);
        }finally {
            //fechar o socket se ele for aberto
            if(daytime == null){
                daytime.close();
            }
        }
    }
}
Tags : ,

aula01TServidor

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


//destinatário, receptor
public class Servidor {
    public static void main (String args[]) {
        try {
            System.out.println("Binding to local port 2000");

            // CREATE A DATAGRAM SOCKET, BOUND TO THE SPECIFIC PORT 2000
            DatagramSocket socket = new DatagramSocket(2000);

            // CREATE A DATAGRAM PACKET WITH A MAXIMUM BUFFER OF 256 BYTES
            DatagramPacket packet = new DatagramPacket(new byte[256], 256);

            // RECEIVE A PACKET (BY DEFAULT, THIS IS A BLOCKING OPERATION)
            socket.receive(packet);

            // DISPLAY PACKET INFORMATION
            InetAddress remote_addr = packet.getAddress();
            System.out.println("Sent by: " + remote_addr.getHostAddress());
            System.out.println("Sent from port: " + packet.getPort());
            //apenas os bytes que foram copiados packet.getData()
            String msg = new String(packet.getData(), 0, packet.getLength());
            System.out.println(msg);

            socket.close();
        } catch (IOException e) {
            System.err.println("Error - " + e);
        }
    }}
Tags : ,

aula01TCliente

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

//emissor
public class Cliente {
    public static void main (String args[]){
        // CHECK FOR VALID NUMBER OF PARAMETERS
        int argc = args.length;
        if (argc != 1){
            System.out.println ("Syntax :");
            System.out.println ("java PacketSendDemo hostname");
            return;
        }
        String hostname = args[0];
        try{
            System.out.println ("Binding to a local port");

            // CREATE A DATAGRAM SOCKET, BOUND TO ANY AVAILABLE LOCAL PORT
            DatagramSocket socket = new DatagramSocket();
            System.out.println ("Bound to local port " + socket.getLocalPort());

            byte[] barray = "Greetings!".getBytes();

            // CREATE A DATAGRAM PACKET, CONTAINING OUR BYTE ARRAY
            DatagramPacket packet = new DatagramPacket( barray, barray.length );
            System.out.println ("Looking up hostname " + hostname );

            // LOOKUP THE SPECIFIED HOSTNAME, AND GET AN INETADDRESS
            InetAddress addr = InetAddress.getByName(hostname);
            System.out.println ("Hostname resolved as "+addr.getHostAddress());

            // ADDRESS PACKET TO SENDER
            packet.setAddress(addr);

            // SET PORT NUMBER TO 2000
            packet.setPort(2000);

            // SEND THE PACKET - REMEMBER NO GUARANTEE OF DELIVERY
            socket.send(packet);
            System.out.println ("Packet sent!");
        }catch (UnknownHostException e){
            System.err.println ("Can't find host " + hostname);
        }catch (IOException e){
            System.err.println ("Error - " + e);
        }
    }
}
Tags : ,