Exemplo n.º 1
1
  public Vector obterLinhas(String nome, String status) {
    Vector linhas = new Vector();
    try {
      if (status.equals("Ativo")) {
        usuariosAtivos = usuarioDao.obterUsuarios(nome, status);
        for (int i = 0; i < usuariosAtivos.size(); i++) {
          Usuario usuario = usuariosAtivos.get(i);
          linhas.addElement(this.criarLinhaUsuario(usuario));
        }
      } else {
        usuariosInativos = usuarioDao.obterUsuarios(nome, status);
        for (int i = 0; i < usuariosInativos.size(); i++) {
          Usuario usuario = usuariosInativos.get(i);
          linhas.addElement(this.criarLinhaUsuario(usuario));
        }
      }
    } catch (SQLException ex) {
      ex.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "Erro ao acesso o banco de dados,\n" + "por favor contate o Suporte",
          "Erro",
          JOptionPane.ERROR_MESSAGE);
    }

    return linhas;
  }
Exemplo n.º 2
1
 protected void resolve() {
   boolean consistent = true;
   for (int i = 0; i < queue.size() && i < 10; i++) {
     ccr.app.Context ctx = (ccr.app.Context) queue.get(i);
     if (filterLocCons2Stay(ctx, candidate) && !funcLocDistOk(ctx, candidate)) {
       consistent = false;
       break;
     }
     if (filterLocCons2Walk(ctx, candidate) && !funcLocWalkAdjVeloOk(ctx, candidate)) {
       consistent = false;
       break;
     }
     if (filterLocSkip1Stay(ctx, candidate) && !funcLocDistOk(ctx, candidate)) {
       consistent = false;
       break;
     }
     if (filterLocSkip1Walk(ctx, candidate) && !funcLocWalkSkipVeloOk(ctx, candidate)) {
       consistent = false;
       break;
     }
     if (filterLocSkip1Mix(ctx, candidate) && !funcLocMixVeloOk(ctx, candidate)) {
       consistent = false;
       break;
     }
   }
   if (consistent) {
     queue.add(0, candidate);
   } else {
     candidate = (ccr.app.Context) queue.get(0);
   }
 }
Exemplo n.º 3
1
        public void handle(PeerMessage event) {
          PeerAddress oldFriend;
          PeerAddress sender = event.getMSPeerSource();
          PeerAddress newFriend = event.getNewFriend();

          // add the sender address to the list of friends
          if (!friends.contains(sender)) {
            if (friends.size() == viewSize) {
              oldFriend = friends.get(rand.nextInt(viewSize));
              friends.remove(oldFriend);
              fdUnregister(oldFriend);
              Snapshot.removeFriend(serverPeerAddress, oldFriend);
            }

            friends.addElement(sender);
            fdRegister(sender);
            Snapshot.addFriend(serverPeerAddress, sender);
          }

          // add the received new friend from the sender to the list of friends
          if (!friends.contains(newFriend) && !serverPeerAddress.equals(newFriend)) {
            if (friends.size() == viewSize) {
              oldFriend = friends.get(rand.nextInt(viewSize));
              friends.remove(oldFriend);
              fdUnregister(oldFriend);
              Snapshot.removeFriend(serverPeerAddress, oldFriend);
            }

            friends.addElement(newFriend);
            fdRegister(newFriend);
            Snapshot.addFriend(serverPeerAddress, newFriend);
          }
        }
Exemplo n.º 4
1
 public static String list(Context c, Vector<BaseObject> objs) {
   String ret = new String();
   if (objs.size() == 0) return ret;
   if (objs.size() == 1) {
     ret = objs.firstElement().getName();
     return ret;
   }
   if (objs.size() == 2) {
     ret =
         objs.get(0).getName()
             + " "
             + c.getString(R.string.stringhandler_and1)
             + " "
             + objs.get(1).getName();
     return ret;
   }
   for (int i = 0; i < objs.size() - 1; i++) {
     ret += objs.get(i).getName();
     if (i < objs.size() - 2) {
       ret += c.getString(R.string.stringhandler_comma);
       ret += " ";
     } else {
       ret += c.getString(R.string.stringhandler_and2);
       ret += " ";
     }
   }
   ret += objs.lastElement().getName();
   return ret;
 }
Exemplo n.º 5
1
  private static void replace(Tree code, String data, Tree replacement) {
    System.out.println("Trying to replace" + data + " with " + replacement + " in " + code);
    if (code.getData().equals(data)) {
      System.out.println("Replacing " + data + " with " + replacement);
      code.removeChildren(false);
      for (Tree t : replacement.getChildren()) {
        code.addChild(new Tree(t), false);
      }
      code.setData(replacement.getData());
    } else if (code.getData().equals(FUN)) {
      // Shadowing
      Vector<Tree> fn = code.getChildren();
      Vector<Tree> args = fn.get(0).getChildren();

      for (Tree t : args) {
        if (t.getData().equals(data)) {
          return;
        }
      }

      // If we made it here, the replacement term is not in the args
      replace(fn.get(1), data, replacement);
    } else {
      for (Tree t : code.getChildren()) {
        replace(t, data, replacement);
      }
    }
  }
Exemplo n.º 6
0
  /** Sort all the painters (according to priority and name) */
  protected void sortThem() {
    sortByPriority.clear();
    sortByName.clear();

    sortByName.addAll(paintersByName.keySet());
    Collections.sort(sortByName);

    Vector<String> painterNames = new Vector<String>();
    Vector<Integer> priorities = new Vector<Integer>();

    painterNames.addAll(sortByName);
    priorities.addAll(painterPriorities.values());
    Collections.sort(priorities);

    while (!priorities.isEmpty()) {
      int prio = priorities.get(0);
      priorities.remove(0);

      for (int i = 0; i < painterNames.size(); i++) {
        if (painterPriorities.get(painterNames.get(i)) == prio) {
          sortByPriority.add(painterNames.get(i));
          painterNames.remove(i);
          break;
        }
      }
    }
  }
Exemplo n.º 7
0
  /**
   * Formats the data in the Game object as an HTML table.
   *
   * @return an HTML table displaying the game's data
   */
  public String toHTMLTable(DisplayMode eDisplayMode) {
    if (m_voPlayers == null) return "";

    StringBuffer sbValue = new StringBuffer();
    int azRunningTotals[] = new int[m_voPlayers.size()];

    sbValue.append("<table style=\"border:none;margin-left:auto;margin-right:auto;\">\n");
    sbValue.append(" <tr>\n");
    sbValue.append("  <th style=\"border:none;background-color:#000000;\">&nbsp;</th>\n");
    for (int i = 0; i < m_voPlayers.size(); i++) {
      sbValue
          .append("  <th colspan=\"2\"")
          .append(
              " style=\"border:none;background-color:#000000;color:#ffffff;font-weight:bold;padding:2px 1em;text-align:center;\">")
          .append(m_voPlayers.get(i).getName())
          .append("</th>\n");
    }
    sbValue.append(" </tr>\n");

    if (m_voRounds != null) { // Draw all the game's rounds.
      for (int i = 0; i < m_voRounds.size(); i++) {
        sbValue.append(
            m_voRounds.get(i).toHTMLTableRow(this.isDoubleDeck(), eDisplayMode, azRunningTotals));
      }
    }

    this.appendFinalScoresToHTML(sbValue, azRunningTotals);

    sbValue.append("</table>\n");

    return sbValue.toString();
  }
 private int max(Vector<Integer> ids) {
   int max = 0;
   for (int i = 0; i < ids.size(); i++) {
     if (ids.get(i) > max) max = ids.get(i);
   }
   return max;
 }
  private void resetFocus(
      Vector<MenuVO> vecFirst, Vector<MenuVO> vecSecond, MenuVO focusFirst, MenuVO focusSecond) {
    if (vecFirst != null) {
      for (MenuVO mvo : vecFirst) {
        mvo.setFocus(false);
      }
    }
    if (vecSecond != null) {
      for (MenuVO mvo : vecSecond) {
        mvo.setFocus(false);
      }
    }

    if (focusFirst != null) {
      focusFirst.setFocus(true);
    } else if (vecFirst != null && vecFirst.get(0) != null) {
      vecFirst.get(0).setFocus(true);
    }

    if (focusSecond != null) {
      focusSecond.setFocus(true);
    } else if (vecSecond != null && vecSecond.get(0) != null) {
      vecSecond.get(0).setFocus(true);
    }
  }
Exemplo n.º 10
0
  private static String getMachinesFile(String dirName) {

    File modelDir = new File(dirName);
    String machinesFile = null;

    // Files in the directory
    String[] fileNames = modelDir.list();

    // If there is no file in the directory
    if (fileNames == null) {
      log.error("The model specified as \"gods.net.model.dir\"" + " is not a directory");

    } else {
      // Check for .machines files in the directory
      Vector<String> machineFiles = new Vector<String>();
      for (String s : fileNames) {
        if (s.endsWith(".machines")) {
          machineFiles.add(s);
        }
      }
      // Warn if more than one because only first will be considered.
      if (machineFiles.size() > 1) {
        log.warn(
            "There are more than one .machine file in "
                + dirName
                + ". Considering "
                + machineFiles.get(0)
                + " and ignoring others.");
      }

      machinesFile = machineFiles.get(0);
    }
    return machinesFile;
  }
Exemplo n.º 11
0
  /**
   * Statische Funktion die ein XML-Trefferdokument erzeugt
   *
   * @param feedDetails Vector der NewsItems-Objekte enthält
   * @param strWhichInputType Zeichenkette für den XML-Dateinamen
   * @throws JAXBException
   */
  public static void write_XML_File(Vector<NewsItems> feedDetails, String strWhichInputType)
      throws JAXBException {
    TrefferDokument trefferDokument = new TrefferDokument();

    for (int i = 0; i < feedDetails.size(); i++) {

      /*
       * Hier werden die Klassen benutzt, die mittels xjc erstellt
       * worden. gut nachzuvollziehen, wenn sich die assignment2.xsd
       * angeschaut wird.
       */
      TrefferType type = new TrefferType();
      ItemType item = new ItemType();

      item.setTitle(feedDetails.get(i).getTitle());
      item.setDescription(feedDetails.get(i).getDescription());

      type.getItem().add(item);
      trefferDokument.getTreffer().add(type);

      JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
      Marshaller m = jc.createMarshaller();
      /*
       * Output wird für eine gewohnte Lesbarkeit formatiert
       */
      m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

      m.marshal(trefferDokument, new File(strWhichInputType + ".xml"));
    }
  }
Exemplo n.º 12
0
  /**
   * Rule: A
   *
   * @param DefaultMutableTreeNode parent
   * @return String
   */
  private static String rule_a(DefaultMutableTreeNode parent) {
    Boolean operatorFlag = false;
    String type, type2 = "", typeOp = "";
    DefaultMutableTreeNode node;

    node = new DefaultMutableTreeNode("B");
    parent.add(node);
    addTokenToStack();
    type = rule_b(node);

    currentWord = tokens.get(currentToken).getWord();

    while (currentToken < tokens.size() && (currentWord.equals("*") || currentWord.equals("/"))) {
      node = new DefaultMutableTreeNode(currentWord);
      parent.add(node);
      addTokenToStack();
      typeOp = currentWord;
      currentToken++;

      node = new DefaultMutableTreeNode("B");
      parent.add(node);
      addTokenToStack();
      type2 = rule_b(node);

      currentWord = tokens.get(currentToken).getWord();

      operatorFlag = true;
    }

    if (operatorFlag) {
      SemanticAnalyzer.calculateCube(type, type2, typeOp);
    }

    return type;
  }
Exemplo n.º 13
0
  /**
   * Rule: Assignment
   *
   * @param DefaultMutableTreeNode parent
   * @return boolean
   */
  public static void rule_assignment(DefaultMutableTreeNode parent) {
    DefaultMutableTreeNode node;
    String type1, type2;

    // identifier

    type1 = tokens.get(currentToken).getWord();
    node = new DefaultMutableTreeNode("identifier" + "(" + type1 + ")");
    parent.add(node);
    addTokenToStack();
    currentToken++;

    // '='

    if (currentToken < tokens.size() && tokens.get(currentToken).getWord().equals("=")) {
      node = new DefaultMutableTreeNode("=");
      parent.add(node);
      addTokenToStack();
      currentToken++;
    } else {
      error(5); // expected =
      return;
    }

    // <expression>

    node = new DefaultMutableTreeNode("expression");
    parent.add(node);
    addTokenToStack();
    type2 = rule_expression(node);

    // check for type equivalence
    SemanticAnalyzer.calculateCube(type1, type2, "=");
  }
Exemplo n.º 14
0
  /**
   * Rule: Program
   *
   * @param DefaultMutableTreeNode parent
   * @return boolean
   */
  public static void rule_program(DefaultMutableTreeNode parent) {
    boolean error = false;
    DefaultMutableTreeNode node;

    // '{'

    if (currentToken < tokens.size() && tokens.get(currentToken).getWord().equals("{")) {
      node = new DefaultMutableTreeNode("{");
      parent.add(node);
      currentToken++;
    } else {
      error(1); // expected {
      return;
    }

    // <body>

    node = new DefaultMutableTreeNode("body");
    parent.add(node);
    rule_body(node);

    // '}'

    if (currentToken < tokens.size() && tokens.get(currentToken).getWord().equals("}")) {
      node = new DefaultMutableTreeNode("}");
      parent.add(node);
      currentToken++;
    } else {
      error(2); // expected }
    }
  }
Exemplo n.º 15
0
 /**
  * works out the total time taken.
  *
  * @return the elapsed time since the walk was started
  */
 public double getTimeTaken() {
   if (path.size() == 0) {
     return 0;
   } else {
     return path.get(path.size() - 1).getTime() - path.get(0).getTime();
   }
 }
Exemplo n.º 16
0
 /**
  * works out the total distance traveled along the walk.
  *
  * @return the running total of km traveled.
  */
 public double getDistance() {
   double total = 0;
   for (int i = 0; i < path.size() - 1; i++) {
     total += LocationPoint.distBetween(path.get(i), path.get(i + 1));
   }
   return total;
 }
Exemplo n.º 17
0
  /**
   * regarde si la case e est menace par le camp c
   *
   * @param c
   * @param e
   * @return liste de piece qui menace la case
   */
  public Vector<Case> estMenacePar(String camp, Case e) {
    Vector<Case> listePieceAdverse = new Vector<Case>();
    Vector<Case> listePieceMenacante = new Vector<Case>();

    if (camp.equals("noir")) {
      listePieceAdverse = listerPiecesNoires(this.listePieceEnJeu);

    } else if (camp.equals("blanc")) {
      listePieceAdverse = listerPiecesBlanches(this.listePieceEnJeu);
    } else { // TODO: creer une exception
    }
    for (int i = 0; i < listePieceAdverse.size(); i++) { // pour toutes les pieces adverses

      ArrayList<Case> deplacementPieceAdverse = filtreGeneral(listePieceAdverse.get(i));
      for (int j = 0;
          j < deplacementPieceAdverse.size();
          j++) { // pour tous les deplacements de chaque piece
        if (deplacementPieceAdverse
            .get(j)
            .getPosition()
            .equals(e.getPosition())) { // la case e est égale a la case que l'on veut tester
          listePieceMenacante.add(listePieceAdverse.get(i));
        }
      }
    }

    return listePieceMenacante;
  }
Exemplo n.º 18
0
  public static Vector filterDistinct(Vector tupels, String key) {
    Vector res = new Vector();
    key = key.toLowerCase();

    for (int i = 0; i < tupels.size(); i++) {
      DB_Tupel tupel = (DB_Tupel) tupels.get(i);
      Object o = tupel.get(key);

      if (o instanceof String) {
        String s = (String) o;
        boolean found = false;
        for (int j = 0; j < res.size(); j++) {
          String t = (String) res.get(j);
          if (s.equalsIgnoreCase(t)) {
            found = true;
            break;
          }
        }
        if (!found) res.add(s);
      } else {
        if (!res.contains(o)) res.add(o);
      }
    }

    return res;
  }
Exemplo n.º 19
0
  /**
   * Executa o c�lculo da fun��o
   *
   * @return valor do c�lculo
   * @param oper nome da fun��o
   * @param params parametros da fun��o
   * @throws java.lang.Exception erro
   */
  public String Calculate(String oper, Vector params) throws Exception {
    if (params.size() == 0) return Calculate0(oper);
    if (params.size() == 1) return Calculate1(oper, (String) params.get(0));
    if (params.size() == 2) return Calculate2(oper, (String) params.get(0), (String) params.get(1));

    throw new Exception("ERRO fun��o parametros errados [" + oper + "] " + params.toString());
  }
Exemplo n.º 20
0
  /**
   * Generate artificial training examples.
   *
   * @param artSize size of examples set to create
   * @param data training data
   * @return the set of unlabeled artificial examples
   */
  protected Instances generateArtificialData(int artSize, Instances data) {
    int numAttributes = data.numAttributes();
    Instances artData = new Instances(data, artSize);
    double[] att;
    Instance artInstance;

    for (int i = 0; i < artSize; i++) {
      att = new double[numAttributes];
      for (int j = 0; j < numAttributes; j++) {
        if (data.attribute(j).isNominal()) {
          // Select nominal value based on the frequency of occurence in the training data
          double[] stats = (double[]) m_AttributeStats.get(j);
          att[j] = (double) selectIndexProbabilistically(stats);
        } else if (data.attribute(j).isNumeric()) {
          // Generate numeric value from the Guassian distribution
          // defined by the mean and std dev of the attribute
          double[] stats = (double[]) m_AttributeStats.get(j);
          att[j] = (m_Random.nextGaussian() * stats[1]) + stats[0];
        } else System.err.println("Decorate can only handle numeric and nominal values.");
      }
      artInstance = new Instance(1.0, att);
      artData.add(artInstance);
    }
    return artData;
  }
Exemplo n.º 21
0
 // keyboard discovery code
 private void _mapKey(char charCode, int keyindex, boolean shift, boolean altgraph) {
   log("_mapKey: " + charCode);
   // if character is not in map, add it
   if (!charMap.containsKey(new Integer(charCode))) {
     log("Notified: " + (char) charCode);
     KeyEvent event =
         new KeyEvent(
             applet(),
             0,
             0,
             (shift ? KeyEvent.SHIFT_MASK : 0) + (altgraph ? KeyEvent.ALT_GRAPH_MASK : 0),
             ((Integer) vkKeys.get(keyindex)).intValue(),
             (char) charCode);
     charMap.put(new Integer(charCode), event);
     log("Mapped char " + (char) charCode + " to KeyEvent " + event);
     if (((char) charCode) >= 'a' && ((char) charCode) <= 'z') {
       // put shifted version of a-z in automatically
       int uppercharCode = (int) Character.toUpperCase((char) charCode);
       event =
           new KeyEvent(
               applet(),
               0,
               0,
               KeyEvent.SHIFT_MASK + (altgraph ? KeyEvent.ALT_GRAPH_MASK : 0),
               ((Integer) vkKeys.get(keyindex)).intValue(),
               (char) uppercharCode);
       charMap.put(new Integer(uppercharCode), event);
       log("Mapped char " + (char) uppercharCode + " to KeyEvent " + event);
     }
   }
 }
Exemplo n.º 22
0
 public void resolveJoinToken(Integer tokenPosition, Object value) {
   values[index] = value;
   if (index == 0 && timeout > 0) {
     ServiceFactory.getTransport().timeoutSend(timeout, self);
   }
   // System.out.println("JD:::"+ getUAL() +" input="+index+"/"+requiredTokens);
   index++;
   if (requiredTokens == index) {
     for (int i = 0; i < targetActors.size(); i++) {
       ActorReference target = (ActorReference) targetActors.get(i);
       String messageId = (String) targetMessages.get(i);
       Integer position = (Integer) targetPositions.get(i);
       Object[] arguments = new Object[3];
       arguments[0] = messageId;
       arguments[1] = position;
       if (position.intValue() == -3) arguments[2] = null;
       else arguments[2] = values;
       Message data =
           new Message(
               ((JoinDirector) self), target, "resolveToken", arguments, null, null, false);
       target.send(data);
     }
     this.ServiceDie();
   }
 }
 private String selectSessionVarsByState(
     String sig, String entry, String targetState, String inputParas) {
   String sessionVars = "null";
   // String sessionVars = "";
   boolean found = false;
   Vector<String> sessionVarsList = new Vector<String>();
   if (!sessionVarsSet.containsKey(targetState)) {
     // System.out.println("Warning: no session vars are selected for: " + targetState);
     return sessionVars; // no desired states are available.
   }
   for (String sv : sessionVarsSet.get(targetState)) {
     sessionVarsList.add(sv);
   }
   for (int i = 0; i < sessionVarsList.size(); i++) {
     if (!checkEqualityConstViolated(
         sig,
         entry,
         inputParas,
         sessionVarsList.get(i))) { // check if equality constraint violated.
       sessionVars = sessionVarsList.get(i);
       found = true;
       break;
     }
   }
   // if (!found) System.out.println("Warning: don't find the desired session variables.");
   return sessionVars;
 }
Exemplo n.º 24
0
    public boolean timeoutMsg() {
      for (int i = 0; i < targetActors.size(); i++) {
        ActorReference target = (ActorReference) targetActors.get(i);
        String messageId = (String) targetMessages.get(i);
        Integer position = (Integer) targetPositions.get(i);

        /**
         * If the value is a large object, it isn't required to be sent if this token is being used
         * for synchronization. We can send null instead.
         */
        Object[] arguments = new Object[3];
        arguments[0] = messageId;
        arguments[1] = position;
        Object[] ret = new Object[index];
        System.arraycopy(values, 0, ret, 0, index);
        if (position.intValue() == -3) arguments[2] = null;
        else arguments[2] = ret;
        Message data =
            new Message(
                ((JoinDirector) self), target, "resolveToken", arguments, null, null, false);
        target.send(data);
      }
      this.ServiceDie();
      return true;
    }
 private boolean find(Vector<Integer> ids) {
   int first = ids.get(0);
   for (int i = 1; i < ids.size(); i++) {
     if (ids.get(i) != first) return false;
   }
   return true;
 }
  public void testGetBulletinChunkTypo() throws Exception {
    final String authorAccountId = "a";
    final String bulletinLocalId = "b";
    final int offset = 123;
    final int maxChunkSize = 456;

    supplier.returnResultTag = NetworkInterfaceConstants.CHUNK_OK;
    supplier.authorizedCaller = callerAccountId;
    String returnZipData = StreamableBase64.encode("zip data");
    UniversalId uid = UniversalId.createFromAccountAndLocalId(authorAccountId, bulletinLocalId);
    supplier.addZipData(uid, returnZipData);

    Vector parameters = new Vector();
    parameters.add(MirroringInterface.CMD_MIRRORING_GET_BULLETIN_CHUNK_TYPO);
    parameters.add(authorAccountId);
    parameters.add(bulletinLocalId);
    parameters.add(new Integer(offset));
    parameters.add(new Integer(maxChunkSize));
    String sig = callerSecurity.createSignatureOfVectorOfStrings(parameters);
    Vector result = handler.request(callerAccountId, parameters, sig);

    assertEquals(authorAccountId, supplier.gotAccount);
    assertEquals(bulletinLocalId, supplier.gotLocalId);
    assertEquals(offset, supplier.gotChunkOffset);
    assertEquals(maxChunkSize, supplier.gotMaxChunkSize);

    assertEquals(2, result.size());
    assertEquals(NetworkInterfaceConstants.CHUNK_OK, result.get(0));
    Object[] details = (Object[]) result.get(1);
    assertEquals(new Integer(supplier.getChunkSize(uid) * 3), details[0]);
    assertEquals(new Integer(supplier.getChunkSize(uid)), details[1]);
    assertEquals(returnZipData, details[2]);
  }
Exemplo n.º 27
0
 private static int compareName(Vector source, Vector target) {
   Collator collator = Collator.getInstance(new Locale("vi", "VN"));
   int totalS = source.size() - 1;
   int totalT = target.size() - 1;
   String nameS = "";
   String nameT = "";
   int compare = 0;
   for (int s = totalS, t = totalT; (s > -1) && (t > -1); s--, t--) {
     nameS = (String) source.get(s);
     nameT = (String) target.get(t);
     compare = collator.compare(nameS, nameT);
     // compare = nameS.compareTo(nameT);
     if (compare > 0) {
       return 1;
     } else if (compare < 0) {
       return -1;
     } else {
       continue;
     }
   }
   if (totalS > totalT) {
     return 1;
   } else if (totalS < totalT) {
     return -1;
   } else {
     return 0;
   }
 }
Exemplo n.º 28
0
  public void testNodeManipulations() {
    NodeDAO nodeDao = (NodeDAO) context.getBean("nodeDAO");
    NodeImage image = getTestImage();
    Node life = (Node) nodeDao.findNodesExactlyNamed("Life on Earth").get(0);
    Node viruses = (Node) nodeDao.findNodesExactlyNamed("Viruses").get(0);
    Node eukaryotes = (Node) nodeDao.findNodesExactlyNamed("Eukaryotes").get(0);

    image.addToNodesSet(life);
    dao.saveImage(image);
    NodeImage foundImage = dao.getImageWithId(image.getId());
    assertTrue(foundImage.getNodesSet().size() == 1);
    Node firstNode = (Node) new Vector(foundImage.getNodesSet()).get(0);
    assertEquals(firstNode.getId(), life.getId());
    image.addToNodesSet(viruses);
    dao.saveImage(image);
    foundImage = dao.getImageWithId(image.getId());
    assertTrue(foundImage.getNodesSet().size() == 2);
    Vector nodes = new Vector(foundImage.getNodesSet());
    firstNode = (Node) nodes.get(0);
    Node secondNode = (Node) nodes.get(1);
    assertTrue(firstNode.getId() == life.getId() || firstNode.getId() == viruses.getId());
    assertTrue(secondNode.getId() == life.getId() || secondNode.getId() == viruses.getId());

    image.removeFromNodesSet(life);
    image.removeFromNodesSet(viruses);
    image.addToNodesSet(eukaryotes);
    dao.saveImage(image);
    foundImage = dao.getImageWithId(image.getId());
    assertTrue(foundImage.getNodesSet().size() == 1);
    nodes = new Vector(foundImage.getNodesSet());
    firstNode = (Node) nodes.get(0);
    assertTrue(firstNode.getId() == eukaryotes.getId());
    dao.deleteImage(image);
  }
 /*
  * (non-Javadoc)
  *
  * @see pt.lsts.neptus.util.comm.manager.CommonCommBaseImplementation#triggerExtraActionOnSetActive(boolean,
  * pt.lsts.neptus.messages.listener.MessageInfo, pt.lsts.neptus.messages.IMessage)
  */
 @Override
 protected void triggerExtraActionOnSetActive(
     boolean isActive, MessageInfo info, IMCMessage message) {
   ImcSystem sys = ImcSystemsHolder.lookupSystem(getSystemCommId());
   if (sys != null) {
     if (message == null
         || !StringUtils.isTokenInList("Announce,EntityList", message.getAbbrev())) {
       if (!useActivityCounter) {
         sys.setActive(isActive);
         // NeptusLog.pub().info("<###> "+sys.getName()+": "+isActive()+"  "+(message !=
         // null?message.getAbbrevName():""));
       } else {
         // If IMCAuthorityState.OFF then we consider not active
         if (sys.getAuthorityState() == ImcSystem.IMCAuthorityState.OFF) {
           sys.setActive(false);
         } else if (!isActive) {
           sys.setActive(false);
         } else {
           activityCounter.add(System.currentTimeMillis());
           int vecSize = activityCounter.size();
           if (vecSize > 3) {
             activityCounter.remove(0);
           }
           vecSize = activityCounter.size();
           if (vecSize == 3) {
             if (activityCounter.get(2) - activityCounter.get(0) <= 3000) sys.setActive(true);
             else sys.setActive(false);
           } else {
             sys.setActive(false);
           }
         }
       }
     }
   }
 }
Exemplo n.º 30
0
 public String getName(String str, boolean isSuccess) {
   String result = "";
   String sPersons[] = str.split(",");
   for (int i = 0; i < sPersons.length; i++) {
     for (int j = 0; j < checkedPersons.size(); j++) {
       if (sPersons[i].equals(checkedPersons.get(j).phone)) {
         String name = checkedPersons.get(j).name;
         if (name == null) {
           name = "";
         }
         result += name;
         for (int n = 0; n < 7 - name.length(); n++) {
           result += "---";
         }
         result += checkedPersons.get(j).phone + "\n";
         if (isSuccess) {
           successPersons.add(checkedPersons.get(j).phone);
         }
         break;
       } else if (j == checkedPersons.size() - 1) {
         for (int n = 0; n < 7; n++) {
           result += "---";
         }
         result += sPersons[i] + "\n";
         if (isSuccess) {
           successPersons.add(sPersons[i]);
         }
       }
     }
   }
   return result;
 }