Exemplo n.º 1
0
  /**
   * Helper function: update the "old" RM group with the "next" group provided.
   *
   * @param old
   * @param next
   */
  private void updateRMGroup(LinkedList<MemberInfo> old, LinkedList<MemberInfo> next) {
    if (next == null || next.isEmpty()) {
      System.out.println("empty or null next MemberInfo sent in updated.");
      return;
    }

    // Add to our old list the memberInfo objects that were not previously there.
    for (MemberInfo m : next) {
      if (old == null) {
        System.out.println("OLD NULL");
      }

      if (m == null) {
        System.out.println("M NULL");
      }

      if (!old.contains(m)) {
        old.add(m);
      }
    }

    // Remove from our old list the memberInfo objects that are absent in next.
    LinkedList<MemberInfo> toRemove = new LinkedList<MemberInfo>();
    for (MemberInfo m : old) {
      if (!next.contains(m)) {
        toRemove.add(m);
      }
    }
    for (MemberInfo m : toRemove) {
      old.remove(m);
    }
  }
Exemplo n.º 2
0
  /** Generate a sentence that includes (if possible) the specified word. */
  public String getSentence(String word) {
    LinkedList parts = new LinkedList();

    Quad[] quads;
    if (words.containsKey(word)) {
      quads = (Quad[]) ((HashSet) words.get(word)).toArray(new Quad[0]);
    } else {
      quads = (Quad[]) this.quads.keySet().toArray(new Quad[0]);
    }

    if (quads.length == 0) {
      return "";
    }

    Quad middleQuad = quads[rand.nextInt(quads.length)];
    Quad quad = middleQuad;

    for (int i = 0; i < 4; i++) {
      parts.add(quad.getToken(i));
    }

    while (quad.canEnd() == false) {
      String[] nextTokens = (String[]) ((HashSet) next.get(quad)).toArray(new String[0]);
      String nextToken = nextTokens[rand.nextInt(nextTokens.length)];
      quad =
          (Quad)
              this.quads.get(
                  new Quad(quad.getToken(1), quad.getToken(2), quad.getToken(3), nextToken));
      parts.add(nextToken);
    }

    quad = middleQuad;
    while (quad.canStart() == false) {
      String[] previousTokens = (String[]) ((HashSet) previous.get(quad)).toArray(new String[0]);
      String previousToken = previousTokens[rand.nextInt(previousTokens.length)];
      quad =
          (Quad)
              this.quads.get(
                  new Quad(previousToken, quad.getToken(0), quad.getToken(1), quad.getToken(2)));
      parts.addFirst(previousToken);
    }

    StringBuffer sentence = new StringBuffer();
    Iterator it = parts.iterator();
    while (it.hasNext()) {
      String token = (String) it.next();
      sentence.append(token);
    }

    return sentence.toString();
  }
Exemplo n.º 3
0
 // Test method
 public LinkedList<Integer> getLiveAuctionsIds() throws RemoteException {
   LinkedList<Integer> ll = new LinkedList<Integer>();
   for (AuctionItem t : liveAuctionItems.values()) {
     ll.add(t.getAuctionId());
   }
   return ll;
 }
 public void addFinishedTarget(Target target) {
   // 向finishedTargets队列中加入一个任务
   synchronized (finishedTargets) {
     finishedTargets.notify();
     finishedTargets.add(target);
   }
 }
  public void addTarget(Target target) {
    // 向targets队列中加入一个任务
    SocketChannel socketChannel = null;
    try {
      socketChannel = SocketChannel.open();
      socketChannel.configureBlocking(false);
      socketChannel.connect(target.address);

      target.channel = socketChannel;
      target.connectStart = System.currentTimeMillis();

      synchronized (targets) {
        targets.add(target);
      }
      selector.wakeup();
    } catch (Exception x) {
      if (socketChannel != null) {
        try {
          socketChannel.close();
        } catch (IOException xx) {
        }
      }
      target.failure = x;
      addFinishedTarget(target);
    }
  }
Exemplo n.º 6
0
  public String get_item_ids() {

    String jsonarry;

    try {

      krypton_database_get_my_tokens getxt = new krypton_database_get_my_tokens();

      String token_array[] = new String[network.listing_size];
      token_array = getxt.get_tokens(network.base58_id);

      LinkedList<String> list = new LinkedList<String>();
      for (int loop = 0; loop < token_array.length; loop++) { // ************

        if (!token_array[loop].contains("-")) {
          list.add(token_array[loop]);
        }
      } // *****************************************************************

      jsonarry = JSONValue.toJSONString(list);

    } catch (Exception e) {

      statex = "0";
      jsonarry = "Error";
    } // *****************

    return jsonarry;
  } // *************************************
Exemplo n.º 7
0
    void add(Target t) {
      SocketChannel sc = null;
      try {

        sc = SocketChannel.open();
        sc.configureBlocking(false);

        boolean connected = sc.connect(t.address);

        t.channel = sc;
        t.connectStart = System.currentTimeMillis();

        if (connected) {
          t.connectFinish = t.connectStart;
          sc.close();
          printer.add(t);
        } else {
          synchronized (pending) {
            pending.add(t);
          }

          sel.wakeup();
        }
      } catch (IOException x) {
        if (sc != null) {
          try {
            sc.close();
          } catch (IOException xx) {
          }
        }
        t.failure = x;
        printer.add(t);
      }
    }
Exemplo n.º 8
0
  /** {@inheritDoc} */
  public void initializeFrom(Element element) throws DocumentSerializationException {
    for (Enumeration e = element.getChildren(); e.hasMoreElements(); ) {
      Element serviceElement = (TextElement) e.nextElement();
      String tagName = (String) serviceElement.getKey();

      if (tagName.equals("service")) {
        try {
          ModuleClassID moduleClassID =
              (ModuleClassID)
                  IDFactory.fromURI(
                      new URI(
                          DocumentSerializableUtilities.getString(
                              serviceElement, "moduleClassID", "ERROR")));

          try {
            ServiceMonitorFilter serviceMonitorFilter =
                MonitorResources.createServiceMonitorFilter(moduleClassID);
            serviceMonitorFilter.init(moduleClassID);
            Element serviceMonitorFilterElement =
                DocumentSerializableUtilities.getChildElement(serviceElement, "serviceFilter");
            serviceMonitorFilter.initializeFrom(serviceMonitorFilterElement);
            serviceMonitorFilters.put(moduleClassID, serviceMonitorFilter);
          } catch (Exception ex) {
            if (unknownModuleClassIDs == null) unknownModuleClassIDs = new LinkedList();

            unknownModuleClassIDs.add(moduleClassID);
          }
        } catch (URISyntaxException jex) {
          throw new DocumentSerializationException("Can't get ModuleClassID", jex);
        }
      }
    }
  }
Exemplo n.º 9
0
 @Override
 public LinkedList<String> getExpiredAuctions() throws RemoteException {
   LinkedList<String> ll = new LinkedList<String>();
   for (ExpiredAuctionItem item : expiredAuctions.values()) {
     ll.add(item.toString());
   }
   return ll;
 }
Exemplo n.º 10
0
 @Override
 public LinkedList<String> getExistingAuctions() throws RemoteException {
   LinkedList<String> ll = new LinkedList<String>();
   for (AuctionItem i : liveAuctionItems.values()) {
     ll.add(i.toString());
   }
   return ll;
 }
    public void sendMessage(Address address, byte[] message) throws java.io.IOException {
      Socket s = null;
      SocketEntry entry = (SocketEntry) sockets.get(address);
      if (logger.isDebugEnabled()) {
        logger.debug("Looking up connection for destination '" + address + "' returned: " + entry);
        logger.debug(sockets.toString());
      }
      if (entry != null) {
        s = entry.getSocket();
      }
      if ((s == null) || (s.isClosed())) {
        if (logger.isDebugEnabled()) {
          logger.debug("Socket for address '" + address + "' is closed, opening it...");
        }
        SocketChannel sc = null;
        try {
          // Open the channel, set it to non-blocking, initiate connect
          sc = SocketChannel.open();
          sc.configureBlocking(false);
          sc.connect(
              new InetSocketAddress(
                  ((TcpAddress) address).getInetAddress(), ((TcpAddress) address).getPort()));
          s = sc.socket();
          entry = new SocketEntry((TcpAddress) address, s);
          entry.addMessage(message);
          sockets.put(address, entry);

          synchronized (pending) {
            pending.add(entry);
          }

          selector.wakeup();
          logger.debug("Trying to connect to " + address);
        } catch (IOException iox) {
          logger.error(iox);
          throw iox;
        }
      } else {
        entry.addMessage(message);
        synchronized (pending) {
          pending.add(entry);
        }
        selector.wakeup();
      }
    }
Exemplo n.º 12
0
  public ShowComp() throws InterruptedException, IOException {
    super("CONNECTED COMPUTERS");
    int x = 0, d = 20;
    mb = new JMenuBar();
    File = new JMenu("File");
    mb.add(File);
    exit = new JMenuItem("Exit");
    exit.addActionListener(this);
    File.add(exit);
    ta = new JTextArea();
    ta.setBounds(20, 30, 315, 470);
    ta.setEditable(false);
    add(ta);

    setJMenuBar(mb);

    sel = new JLabel("The connected computers are..");
    sel.setBounds(15, 5, 300, 30);
    add(sel);
    b1 = new JButton("<< BACK");
    b1.setBounds(140, 510, 100, 30);
    b1.setToolTipText("Back to main page");
    b1.addActionListener(this);
    add(b1);
    setLayout(null);
    while (x < 360) {
      x = x + d;
      setBounds(675, 50, x, 600);
      this.show();
    }
    // setVisible(true);
    String s = "192.168.0.", temp = null;
    Printer printer = new Printer();
    printer.start();
    Connector connector = new Connector(printer);
    connector.start();

    LinkedList targets = new LinkedList();
    for (int i = 1; i <= 255; i++) {
      temp = s + Integer.toString(i);
      Target t = new Target(temp);
      targets.add(t);
      connector.add(t);
    }
    Thread.sleep(2000);
    connector.shutdown();
    connector.join();

    for (Iterator i = targets.iterator(); i.hasNext(); ) {
      Target t = (Target) i.next();
      if (!t.shown) t.show();
    }

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
  }
Exemplo n.º 13
0
 @Override
 public Iterator<TickClient> getLocalItems(int itemTypes, Room R) {
   LinkedList<TickClient> localItems = null;
   for (TickClient C : tickers) {
     switch (itemTypes) {
       case 0:
         if (C.getClientObject() instanceof MOB) {
           if (((MOB) C.getClientObject()).getStartRoom() == R) {
             if (localItems == null) localItems = new LinkedList<TickClient>();
             localItems.add(C);
           }
         } else if ((C.getClientObject() instanceof ItemTicker)
             && ((((ItemTicker) C.getClientObject()).properLocation() == R))) {
           if (localItems == null) localItems = new LinkedList<TickClient>();
           localItems.add(C);
         }
         break;
       case 1:
         if ((C.getClientObject() instanceof ItemTicker)
             && ((((ItemTicker) C.getClientObject()).properLocation() == R))) {
           if (localItems == null) localItems = new LinkedList<TickClient>();
           localItems.add(C);
         }
         break;
       case 2:
         if ((C.getClientObject() instanceof MOB)
             && (((MOB) C.getClientObject()).getStartRoom() == R)) {
           if (localItems == null) localItems = new LinkedList<TickClient>();
           localItems.add(C);
         }
         break;
     }
   }
   if (localItems == null) return null;
   return localItems.iterator();
 }
Exemplo n.º 14
0
  /** Creates a user data object with default values. */
  public UserData() {
    interactive = true;
    startServer = true;
    enableWindowsService = false;
    forceOnError = true;
    verbose = false;

    LinkedList<String> baseDn = new LinkedList<>();
    baseDn.add("dc=example,dc=com");
    NewSuffixOptions defaultNewSuffixOptions = NewSuffixOptions.createEmpty(baseDn);
    setNewSuffixOptions(defaultNewSuffixOptions);

    // See what we can propose as port
    int defaultLdapPort = getDefaultPort();
    if (defaultLdapPort != -1) {
      setServerPort(defaultLdapPort);
    }

    //  See what we can propose as port
    int defaultAdminPort = getDefaultAdminConnectorPort();
    if (defaultAdminPort != -1) {
      setAdminConnectorPort(defaultAdminPort);
    }

    setHostName(getDefaultHostName());

    setDirectoryManagerDn(Constants.DIRECTORY_MANAGER_DN);

    setNewSuffixOptions(defaultNewSuffixOptions);
    DataReplicationOptions repl = DataReplicationOptions.createStandalone();
    setReplicationOptions(repl);
    setGlobalAdministratorUID(Constants.GLOBAL_ADMIN_UID);

    SuffixesToReplicateOptions suffixes =
        new SuffixesToReplicateOptions(
            SuffixesToReplicateOptions.Type.REPLICATE_WITH_EXISTING_SUFFIXES,
            new HashSet<SuffixDescriptor>(),
            new HashSet<SuffixDescriptor>());
    setSuffixesToReplicateOptions(suffixes);
    SecurityOptions sec = SecurityOptions.createNoCertificateOptions();
    sec.setSslPort(getDefaultSslPort(defaultLdapPort));
    setSecurityOptions(sec);

    remoteWithNoReplicationPort = new HashMap<>();

    createDefaultJavaArguments();
  }
Exemplo n.º 15
0
 private Drawing createDrawing() {
   DefaultDrawing drawing = new DefaultDrawing();
   LinkedList<InputFormat> inputFormats = new LinkedList<InputFormat>();
   inputFormats.add(new SVGInputFormat());
   inputFormats.add(new SVGZInputFormat());
   inputFormats.add(new ImageInputFormat(new SVGImageFigure()));
   inputFormats.add(new TextInputFormat(new SVGTextFigure()));
   LinkedList<OutputFormat> outputFormats = new LinkedList<OutputFormat>();
   outputFormats.add(new SVGOutputFormat());
   outputFormats.add(new ImageOutputFormat());
   drawing.setInputFormats(inputFormats);
   drawing.setOutputFormats(outputFormats);
   return drawing;
 }
Exemplo n.º 16
0
  /** {@inheritDoc} */
  public void initializeFrom(Element element) throws DocumentSerializationException {
    for (Enumeration e = element.getChildren(); e.hasMoreElements(); ) {
      Element childElement = (TextElement) e.nextElement();
      String tagName = (String) childElement.getKey();

      if (tagName.equals("transportMetric")) {
        TransportMetric transportMetric =
            (TransportMetric)
                DocumentSerializableUtilities.getDocumentSerializable(
                    childElement, TransportMetric.class);
        transportMetrics.add(transportMetric);
      }
      if (tagName.equals("moduleClassID")) {
        try {
          moduleClassID =
              (ModuleClassID)
                  IDFactory.fromURI(new URI(DocumentSerializableUtilities.getString(childElement)));
        } catch (URISyntaxException jex) {
          throw new DocumentSerializationException("Can't read moduleClassID", jex);
        }
      }
    }
  }
  /**
   * Enrich portClassHier with class/interface names that map to a list of parent
   * classes/interfaces. For any class encountered, find its parents too.<br>
   * Also find the port types which have assignable schema classes.
   *
   * @param oper Operator to work on
   * @param portClassHierarchy In-Out param that contains a mapping of class/interface to its
   *     parents
   * @param portTypesWithSchemaClasses Json that will contain all the ports which have any schema
   *     classes.
   */
  public void buildAdditionalPortInfo(
      JSONObject oper, JSONObject portClassHierarchy, JSONObject portTypesWithSchemaClasses) {
    try {
      JSONArray ports = oper.getJSONArray(OperatorDiscoverer.PORT_TYPE_INFO_KEY);
      for (int i = 0; i < ports.length(); i++) {
        JSONObject port = ports.getJSONObject(i);

        String portType = port.optString("type");
        if (portType == null) {
          // skipping if port type is null
          continue;
        }

        if (typeGraph.size() == 0) {
          buildTypeGraph();
        }

        try {
          // building port class hierarchy
          LinkedList<String> queue = Lists.newLinkedList();
          queue.add(portType);
          while (!queue.isEmpty()) {
            String currentType = queue.remove();
            if (portClassHierarchy.has(currentType)) {
              // already present in the json so we skip.
              continue;
            }
            List<String> immediateParents = typeGraph.getParents(currentType);
            if (immediateParents == null) {
              portClassHierarchy.put(currentType, Lists.<String>newArrayList());
              continue;
            }
            portClassHierarchy.put(currentType, immediateParents);
            queue.addAll(immediateParents);
          }
        } catch (JSONException e) {
          LOG.warn("building port type hierarchy {}", portType, e);
        }

        // finding port types with schema classes
        if (portTypesWithSchemaClasses.has(portType)) {
          // already present in the json so skipping
          continue;
        }
        if (portType.equals("byte")
            || portType.equals("short")
            || portType.equals("char")
            || portType.equals("int")
            || portType.equals("long")
            || portType.equals("float")
            || portType.equals("double")
            || portType.equals("java.lang.String")
            || portType.equals("java.lang.Object")) {
          // ignoring primitives, strings and object types as this information is needed only for
          // complex types.
          continue;
        }
        if (port.has("typeArgs")) {
          // ignoring any type with generics
          continue;
        }
        boolean hasSchemaClasses = false;
        List<String> instantiableDescendants = typeGraph.getInstantiableDescendants(portType);
        if (instantiableDescendants != null) {
          for (String descendant : instantiableDescendants) {
            try {
              if (typeGraph.isInstantiableBean(descendant)) {
                hasSchemaClasses = true;
                break;
              }
            } catch (JSONException ex) {
              LOG.warn("checking descendant is instantiable {}", descendant);
            }
          }
        }
        portTypesWithSchemaClasses.put(portType, hasSchemaClasses);
      }
    } catch (JSONException e) {
      // should not reach this
      LOG.error("JSON Exception {}", e);
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 18
0
 void add(Target t) {
   synchronized (pending) {
     pending.add(t);
     pending.notify();
   }
 }
Exemplo n.º 19
0
  private void readwrite(long s1[], long s2[], int pass) {
    // oids[] should correspond to s1[] going in, s2[] going out
    String[] names = null;
    time_retrieve = 0;
    store_bytes = 0;
    time_store = 0;

    String algorithm_id = algorithms[randIndex(algorithms.length)];
    String content_type = content_types[randIndex(content_types.length)];
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < s1.length; i++) {
      String retrieved = null;
      boolean error1 = false;
      long t1 = System.currentTimeMillis();
      while (true) {
        boolean error = false;
        try {
          retrieved = retrieve(oids[i], times, 0);
          time_retrieve += times[0];
          total_retrieve_time += times[0];
        } catch (HoneycombTestException e) {
          flex("retrv " + oids[i], e);
          String s = "#e retrv " + oids[i] + ": " + e.getMessage();
          log.log(s);
          // flog(s + "\n");
          // e.printStackTrace();
          error = true;
        } catch (Throwable t) {
          flex("retrv " + oids[i], t);
          log.log("retrieve got throwable");
          t.printStackTrace();
          error = true;
        }
        if (error) {
          error1 = true;
          retrieve_retries++;
          if (System.currentTimeMillis() - t1 > GIVEUP) {
            retrieve_failures++;
            retrieved = null;
            break;
          }
          sleep(SLEEP);
          continue;
        }
        break;
      }
      if (retrieved == null) {
        failed_rtrv.add(oids[i]);
      } else {
        if (error1) flog("#E ok\n");
        dot("r");
        // compare retrieved w/ original
        File f = new File(retrieved);
        if (f.length() != s1[i]) {
          bad_file_errors++;
          String s =
              "#e size mismatch ["
                  + oids[i]
                  + "] store/retrieve: "
                  + s1[i]
                  + " / "
                  + f.length()
                  + "\n";
          flog(s);
        } else {
          String sha1sum = null;
          try {
            sha1sum = shell.sha1sum(retrieved);
          } catch (Exception e) {
            e.printStackTrace();
          }
          if (sha1sum != null && !sha1sum.equals(shas[i])) {
            bad_file_errors++;
            String s =
                "#e sha1 mismatch ["
                    + oids[i]
                    + "] store/retrieve: "
                    + shas[i]
                    + " / "
                    + sha1sum
                    + "\n";
            flog(s);
          }
        }
        deleteFile(retrieved);
      }
      // compare mdata
      t1 = System.currentTimeMillis();
      NameValueRecord nvr = null;
      error1 = false;
      while (true) {
        boolean error = false;
        try {
          nvr = retrieveMetadata(oids[i], times, 0);
          md_retrieve_time += times[0];
          md_retrieves++;
        } catch (HoneycombTestException e) {
          flex("md retrv " + oids[i], e);
          String s = "#e md retrv " + oids[i] + ": " + e.getMessage();
          log.log(s);
          // flog(s + "\n");
          // e.printStackTrace();
          error = true;
        } catch (Throwable t) {
          flex("md retrv " + oids[i], t);
          log.log("md retrieve got throwable");
          t.printStackTrace();
          error = true;
        }
        if (error) {
          error1 = true;
          md_retrieve_retries++;
          if (System.currentTimeMillis() - t1 > GIVEUP) {
            md_retrieve_failures++;
            nvr = null;
            flog("#E " + oids[i] + ": giving up\n");
            break;
          }
          sleep(SLEEP);
          continue;
        }
        break;
      }
      if (nvr == null) {
        failed_md_rtrv.add(oids[i]);
      } else {
        if (error1) flog("#E ok\n");
        SystemRecord sr = nvr.getSystemRecord();
        String stored_oid = sr.getObjectIdentifier().toString();
        if (!oids[i].equals(stored_oid)) {
          // one oid looked up another
          sb.append("#e  oid mismatch! ").append(oids[i]);
          sb.append(" / ").append(stored_oid).append("\n");
        }
        String sha2 = nvr.getString("sha1");
        if (sha2 == null) {
          sb.append("#e  no sha1 in metadata\n");
        } else if (!sha2.equals(shas[i])) {
          sb.append("#e  original/md sha:  ").append(shas[i]);
          sb.append(" / ").append(sha2).append("\n");
        }

        checkMD(sb, nvr, "cedars_subject_id", subject_id);
        checkMD(sb, nvr, "cedars_study_id", study_id);
        checkMD(sb, nvr, "cedars_species_id", species_id);
        checkMD(sb, nvr, "cedars_sample_id", sample_id);
        checkMD(sb, nvr, "cedars_collection_date", collection_date);
        checkMD(sb, nvr, "cedars_processing_date", processing_date);
        checkMD(sb, nvr, "cedars_collected_by", collected_by);
        checkMD(sb, nvr, "cedars_processed_by", processed_by);
        checkMD(sb, nvr, "cedars_sample_type", sample_type);
        checkMD(sb, nvr, "cedars_experiment_date", experiment_date);
        checkMD(sb, nvr, "cedars_experiment_number", experiment_number);

        checkMD(sb, nvr, "cedars_scan_number", Integer.toString(i));

        if (pass > 2) {
          checkMD(sb, nvr, "cedars_algorithm_id", prev_algorithm_id);
          checkMD(sb, nvr, "cedars_content_type", prev_content_type);
        }

        if (sb.length() > 0) {
          bad_md_errors++;
          flog("#e md error " + oids[i] + "\n");
          flog(sb.toString());
          sb.setLength(0);
        }
      }

      if (s2 != null) {
        // store next smaller file and save oid
        nvr = createRecord();
        nvr.put("cedars_subject_id", subject_id);
        nvr.put("cedars_study_id", study_id);
        nvr.put("cedars_species_id", species_id);

        nvr.put("cedars_sample_id", sample_id);
        nvr.put("cedars_collection_date", collection_date);
        nvr.put("cedars_processing_date", processing_date);
        nvr.put("cedars_collected_by", collected_by);
        nvr.put("cedars_processed_by", processed_by);
        nvr.put("cedars_sample_type", sample_type);

        nvr.put("cedars_experiment_date", experiment_date);
        nvr.put("cedars_experiment_number", experiment_number);

        nvr.put("cedars_pass", Long.toString(pass));
        nvr.put("cedars_scan_number", Long.toString(i));

        nvr.put("cedars_algorithm_id", algorithm_id);
        nvr.put("cedars_content_type", content_type);

        names = store(names, s2[i], i, nvr);
        oids[i] = names[1];
        dot("s");
      }
    }
    prev_algorithm_id = algorithm_id;
    prev_content_type = content_type;

    if (names != null && names[0] != null) deleteFile(names[0]);
  }
Exemplo n.º 20
0
 /** Append a Transport Metric */
 public void addTransportMetric(TransportMetric transportMetric) {
   transportMetrics.add(transportMetric);
 }