77 Matching Annotations
  1. Oct 2023
    1. ``` @Test void test() { PlacesListManagerInterface plm; PlacesListManagerInterface plmret; PlacesListInterface pli; ObjectRegistryInterface ori;

          try{
              System.out.println("Localizar ReplicaManager...");
              plm  = (PlacesListManagerInterface) Naming.lookup("rmi://localhost:2024/replicamanager");
      
              Place p1 = new Place("3510", "Viseu");
              System.out.println("Invocar addPlace() no ReplicaManager para 3510...");
              plm.addPlace(p1);
      
              Place p2 = new Place("1000", "Lisboa");
              System.out.println("Invocar addPlace() no ReplicaManager para 1000...");
              plm.addPlace(p2);
      
              Place p3 = new Place("4000", "Lisboa");
              System.out.println("Invocar addPlace() no ReplicaManager para 4000...");
              plm.addPlace(p3);
      
              System.out.println("Obter o endereço do ReplicaManager no Registry() para o ObjectID 1000 ...");
              ori = (ObjectRegistryInterface) Naming.lookup("rmi://localhost:2023/registry");
              String addrRM = ori.resolve("1000");
      
              System.out.println("Pedir ao ReplicaManager para devolver um PlaceManager para o ObjectID 1000 ...");
              plm = (PlacesListManagerInterface) Naming.lookup(addrRM);
              boolean pl1done = false;
              boolean pl2done = false;
              boolean pl3done = false;
              String plAddress = null;
              for(int i=0; i<10 ; i++) {
                  plAddress = plm.getPlaceListAddress("1000");
                  System.out.println("\tDevolveu " + plAddress);
                  if(plAddress.equals("rmi://localhost:2025/placelist")) pl1done=true;
                  else if(plAddress.equals("rmi://localhost:2026/placelist")) pl2done=true;
                       else if(plAddress.equals("rmi://localhost:2027/placelist")) pl3done=true;
              }
      
              if(!(pl1done==pl2done==pl3done==true)) fail("Não está a devolver um PlaceManager aleatório...");
      
              System.out.println("Invocar getPlace() no PlaceManager");
              pli  = (PlacesListInterface) Naming.lookup(plAddress);
              String locality = pli.getPlace("1000").getLocality();
      
              System.out.println("\tDevolveu " + locality);
              assertEquals("Lisboa", locality);
      
      
          } catch(Exception e) { fail("Erro\n" + e.getMessage()); }
      }
      

      ```

    1. java class PlaceManager extends UnicastRemoteObject implements PlacesListInterface{ ... }

    1. Cenário de Teste 1 -> Msg 2 -> Msg 3 -> Msg 5 -> waitingfor,4 6 -> waitingfor,4 8 -> waitingfor,4 9 -> waitingfor,4 4 -> waitingfor,7 7 -> Msg

    1. Person p = (Person) ois.readObject(); String loc = p.getPlace().getLocality();

    1. ret =  ois.readObject();

      Person ret = (Person) ois.readObject();

  2. Sep 2023
    1. Algoritmo principal receber a mensagem M se M estiver em ordem processar M processar mensagens seguintes da lista, se houver senão colocar M na lista temporária a comunicação é request->reply (não pode haver vários replies para um request), logo reply = "waitingfor,x" se a lista tiver elementos ou reply = "última mensagem processada" para lista vazia

      Documentação do Hashmap https://www.w3schools.com/java/java_hashmap.asp

    2. Código de teste utilizado pelo Break.IT para validar a implementação ``` @Test public void test() throws IOException {

          DatagramSocket aSocket = null;
      
          //try {
      
              aSocket = new DatagramSocket();  
              aSocket.setSoTimeout(5000);
              int nMessage=1;
      
              String m= "vou enviar esta mensagem ao servidor";
      
              InetAddress aHost = InetAddress.getByName("localhost");
      
              int serverPort = 6789;
              while(nMessage < 10) {
                  if(nMessage == 4 || nMessage == 7) nMessage++;
                  byte[] mb= (String.valueOf(nMessage).concat(",").concat(m)).getBytes();
      
                  DatagramPacket reply = sendDatagramAndWaitForResponse(aSocket, aHost, serverPort, mb);
                  if(nMessage > 4)
                      assertEquals("waitingfor,"+4, new String(reply.getData()).trim());
                  else
                      assertEquals(m, new String(reply.getData()).trim());
                  nMessage++;
              }
      
              byte[] mb= (String.valueOf(4).concat(",").concat(m)).getBytes();            
              DatagramPacket reply = sendDatagramAndWaitForResponse(aSocket, aHost, serverPort, mb);
              assertEquals("waitingfor,"+7, new String(reply.getData()).trim());
      
              mb= (String.valueOf(7).concat(",").concat(m)).getBytes();           
              reply = sendDatagramAndWaitForResponse(aSocket, aHost, serverPort, mb);
              assertEquals(m, new String(reply.getData()).trim());
      
              mb= (String.valueOf(10).concat(",").concat(m)).getBytes();          
              reply = sendDatagramAndWaitForResponse(aSocket, aHost, serverPort, mb);
              assertEquals(m, new String(reply.getData()).trim());
      
          //}catch (SocketException e){System.out.println("Socket: " + e.getMessage()); fail("");
      
          //}catch (IOException e){System.out.println("IO: " + e.getMessage()); fail("");
      
      //  }finally {if(aSocket != null) aSocket.close();}
      
      }
      

      private DatagramPacket sendDatagramAndWaitForResponse(DatagramSocket aSocket, InetAddress aHost, int serverPort, byte[] mb) throws IOException { DatagramPacket request = new DatagramPacket(mb, mb.length, aHost, serverPort);

          aSocket.send(request);
      
          byte[] buffer = new byte[1000];
      
          DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
      
          aSocket.receive(reply);
          System.out.println("Enviei/recebi a mensagem: " + new String(reply.getData()));
          return reply;
      }
      

      ```

    1. do lado do cliente, é necessário concatenar o número da mensagem com o texto da mensagem java msgEnviada = i + "," + "vou enviar esta ...."; do lado do servidor é necessário fazer o split da mensagem de forma a obter o número da mesma e o texto, separadamente java numero = msgRecebida.split(",")[0] msg = msgRecebida.split(",")[1] Código utilizado para validar a solução: ```java public void test() {

      DatagramSocket aSocket = null;
      
      try {
      
          aSocket = new DatagramSocket();
          aSocket.setSoTimeout(5000);
          int nMessage=1;
      
          String m= "vou enviar esta mensagem ao servidor";
      
          InetAddress aHost = InetAddress.getByName("localhost");
          int serverPort = 6789;
          while(nMessage < 10) {
              if(nMessage == 4 || nMessage == 7) nMessage++;
              byte[] mb= (String.valueOf(nMessage).concat(",").concat(m)).getBytes();
      
              DatagramPacket request = new DatagramPacket(mb,  mb.length, aHost, serverPort);
      
              aSocket.send(request);
      
              byte[] buffer = new byte[1000];
      
              DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
      
              aSocket.receive(reply);
              System.out.println("Enviei/recebi a mensagem: " + new String(reply.getData()));
              if(nMessage >= 5)
                  assertEquals("waitingfor,"+ 4, new String(reply.getData()).trim());
              else
                  assertEquals(m, new String(reply.getData()).trim());
              nMessage++;
          }
      
      }catch (SocketException e){System.out.println("Socket: " + e.getMessage()); fail("");
      
      }catch (IOException e){System.out.println("IO: " + e.getMessage()); fail("");
      
      }finally {if(aSocket != null) aSocket.close();}
      

      } ```

  3. May 2023
    1. ```java import static org.junit.jupiter.api.Assertions.*;

      import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream;

      import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test;

      import com.es2.decorator.Auth; import com.es2.decorator.AuthException; import com.es2.decorator.AuthInterface; import com.es2.decorator.CommonWordsValidator; import com.es2.decorator.End; import com.es2.decorator.Logging;

      class TestDecorator { private static final ByteArrayOutputStream outContent = new ByteArrayOutputStream();

      @BeforeEach
      void setUp() throws Exception {
      }
      
      @BeforeAll
      public static void setUpStreams() {
          System.setOut(new PrintStream(outContent));
      }
      
      @AfterAll
      public static void tearDownAfterClass() {
          System.setOut(System.out);
          End e = new End();
      }
      
      @DisplayName("Test if authentication is performed correctly using admin/admin")
      @Test
      void testRightAuthWithoutDecorators() throws AuthException, IOException {
          AuthInterface auth = new Auth();
      
          auth.auth("admin", "admin");
      }
      
      @DisplayName("Test if authentication exception is thrown for bad authentication")
      @Test
      void testWrongAuthWithoutDecorators() throws AuthException, IOException {
          AuthInterface auth = new Auth();
      
          assertThrows(AuthException.class, ()->{
              auth.auth("admin1", "admin1");
          });
      }
      
      @DisplayName("Test if Logging is decorating correctly the authentication")
      @Test
      void testLoggingDecorator() throws AuthException, IOException {
          AuthInterface auth = new Logging(new Auth());
      
          auth.auth("admin", "admin");
          assertTrue(outContent.toString().contains("auth()"));
      }
      
      @DisplayName("Test if CommonWordsValidator is decorating correctly the authentication")
      @Test
      void testCommonWordsValidatorDecorator() throws AuthException, IOException {
          AuthInterface auth = new CommonWordsValidator(new Auth());
      
          auth.auth("admin", "admin");
      }
      
      @DisplayName("Test if CommonWordsValidator is decorating correctly the authentication")
      @Test
      void testCommonWordsValidatorDecoratorIfFalse() throws AuthException, IOException {
          AuthInterface auth = new CommonWordsValidator(new Auth());
      
          assertThrows(AuthException.class,()->{
              auth.auth("admin1", "admin1");
          });
      }
      
      @DisplayName("Test if Logging and CommonWordsValidator is decorating correctly the authentication")
      @Test
      void testLoggingCommonWordsValidatorDecorator() throws AuthException, IOException {
          AuthInterface auth = new CommonWordsValidator(new Logging(new Auth()));
      
          auth.auth("admin", "admin");
      }
      

      } ```

  4. Feb 2023
    1. ``` java import static org.junit.jupiter.api.Assertions.*;

      import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test;

      import com.es2.bridge.APIMoodle; import com.es2.bridge.APIRequest; import com.es2.bridge.APIRequestContentAggregator; import com.es2.bridge.ServiceNotFoundException;

      class BridgePatternTest { APIRequest req;

      @BeforeEach
      void setUp() throws Exception {
      }
      
      @DisplayName("Test if the exception is thrown for not existing services")
      @Test
      void testServiceNotFoundExceptionThrown() {
          req= new APIRequest();
          assertThrows(ServiceNotFoundException.class,
                  ()->{
                          req.getContent("abc", "12");
                  });
      }
      
      @DisplayName("Test if the request returns null for not existing content")
      @Test
      void testRequestReturnsNull() throws ServiceNotFoundException {
          req= new APIRequest();
          String idService = req.addService(new APIMoodle());
          assertNull(req.getContent(idService, "12"));
      }
      
      @DisplayName("Test if the request returns the content previously added")
      @Test
      void testContentPreviouslyAdded() throws ServiceNotFoundException {
          req= new APIRequest();
          String idService = req.addService(new APIMoodle());
          String idContent = req.setContent(idService, "12");
          assertEquals(req.getContent(idService,idContent),"12");
      }
      
      @DisplayName("Test if the aggregated content of one service is returned correctly")
      @Test
      void testAggregatedContent() throws ServiceNotFoundException {
          req= new APIRequestContentAggregator();
          String idService = req.addService(new APIMoodle());
          req.setContent(idService, "Eu vou");
          req.setContent(idService, " a Viseu");
          req.setContent(idService, " estudar");
          assertEquals(req.getContent(idService,"0"),"Eu vou a Viseu estudar");
      }
      

      } ```

    1. ```java import static org.junit.jupiter.api.Assertions.*;

      import java.io.IOException; import java.lang.reflect.Modifier; import java.net.HttpURLConnection; import java.util.ArrayList;

      import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test;

      import com.es2.objectpool.ObjectNotFoundException; import com.es2.objectpool.PoolExhaustedException; import com.es2.objectpool.ReusablePool;

      class ObjectPoolTest { @BeforeEach void setUp() throws Exception { }

      @Test
      @DisplayName("Test whether important methods are synchronized")
      void testSynchronized() throws NoSuchMethodException, SecurityException {
          if( ! Modifier.isSynchronized(ReusablePool.class.getMethod("acquire").getModifiers()) || 
              ! Modifier.isSynchronized(ReusablePool.class.getMethod("release",HttpURLConnection.class).getModifiers()) ||
              ! Modifier.isSynchronized(ReusablePool.class.getMethod("resetPool").getModifiers())
          ){
              fail("Methods are not thread safe!!! Don't forget that you are moving connections between two lists!!!");   
          }
      }
      
      @Test
      @DisplayName("Test if constructor is not public")
      void testPrivateConstructor() throws NoSuchMethodException, SecurityException{
          if(Modifier.isPublic(ReusablePool.class.getDeclaredConstructor().getModifiers())){
              fail("Singleton objects should protect their constructor!!!");  
          }
      }
      
      @Test
      @DisplayName("Test maximum number of connections for acquiring")
      void testMaxConnectionsWithoutInitMaxConnections() throws IOException, PoolExhaustedException, ObjectNotFoundException {
          ArrayList<HttpURLConnection> conns = new ArrayList<HttpURLConnection>();
          ReusablePool.getInstance().setMaxPoolSize(11);
          for(int i =0; i< 11; i++)
              conns.add(ReusablePool.getInstance().acquire());
          for(int i =0; i< 11; i++)
              ReusablePool.getInstance().release(conns.get(i));
      
          ReusablePool.getInstance().resetPool();
      }
      
      @Test
      @DisplayName("Test if max connections are initialized")
      void testInitMaxConnections() throws IOException, PoolExhaustedException, ObjectNotFoundException {
          ArrayList<HttpURLConnection> conns = new ArrayList<HttpURLConnection>();
          for(int i =0; i< 10; i++)
              conns.add(ReusablePool.getInstance().acquire());
          for(int i =0; i< 10; i++)
              ReusablePool.getInstance().release(conns.get(i));
          ReusablePool.getInstance().resetPool();
      }
      
      @Test
      @DisplayName("Test if PoolExhaustedException is thrown")
      void testThrowsPoolExhaustedException() throws ObjectNotFoundException {
          ArrayList<HttpURLConnection> conns = new ArrayList<HttpURLConnection>();
          assertThrows(PoolExhaustedException.class,
                  ()->{
                      for(int i =0; i< 11; i++)
                          conns.add(ReusablePool.getInstance().acquire());
                  });
      
          ReusablePool.getInstance().resetPool();
      }
      
      @Test
      @DisplayName("Test if ObjectNotFoundException is thrown when object released not exists in the pool")
      void testThrowsObjectNotFoundException() {
          assertThrows(ObjectNotFoundException.class,
                  ()->{
                          HttpURLConnection conn = ReusablePool.getInstance().acquire();
                          ReusablePool.getInstance().release(conn);
                          ReusablePool.getInstance().release(conn);
                  });
          ReusablePool.getInstance().resetPool();
      }
      

      } ```

  5. Oct 2022
    1. ``` import static org.junit.jupiter.api.Assertions.*;

      import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException;

      import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test;

      class TCP003 { static Thread t;

      @BeforeAll
      public static void runServer() throws InterruptedException {
              t = (new Thread() {
                  public void run() {
                      TCPServer.main(new String[0]);
                      }
                      });
              t.start();
              Thread.sleep(1000);
      }
      
      @AfterAll
      public static void stopServer() {
          t.interrupt();
      }
      
      @Test
      void test() {
              int idPlace1 = Integer.parseInt(sendAndReceive(new Request(new Place("3510","Viseu")))); 
              int idPlace2 = Integer.parseInt(sendAndReceive(new Request(new Place("2000","Viseu"))));
      
              assertEquals("Viseu",sendAndReceive(new Request(idPlace1,"getLocality")));
              assertEquals("2000",sendAndReceive(new Request(idPlace2,"getPostalCode")));
              assertEquals("invalid objectid",sendAndReceive(new Request(idPlace2+1,"getPostalCode")));
              assertEquals("invalid method",sendAndReceive(new Request(idPlace2,"getPostalCode2")));
      }
      
      String sendAndReceive(Request o) {
          Socket s = null;
      
          try{
      
              int serverPort = 7896; //porto do servidor
              s = new Socket("localhost", serverPort);
              s.setSoTimeout(5000);
              DataInputStream in = new DataInputStream( s.getInputStream());
              DataOutputStream out = new DataOutputStream( s.getOutputStream());
              ObjectOutputStream oos = new ObjectOutputStream(out);
      
              oos.writeObject(o);
              return in.readUTF();
          }catch (UnknownHostException e){
              fail("Sock:"+e.getMessage());
          }catch (EOFException e){
              fail("IO:" + e.getMessage());
          }catch (IOException e){
              fail("IO:"+e.getMessage());
          }finally {
              if(s!=null)
                  try {
                      s.close();
                  }catch (IOException e){
                      fail("close:"+e.getMessage());}
      
          }
          return null;
      
      }
      

      } ```

  6. Mar 2022
    1. ``` @Test @DisplayName("Test if the server returns to the initial server state") void testAddReturnInitialServerState() throws ExistingStudentException, NotExistingSnapshotException { Server s = new Server(); BackupService backup = new BackupService(s); backup.takeSnapshot(); s.addStudent("Maria José"); s.addStudent("Manuel António");

          assertEquals(s.getStudentNames().size(), 2);
      
          backup.restoreSnapshot(0);      
          assertEquals(s.getStudentNames().size(), 0);
      }
      
      @Test
      @DisplayName("Test if the server returns to a previous snapshot")
      void testAddReturnToPreviousSnapshot() throws ExistingStudentException, NotExistingSnapshotException {
          Server s = new Server();
          BackupService backup =  new BackupService(s);
          backup.takeSnapshot();
          s.addStudent("Maria José");
          backup.takeSnapshot();
          s.addStudent("Manuel António");
      
          assertEquals(2, s.getStudentNames().size());
      
          backup.restoreSnapshot(1);      
          assertEquals(1, s.getStudentNames().size());
      }
      
      @Test
      @DisplayName("Test if the server ExistingStudentException is thrown")
      void testExistingStudentExceptionThrown() throws ExistingStudentException {
          Server s = new Server();
          s.addStudent("Maria José");
          assertThrows(ExistingStudentException.class,()->{
              s.addStudent("Maria José");
          });
      }
      
      @Test
      @DisplayName("Test if the server NotExistingSnapshotException is thrown")
      void testNotExistingSnapshotException() throws ExistingStudentException {
          Server s = new Server();
          BackupService backup =  new BackupService(s);
          backup.takeSnapshot();
          s.addStudent("Maria José");
          backup.takeSnapshot();
          s.addStudent("Manuel António");
      
          assertThrows(NotExistingSnapshotException.class,()->{
              backup.restoreSnapshot(2);
          });
      }
      

      ```

  7. Nov 2021
    1. PlacesListInterface l1 = null;
              try{
                  System.out.println("Localizar servidor de Objetos...");
                  l1  = (PlacesListInterface) Naming.lookup("rmi://localhost:2022/placelist");
      
                  Place p = new Place("3510", "Viseu");
                  System.out.println("Invocar addPlace() ...");
                  l1.addPlace(p);
      
                  System.out.println("Obter o endereço do servidor no Registry() ...");
                  ObjectRegistryInterface l2;
                  PlacesListInterface l3;
                  try {
                      l2 = (ObjectRegistryInterface) Naming.lookup("rmi://localhost:2023/registry");
                      String addr = l2.resolve("3510");
      
                      System.out.println("Invocar getPlace() no servidor de objetos...");
                      l3  = (PlacesListInterface) Naming.lookup(addr);
                      assertEquals("Viseu", l3.getPlace("3510").getLocality());
                  } catch (MalformedURLException | NotBoundException e) {
                      fail(e.getCause());
                  }
      
              } catch(Exception e) { fail("Problemas de Comunicação\n" + e.getMessage()); }
      
  8. Apr 2021
  9. Nov 2020
    1. botão direito do rato sobre o project RMIClient->Build Path->Configure Build Path->[Projects]->Add
  10. Feb 2020
  11. ec2-18-220-227-92.us-east-2.compute.amazonaws.com ec2-18-220-227-92.us-east-2.compute.amazonaws.com
    1. Exercício
          @DisplayName("Test if the exception is thrown for not existing services")
          @Test
          void testServiceNotFoundExceptionThrown() {
              req= new APIRequest();
              assertThrows(ServiceNotFoundException.class,
                      ()->{
                              req.getContent("abc", "12");
                      });
          }
      
          @DisplayName("Test if the request returns null for not existing content")
          @Test
          void testRequestReturnsNull() throws ServiceNotFoundException {
              req= new APIRequest();
              String idService = req.addService(new APIMoodle());
              assertNull(req.getContent(idService, "12"));
          }
      
          @DisplayName("Test if the request returns the content previously added")
          @Test
          void testContentPreviouslyAdded() throws ServiceNotFoundException {
              req= new APIRequest();
              String idService = req.addService(new APIMoodle());
              String idContent = req.setContent(idService, "12");
              assertEquals(req.getContent(idService,idContent),"12");
          }
      
          @DisplayName("Test if the aggregated content of one service is returned correctly")
          @Test
          void testAggregatedContent() throws ServiceNotFoundException {
              req= new APIRequestContentAggregator();
              String idService = req.addService(new APIMoodle());
              req.setContent(idService, "Eu vou");
              req.setContent(idService, " a Viseu");
              req.setContent(idService, " estudar");
              assertEquals(req.getContent(idService,"0"),"Eu vou a Viseu estudar");
          }
      
  12. Dec 2019
    1. inimum frequencyand minimum cluster size are two parameters that significantly af-fect mining of navigation patterns

      cluster parameters

    2. Depth-first search (DFS) is an algorithmfor traversing or searching a graph. Starting from a vertexa, DFS in-duced byMis applied to search for the connected componentreachable from this vertex. Once the component has been found,the algorithm checks if there are any nodes that are not consideredin the visit.

      algorithm for traversing the graph

    3. In WebPUMTime ConnectivityandFrequencyare two strongindicators of the degree of connectivity for each pair of Web pages.

      Time Connectivity and frequency to measure relation between pages

    4. he clusteringmodel is build to find collection of related pages at a particularWeb site, relying on the visit-coherence assumption (Perkowitz &Etzioni, 2000a). The pages that a user visits during one interactionwith the site tend to be conceptually related.

      consider full pages without states?

    5. navigation pattern min-ing is performed on the derived user access sessions. The represen-tative user navigation pattern can be obtained by clusteringalgorithms

      clustering algorithms

    1. when it comes to your web browsing experience, it turns out that latency, not bandwidth, is likely the constraining factor today.
    2. Figure 1-1. In this data from StatCounter Global Stats, we can see that the total percentage of Internet traffic coming from mobile devices is steadily increasing.
    3. 75% of online shoppers who experience an issue such as a site freezing, crashing, taking too long to load, or having a convoluted checkout process will not buy from that site. Gomez studied online shopper behavior and found that 88% of online consumers are less likely to return to a site after a bad experience. The same study found that “at peak traffic times, more than 75% of online consumers left for a competitor’s site rather than suffer delays.”
    4. users expect pages to load in two seconds, and after three seconds, up to 40% of users will abandon your site. Moreover, 85% of mobile users expect sites to load at least as fast or faster than sites on their desktop.
    5. components of its user experience: layout, hierarchy, intuitiveness, ease of use, and more.
  13. Nov 2019
    1. UUID uuid = UUID.randomUUID();

      criação de um identificador UUID

    1. So what can we do? }Alternative? Synchronous models? BUT REAL, PRACTICAL SYSTEMS ARE NOT SYNCHRONUS !!! }Use randomization, probabilistic guarantees }Process groups: sacrifice liveness under the assumption that retransmissions will eventually be received from good participants, the protocol eventually terminates }Avoid consensus, use quorum systems

      resolução do problema de consenso em sistemas distribuídos assíncronos

    2. }Agreement: all non-faulty processes decide on the same value }Validity: if a process decides on a value, then there was a process that started with that value }Termination: A non-faulty process decides in a finite time

      propriedades de um algoritmo de consenso

    3. In an asynchronous system, a process pi cannot tell whether a non-responsive process pj has crashed or it is just slow

      o problema de consenso em sistemas assíncronos

    1. Technically, solving the asynchronous distributed consensus problem in bounded time is impossible. As proven by the Dijkstra Prize–winning FLP impossibility result [Fis85], no asynchronous distributed consensus algorithm can guarantee progress in the presence of an unreliable network.

      o problema de consenso em sistemas distribuídos assíncronos é impossível de resolver

    2. Distributed consensus algorithms may be crash-fail (which assumes that crashed nodes never return to the system) or crash-recover. Crash-recover algorithms are much more useful, because most problems in real systems are transient in nature due to a slow network, restarts, and so on. Algorithms may deal with Byzantine or non-Byzantine failures. Byzantine failure occurs when a process passes incorrect messages due to a bug or malicious activity, and are comparatively costly to handle, and less often encountered.

      modelos de falha considerados

    3. asynchronous distributed consensus, which applies to environments with potentially unbounded delays in message passing

      interesse apenas em sistemas assíncronos

    4. Network partitions are particularly challenging—a problem that appears to be caused by a full partition may instead be the result of: A very slow network Some, but not all, messages being dropped Throttle occurring in one direction, but not the other direction

      Porque é que as partições de rede criam condições de falha difíceis de diagnosticar

    5. The logic is intuitive: if two nodes can’t communicate (because the network is partitioned), then the system as a whole can either stop serving some or all requests at some or all nodes (thus reducing availability), or it can serve requests as usual, which results in inconsistent views of the data at each node.

      Resume a lógica do teorema CAP

    6. CAP Theorem

      Descreve propriedades fundamentais de um sistema distribuído.

    7. Which process is the leader of a group of processes? What is the set of processes in a group?

      questões importantes na gestão do grupo

    8. we find developers spend a significant fraction of their time building extremely complex and error-prone mechanisms to cope with eventual consistency and handle data that may be out of date. We think this is an unacceptable burden to place on developers and that consistency problems should be solved at the database level.

      A complexidade da eventual consistency pode inviabilizar a sua adoção

    9. Systems and software engineers are usually familiar with the traditional ACID datastore semantics (Atomicity, Consistency, Isolation, and Durability), but a growing number of distributed datastore technologies provide a different set of semantics known as BASE (Basically Available, Soft state, and Eventual consistency). Datastores that support BASE semantics have useful applications for certain kinds of data and can handle large volumes of data and transactions that would be much more costly, and perhaps altogether infeasible, with datastores that support ACID semantics.

      semânticas ACID e BASE

  14. Oct 2019
    1. Teste este serviço
      //...
      
      PlacesListInterface l1 = null;
      
               try{
                  System.out.println("Localizar servidor de Objetos...");         
                l1  = (PlacesListInterface) Naming.lookup("rmi://localhost:2022/placelist");
      
                  Place p = new Place("3510", "Viseu");
                  System.out.println("Invocar addPlace() ...");
                  l1.addPlace(p);
      
                  System.out.println("Obter o endereço do servidor no Registry() ...");
                  ObjectRegistryInterface l2;
                  PlacesListInterface l3;
                  try {
                      l2 = (ObjectRegistryInterface) Naming.lookup("rmi://localhost:2023/registry");
                      String addr = l2.resolve("3510");
      
                      System.out.println("Invocar getPlace() no servidor de objetos...");
                      l3  = (PlacesListInterface) Naming.lookup(addr);
                      System.out.println(l3.getPlace("3510").getLocality()));
                  } catch (MalformedURLException | NotBoundException e) {
                      e.printStackTrace();
                  }
      
              } catch(Exception e) { e.printStackTrace(); }
      
  15. Apr 2019
    1. - implemente as classes.

      AdicionaEncomenda

       Utilizador u = new Utilizador("Manuel","Ativo");
              PropostaAquisicao propostaAquisicao = new PropostaAquisicao(LocalDate.now(),u, "Alice no Pais das Maravilhas");
              Livro l = new Livro("Programar em Java", "FCA");
              RequisicaoCompraCopia requisicaoCompraCopia = new RequisicaoCompraCopia("pendente", LocalDate.now(), "Oficio",l,u);
              Encomenda encomenda = new Encomenda(LocalDate.now(),requisicaoCompraCopia);
              repo.adicionaEncomenda(encomenda);
      

      EntradaNovoLivro

      Utilizador u = new Utilizador("Manuel","Ativo");
              PropostaAquisicao propostaAquisicao = new PropostaAquisicao(LocalDate.now(),u,"Alice no Pais das Maravilhas");
              Livro l = new Livro("Programar em Java", "FCA");
              Copia c = new Copia(1, l);
              RequisicaoCompraCopia requisicaoCompraCopia = new RequisicaoCompraCopia("pendente", LocalDate.now(), "Oficio",l,u);
              Encomenda encomenda = new Encomenda(LocalDate.now(),requisicaoCompraCopia);
              EntradaNovoLivro entradaNovoLivro = new EntradaNovoLivro(LocalDate.now(),encomenda,c);
              repo.adicionaEntradaNovoLivro(entradaNovoLivro);
      
  16. Mar 2019
    1. construtor da classe Singleton() é privado

      //devolve true se o construtor for Public Modifier.isPublic(Registry.class.getDeclaredConstructor().getModifiers()

    1. Aplique o padrão Bridge a um componente

      Testar APIRequest

      APIRequest req= new APIRequest();
      String idService = req.addService(new APIMoodle());
      String idContent = req.setContent(idService, "12");
              System.out.println(req.getContent(idService,idContent));
      

      Testar APIRequestContentAggregator

      APIRequestContentAggregator req= new APIRequestContentAggregator();
      String idService = req.addService(new APIMoodle());
      req.setContent(idService, "Eu vou");
      req.setContent(idService, " a Viseu");
      req.setContent(idService, " estudar");
      System.out.println(req.getContent(idService,"0"));
      
  17. Feb 2019
    1. Aplique o padrão Composite

      Código para testar o padrão com um menu de 3 níveis

      SubMenu m = new SubMenu();
      m.setLabel("Inserir");
      
      SubMenu client = new SubMenu();
      client.setLabel("Cliente");
      m.addChild(client);
      
      Link enterprise = new Link();
      enterprise.setLabel("Empresarial");
      
      enterprise.setURL("http://www.abc.pt/empresarial");
      client.addChild(enterprise);
      
      SubMenu particular = new SubMenu();
      particular.setLabel("Particular");
      client.addChild(particular);
      
      Link withVat = new Link();
      withVat.setLabel("Particular com contribuinte");
      withVat.setURL("http://www.abc.pt/pcc");
      particular.addChild(withVat);
      
      m.showOptions();
      
  18. Oct 2018
    1. Submeta os projetos
      static Thread t1;
      
      t1 = (new Thread() {
                  public void run(){
                      RMIRegistry.main(new String[0]);
                      RMIReplicaManager.main(new String[0]);              
                      RMIServer.main(new String[]{"2028"});
                      RMIServer.main(new String[]{"2030"});
                      RMIServer.main(new String[]{"2029"});
                  }});
              t1.start();
      
              Thread.sleep(1000);
      
          PlacesListManagerInterface plm;
          PlacesListManagerInterface plmret;
          PlacesListInterface pli;
          ObjectRegistryInterface ori;
      
      
          try{
              System.out.println("SE DER ERROS DE CONCORRÊNCIA, É NECESSÁRIO TENTAR OUTRA VEZ!!!");
              System.out.println("Localizar ReplicaManager...");
              plm  = (PlacesListManagerInterface) Naming.lookup("rmi://localhost:2024/replicamanager");
              Thread.sleep(1000);
              Place p1 = new Place("3510", "Viseu");
              System.out.println("Invocar addPlace() no ReplicaManager para 3510...");
              plm.addPlace(p1);
      
              Place p2 = new Place("1000", "Lisboa");
              System.out.println("Invocar addPlace() no ReplicaManager para 1000...");
              plm.addPlace(p2);
      
              Place p3 = new Place("4000", "Lisboa");
              System.out.println("Invocar addPlace() no ReplicaManager para 4000...");
              plm.addPlace(p3);
      
              System.out.println("Obter o endereço do ReplicaManager no Registry() para o ObjectID 1000 ...");
              ori = (ObjectRegistryInterface) Naming.lookup("rmi://localhost:2023/registry");
              String addrRM = ori.resolve("1000");
      
              System.out.println("Destruir uma das réplicas ...");
              LocateRegistry.getRegistry(2029).unbind("placelist");
              Thread.sleep(2000);
      
      
              System.out.println("Pedir ao ReplicaManager para devolver um PlaceManager para o ObjectID 1000 ...");
              plm = (PlacesListManagerInterface) Naming.lookup(addrRM);
              boolean pl1done = false;
              boolean pl2done = false;
              boolean pl3done = false;
              String plAddress = null;
              for(int i=0; i<10 ; i++) {
                  plAddress = plm.getPlaceListAddress("1000");
                  invokeGetPlacePlaceManager(plAddress);
                  System.out.println("\tPara o Endereço " + plAddress);
                  if(plAddress.equals("rmi://localhost:2028/placelist")) pl1done=true;
                  else if(plAddress.equals("rmi://localhost:2029/placelist")) pl2done=true;
                       else if(plAddress.equals("rmi://localhost:2030/placelist")) pl3done=true;
              } 
      
              if(!(pl1done==pl2done==pl3done==true)) fail("Não está a devolver um PlaceManager aleatório...");
      
          } catch(Exception e) {
              e.printStackTrace();
              fail("Erro\n" + e.getMessage()); }
      }
      
      private void invokeGetPlacePlaceManager(String plAddress)
              throws NotBoundException, MalformedURLException, RemoteException {
          PlacesListInterface pli;
          System.out.println("Invocar getPlace() no PlaceManager");
          pli  = (PlacesListInterface) Naming.lookup(plAddress);
          String locality = pli.getPlace("1000").getLocality();
      
          System.out.println("\tDevolveu " + locality);
          assertEquals("Lisboa", locality);
      }
      
    1. validação
              t = (new Thread() {
                  public void run() {
                      RMIRegistry.main(new String[0]);
                      RMIReplicaManager.main(new String[0]);
                      RMIServer.main(new String[]{"2028"});
                      RMIServer.main(new String[]{"2029"});
                      RMIServer.main(new String[]{"2030"});
                      }
                      });
              t.start();
      
              Thread.sleep(1000);
      
          PlacesListManagerInterface plm;
          PlacesListManagerInterface plmret;
          PlacesListInterface pli;
          ObjectRegistryInterface ori;
      
      
          try{
              System.out.println("Localizar ReplicaManager...");
              plm  = (PlacesListManagerInterface) Naming.lookup("rmi://localhost:2024/replicamanager");
      
              Place p1 = new Place("3510", "Viseu");
              System.out.println("Invocar addPlace() no ReplicaManager para 3510...");
              plm.addPlace(p1);
      
              Place p2 = new Place("1000", "Lisboa");
              System.out.println("Invocar addPlace() no ReplicaManager para 1000...");
              plm.addPlace(p2);
      
              Place p3 = new Place("4000", "Lisboa");
              System.out.println("Invocar addPlace() no ReplicaManager para 4000...");
              plm.addPlace(p3);
      
              System.out.println("Obter o endereço do ReplicaManager no Registry() para o ObjectID 1000 ...");
              ori = (ObjectRegistryInterface) Naming.lookup("rmi://localhost:2023/registry");
              String addrRM = ori.resolve("1000");
      
              System.out.println("Pedir ao ReplicaManager para devolver um PlaceManager para o ObjectID 1000 ...");
              plm = (PlacesListManagerInterface) Naming.lookup(addrRM);
              boolean pl1done = false;
              boolean pl2done = false;
              boolean pl3done = false;
              String plAddress = null;
              for(int i=0; i<10 ; i++) {
                  plAddress = plm.getPlaceListAddress("1000");
                  System.out.println("\tDevolveu " + plAddress);
                  if(plAddress.equals("rmi://localhost:2028/placelist")) pl1done=true;
                  else if(plAddress.equals("rmi://localhost:2029/placelist")) pl2done=true;
                       else if(plAddress.equals("rmi://localhost:2030/placelist")) pl3done=true;
              } 
      
              if(!(pl1done==pl2done==pl3done==true)) fail("Não está a devolver um PlaceManager aleatório...");        
      
              System.out.println("Invocar getPlace() no PlaceManager");
              pli  = (PlacesListInterface) Naming.lookup(plAddress);
              String locality = pli.getPlace("1000").getLocality();
      
              System.out.println("\tDevolveu " + locality);
              assertEquals("Lisboa", locality);
      
      
          } catch(Exception e) { }
      }
      
  19. Sep 2018
    1. <xs:element ref="grupo"/>

      se for necessário incluir um grupo dentro de outro

    2. Crie o Schema
    3. maxOccurs="unbounded"

      não existe limite máximo para a escolha

    4. minOccurs="1"

      obriga a fazer pelo menos uma escolha

    1. mixed="true"

      O conteúdo do elemento email pode ter texto com elementos misturados dentro do mesmo, tal como aparece no XML anterior.

    1. xsd:element name="Product"

      Como o Product tem outros elementos dentro dele, não vai ter um atributo type="....". Em vez disso, contém um complexType que define os elementos interiores do Product.

    2. xsi:noNamespaceSchemaLocation="Produto.xsd"

      Indica que este ficheiro XML é validado pelo ficheiro Produto.xsd

    3. xsd:attribute name="ProductID"

      Um atributo é sempre declarado dentro do complexType, mas fora da sequência

    4. o elemento sequence

      Apesar de ter outras alternativas, o elemento sequence aparece quase sempre dentro do complexType. Dentro desta sequence estão os elementos interiores do Product.

    1. <N>,<Mensagem enviada pelo cliente>

      Split da String

      String stringComVirgulas="1,xxxx";

      stringComVirgulas.split(",")[0] -- Devolve "1" stringComVirgulas.split(",")[1] -- Devolve "0"

    2. aSocket.receive(request);

      o servidor bloqueia aqui à espera de um pedido do cliente

    3. new String(reply.getData())

      conversão do array de bytes enviado pelo servidor para String, de forma a que possa ser visualizado na consola

    4. aSocket.receive(reply);

      o cliente bloqueia aqui à espera da resposta do servidor

    5. new DatagramPacket(buffer, buffer.length)

      criação do datagrama que vai receber os dados do servidor

    6. byte[] buffer = new byte[1000];

      criação de um buffer para colocar a resposta do servidor

    7. aSocket.send(request);

      envio do datagrama através do socket

    8. DatagramPacket(m,  m.length, aHost, serverPort)

      datagrama com a mensagem a enviar para o servidor

    9. 6789

      porto do servidor

    10. InetAddress.getByName("localhost")

      objeto que representa o endereço do servidor para onde vamos enviar a mensagem

    11. getBytes()

      a mensagem tem de ser convertida para array de bytes antes de ser enviada

    12. DatagramSocket()

      criação do socket de comunicação

    13. erros de checksum

      checksums errados dão origem a mensagens descartadas

    14. checksums
    1. pe

      prefixo que representa o nome do namespace

    2. http://www.ipv.pt/documentos/pessoa

      nome do namespace

    3. documento

      elemento raiz