Ybadoo - Soluções em Software Livre
Tutoriais
Programação Orientada a Objetos

Desenvolva uma classe chamada Server para representar um servidor que verifique se determinado número é primo ou não. O servidor recebe requisições dos clientes por uma fila, chamada de Inbox, e armazena as respostas às requisições numa lista, chamada de Outbox. Desenvolva uma classe chamada Client para representar um cliente que requisita ao servidor se determinado número é primo ou não. O cliente insere as requisições na fila Inbox e espera a resposta na lista Outbox. Para testar o funcionamento do sistema, desenvolva uma aplicação com dois servidores e cinco clientes.

 

Arquivo Request.java

/**
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.ybadoo.com.br)
 *
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 1.3
 * or any later version published by the Free Software Foundation; with
 * no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;

import java.io.Serializable;

/**
 * Classe responsavel pela representacao da requisicao
 */
public class Request implements Serializable
{
  /**
   * Identificador de serializacao da classe
   */
  private static final long serialVersionUID = 1L;

  /**
   * Identificador do solicitante
   */
  private int identifier;

  /**
   * Valor a ser avaliado
   */
  private int value;

  /**
   * Construtor para inicializar a requisicao
   *
   * @param identifier identificador do solicitante
   * @param value valor a ser avaliado
   * @throws IllegalArgumentException parametros invalidos
   */
  public Request(int identifier, int value) throws IllegalArgumentException
  {
    if(identifier > 0)
    {
      this.identifier = identifier;
    }
    else
    {
      throw new IllegalArgumentException("identifier: " + identifier);
    }

    if(value >= 0)
    {
      this.value = value;
    }
    else
    {
      throw new IllegalArgumentException("value: " + value);
    }
  }

  /**
   * Retornar o identificador do solicitante
   *
   * @return identificador do solicitante
   */
  public int getIdentifier()
  {
    return identifier;
  }

  /**
   * Retornar o valor a ser avaliado
   *
   * @return valor a ser avaliado
   */
  public int getValue()
  {
    return value;
  }
}

Arquivo Response.java

/**
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.ybadoo.com.br)
 *
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 1.3
 * or any later version published by the Free Software Foundation; with
 * no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;

import java.io.Serializable;

/**
 * Classe responsavel pela representacao da resposta
 */
public class Response implements Serializable
{
  /**
   * Identificador de serializacao da classe
   */
  private static final long serialVersionUID = 1L;

  /**
   * Requisicao de origem
   */
  private Request request;

  /**
   * Avaliacao da requisicao
   */
  private boolean result;

  /**
   * Construtor para inicializar a resposta
   *
   * @param request requisicao de origem
   * @param result avaliacao da requisicao
   * @throws IllegalArgumentException parametros invalidos
   */
  public Response(Request request, boolean result)
    throws IllegalArgumentException
  {
    if(request != null)
    {
      this.request = request;
    }
    else
    {
      throw new IllegalArgumentException("request: " + request);
    }
    
    this.result = result;
  }

  /**
   * Retornar a requisicao de origem
   * 
   * @return requisicao de origem
   */
  public Request getRequest()
  {
    return request;
  }

  /**
   * Retornar a avaliacao da requisicao
   * 
   * @return avaliacao da requisicao
   */
  public boolean isResult()
  {
    return result;
  }
}

Arquivo Inbox.java

/**
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.ybadoo.com.br)
 *
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 1.3
 * or any later version published by the Free Software Foundation; with
 * no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;

import java.util.LinkedList;
import java.util.List;

/**
 * Classe responsavel pela representacao da caixa de entrada
 */
public class Inbox
{
  /**
   * Caixa de entrada das requisicoes
   */
  private List<Request> inbox;

  /**
   * Construtor padrao
   */
  public Inbox()
  {
    inbox = new LinkedList<Request>();
  }

  /**
   * Receber uma requisicao para ser processada
   *
   * @return requisicao a ser processada
   */
  public synchronized Request receive()
  {
    if(inbox.size() > 0)
    {
      return inbox.remove(0);
    }

    return null;
  }

  /**
   * Adicionar uma requisicao para ser processada
   *
   * @param request requisicao a ser processada
   * @throws IllegalArgumentException requisicao invalida
   */
  public synchronized void sender(Request request)
    throws IllegalArgumentException
  {
    if(request != null)
    {
      inbox.add(request);
    }
    else
    {
      throw new IllegalArgumentException("request: " + request);
    }
  }
}

Arquivo Outbox.java

/**
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.ybadoo.com.br)
 *
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 1.3
 * or any later version published by the Free Software Foundation; with
 * no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;

import java.util.LinkedList;
import java.util.List;

/**
 * Classe responsavel pela representacao da caixa de saida
 */
public class Outbox
{
  /**
   * Caixa de saida das respostas
   */
  private List<Response> outbox;

  /**
   * Construtor padrao
   */
  public Outbox()
  {
    outbox = new LinkedList<Response>();
  }

  /**
   * Receber uma resposta a requisicao
   * @param identifier identificador do solicitante
   * @return resposta a requisicao
   */
  public synchronized Response receive(int identifier)
  {
    for(Response response : outbox)
    {
      if(response.getRequest().getIdentifier() == identifier)
      {
        outbox.remove(response);
        
        return response;
      }
    }
    
    return null;
  }

  /**
   * Adicionar uma resposta a requisicao
   *
   * @param response resposta a requisicao
   * @throws IllegalArgumentException resposta invalida
   */
  public synchronized void sender(Response response)
    throws IllegalArgumentException
  {
    if(response != null)
    {
      outbox.add(response);
    }
    else
    {
      throw new IllegalArgumentException("response: " + response);
    }
  }
}

Arquivo Server.java

/**
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.ybadoo.com.br)
 *
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 1.3
 * or any later version published by the Free Software Foundation; with
 * no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;


/**
 * Classe responsavel pela representacao do servidor
 */
public class Server extends Thread
{
  /**
   * Caixa de entrada com as requisicoes
   */
  private Inbox inbox;
  
  /**
   * Identificador do servidor
   */
  private int identifier;
  
  /**
   * Caixa de saida com as respostas as requisicoes
   */
  private Outbox outbox;
  
  /**
   * Construtor para inicializar o servidor
   * 
   * @param identifier identificador do servidor
   * @param inbox caixa de entrada com as requisicoes
   * @param outbox caixa de saida com as respostas as requisicoes
   * @throws IllegalArgumentException parametros invalidos
   */
  public Server(int identifier, Inbox inbox, Outbox outbox)
    throws IllegalArgumentException
  {
    if(identifier > 0)
    {
      this.identifier = identifier;
    }
    else
    {
      throw new IllegalArgumentException("identifier: " + identifier);
    }
    
    if(inbox != null)
    {
      this.inbox = inbox;
    }
    else
    {
      throw new IllegalArgumentException("inbox: " + inbox);
    }

    if(outbox != null)
    {
      this.outbox = outbox;
    }
    else
    {
      throw new IllegalArgumentException("outbox: " + outbox);
    }
  }
  
  /* (non-Javadoc)
   * @see java.lang.Thread#run()
   */
  public void run()
  {
    while(true)
    {
      Request request = null;
      
      while(request == null)
      {
        try
        {
          sleep((int) (Math.random() * 1000));
        }
        catch(InterruptedException exception)
        {
          exception.printStackTrace();
        }
        
        request = inbox.receive();
      }
        
      System.out.println("Servidor " + identifier
        + ": avaliando solicitação do cliente " + request.getIdentifier()
        + ": número " + request.getValue());
        
      boolean result = true;
        
      for(int i = 2; (i < request.getValue()) && result; i++)
      {
        result = (request.getValue() % i) != 0;
      }
        
      outbox.sender(new Response(request, result));
    }
  }
}

Arquivo Client.java

/**
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.ybadoo.com.br)
 *
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 1.3
 * or any later version published by the Free Software Foundation; with
 * no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;

/**
 * Classe responsavel pela representacao do cliente
 */
public class Client extends Thread
{
  /**
   * Identificador do cliente
   */
  private int identifier;
  
  /**
   * Caixa de entrada com as requisicoes
   */
  private Inbox inbox;

  /**
   * Caixa de saida com as respostas as requisicoes
   */
  private Outbox outbox;
  
  /**
   * Construtor para inicializar o servidor
   * 
   * @param identifier identificador do cliente
   * @param inbox caixa de entrada com as requisicoes
   * @param outbox caixa de saida com as respostas as requisicoes
   * @throws IllegalArgumentException parametros invalidos
   */
  public Client(int identifier, Inbox inbox, Outbox outbox)
    throws IllegalArgumentException
  {
    if(identifier > 0)
    {
      this.identifier = identifier;
    }
    else
    {
      throw new IllegalArgumentException("identifier: " + identifier);
    }
    
    if(inbox != null)
    {
      this.inbox = inbox;
    }
    else
    {
      throw new IllegalArgumentException("inbox: " + inbox);
    }

    if(outbox != null)
    {
      this.outbox = outbox;
    }
    else
    {
      throw new IllegalArgumentException("outbox: " + outbox);
    }
  }
  
  /* (non-Javadoc)
   * @see java.lang.Thread#run()
   */
  public void run()
  {
    while(true)
    {
      int value = (int) (Math.random() * 100);
      
      System.out.println("Cliente " + identifier
        + ": solicitar avaliação do número " + value);
      
      inbox.sender(new Request(identifier, value));
      
      Response response = null;
      
      while(response == null)
      {
        response = outbox.receive(identifier);
        
        try
        {
          sleep((int) (Math.random() * 1000));
        }
        catch(InterruptedException exception)
        {
          exception.printStackTrace();
        }
      }
      
      if(response.isResult())
      {
        System.out.println("Cliente " + identifier
          + ": número " + value + " é primo!");
      }
      else
      {
        System.out.println("Cliente " + identifier
          + ": número " + value + " não é primo!");
      }
      
      try
      {
        sleep((int) (Math.random() * 1000));
      }
      catch(InterruptedException exception)
      {
        exception.printStackTrace();
      }
    }
  }
}

Arquivo Application.java

/**
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.ybadoo.com.br)
 *
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 1.3
 * or any later version published by the Free Software Foundation; with
 * no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;

/**
 * Classe responsavel pela execucao do sistema
 */
public class Application
{
  /**
   * Metodo principal da linguagem de programacao Java
   *
   * @param args argumentos da linha de comando (nao utilizado)
   */
  public static void main(String[] args)
  {
    Inbox inbox = new Inbox();
    
    Outbox outbox = new Outbox();
    
    new Client(1, inbox, outbox).start();
    
    new Client(2, inbox, outbox).start();
    
    new Client(3, inbox, outbox).start();
    
    new Client(4, inbox, outbox).start();
    
    new Client(5, inbox, outbox).start();
    
    new Server(1, inbox, outbox).start();
    
    new Server(2, inbox, outbox).start();
  }
}

Saída

Cliente 2: solicitar avaliação do número 13
Cliente 3: solicitar avaliação do número 81
Cliente 1: solicitar avaliação do número 48
Cliente 5: solicitar avaliação do número 30
Cliente 4: solicitar avaliação do número 95
Servidor 2: avaliando solicitação do cliente 2: número 13
Servidor 2: avaliando solicitação do cliente 5: número 30
Servidor 1: avaliando solicitação do cliente 4: número 95
Cliente 4: número 95 não é primo!
Cliente 4: solicitar avaliação do número 19
Servidor 1: avaliando solicitação do cliente 3: número 81
Cliente 5: número 30 não é primo!
Cliente 2: número 13 é primo!
Servidor 2: avaliando solicitação do cliente 1: número 48
Servidor 1: avaliando solicitação do cliente 4: número 19
Cliente 3: número 81 não é primo!
Cliente 1: número 48 não é primo!
Cliente 1: solicitar avaliação do número 82
Cliente 2: solicitar avaliação do número 27
Servidor 2: avaliando solicitação do cliente 1: número 82
Cliente 5: solicitar avaliação do número 94
Cliente 4: número 19 é primo!
Servidor 1: avaliando solicitação do cliente 2: número 27
Cliente 3: solicitar avaliação do número 4
Servidor 2: avaliando solicitação do cliente 5: número 94
Cliente 4: solicitar avaliação do número 59