Esempio n. 1
0
  protected Connector findConnector(String connectorName) {
    //    List connectors =
    //      com.sun.jdi.Bootstrap.virtualMachineManager().allConnectors();
    List connectors = org.eclipse.jdi.Bootstrap.virtualMachineManager().allConnectors();

    //    // debug: code to list available connectors
    //    Iterator iter2 = connectors.iterator();
    //    while (iter2.hasNext()) {
    //      Connector connector = (Connector)iter2.next();
    //      System.out.println("connector name is " + connector.name());
    //    }

    for (Object c : connectors) {
      Connector connector = (Connector) c;
      //      System.out.println(connector.name());
      //    }
      //    Iterator iter = connectors.iterator();
      //    while (iter.hasNext()) {
      //      Connector connector = (Connector)iter.next();
      if (connector.name().equals(connectorName)) {
        return connector;
      }
    }
    Base.showError(
        "Compiler Error",
        "findConnector() failed to find " + connectorName + " inside Runner",
        null);
    return null; // Not reachable
  }
 public PingClient() throws IOException {
   selector = Selector.open();
   Connector connector = new Connector();
   Printer printer = new Printer();
   connector.start();
   printer.start();
   receiveTarget();
 }
Esempio n. 3
0
 private Connector findConnector(String name) {
   for (Connector connector : Bootstrap.virtualMachineManager().allConnectors()) {
     if (connector.name().equals(name)) {
       return connector;
     }
   }
   return null;
 }
  /** Draws this handle. */
  public void draw(Graphics2D g) {
    Graphics2D gg = (Graphics2D) g.create();
    gg.transform(view.getDrawingToViewTransform());
    for (Connector c : connectors) {
      c.draw(gg);
    }

    gg.dispose();
    drawCircle(g, (getTarget() == null) ? Color.red : Color.green, Color.black);
  }
Esempio n. 5
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);
  }
Esempio n. 6
0
 /*
  * Find Connector by name
  */
 private static Connector findConnector(String name) {
   List connectors = Bootstrap.virtualMachineManager().allConnectors();
   Iterator iter = connectors.iterator();
   while (iter.hasNext()) {
     Connector connector = (Connector) iter.next();
     if (connector.name().equals(name)) {
       return connector;
     }
   }
   return null;
 }
 /** Finds a new connectableConnector of the connection. */
 public void trackStep(Point anchor, Point lead, int modifiersEx) {
   Point2D.Double p = view.viewToDrawing(lead);
   view.getConstrainer().constrainPoint(p);
   connectableFigure = findConnectableFigure(p, view.getDrawing());
   if (connectableFigure != null) {
     Connector aTarget = findConnectionTarget(p, view.getDrawing());
     if (aTarget != null) {
       p = aTarget.getAnchor();
     }
   }
   getOwner().willChange();
   setLocation(p);
   getOwner().changed();
   repaintConnectors();
 }
  @Override
  public APIBlockIdList getBlockIds(BID blockId, int count) throws BCSAPIException {
    try (ConnectorSession session = connection.createSession()) {
      log.trace("get " + count + " block ids from " + blockId);

      ConnectorProducer blockIdsRequestProducer =
          session.createProducer(session.createQueue("blockIdsRequest"));

      ConnectorMessage m = session.createMessage();
      BCSAPIMessage.BLKIDSREQ.Builder builder = BCSAPIMessage.BLKIDSREQ.newBuilder();
      if (blockId != null) {
        builder.setBlockHash(ByteString.copyFrom(blockId.unsafeGetArray()));
      }
      if (count <= 0) count = 20;
      builder.setCount(count);
      m.setPayload(builder.build().toByteArray());
      byte[] response = synchronousRequest(session, blockIdsRequestProducer, m);
      if (response != null) {
        BCSAPIMessage.BLKIDS message = BCSAPIMessage.BLKIDS.parseFrom(response);
        List<ByteString> blockIdsList = message.getBlockIdsList();
        List<BID> blockIds =
            blockIdsList.stream().map(bs -> new BID(bs.toByteArray())).collect(Collectors.toList());
        return new APIBlockIdList(
            blockIds,
            message.getHeight(),
            message.hasPreviousBlockId()
                ? new BID(message.getPreviousBlockId().toByteArray())
                : null);
      }
    } catch (ConnectorException | InvalidProtocolBufferException e) {
      throw new BCSAPIException(e);
    }

    return null;
  }
Esempio n. 9
0
  private Image getImage(String str) throws IOException {
    String url = "http://" + controller.selectedCity.URL + "/cameras/images/" + str + ".jpg";
    System.out.println(url);
    InputStream iStrm = (InputStream) Connector.openInputStream(url);
    Image im = null;

    try {
      ByteArrayOutputStream bStrm = new ByteArrayOutputStream();

      int ch;
      while ((ch = iStrm.read()) != -1) bStrm.write(ch);

      // Place into image array
      byte imageData[] = bStrm.toByteArray();

      // Create the image from the byte array
      im = Image.createImage(imageData, 0, imageData.length);

    } finally {
      // Clean up
      if (iStrm != null) iStrm.close();
    }

    return (im == null ? null : im);
  }
Esempio n. 10
0
 private Image getAvatar() {
   HttpConnection httemp = null;
   InputStream istemp = null;
   Image avatar = null;
   try {
     httemp = (HttpConnection) Connector.open(url);
     if (HttpConnection.HTTP_OK != httemp.getResponseCode()) {
       throw new IOException();
     }
     istemp = httemp.openInputStream();
     byte[] avatarBytes = read(istemp, (int) httemp.getLength());
     // #sijapp cond.if modules_TRAFFIC is "true" #
     Traffic.getInstance().addInTraffic(avatarBytes.length);
     // #sijapp cond.end#
     avatar = javax.microedition.lcdui.Image.createImage(avatarBytes, 0, avatarBytes.length);
     avatarBytes = null;
   } catch (Exception e) {
   }
   try {
     httemp.close();
     istemp.close();
   } catch (Exception e) {
   }
   return avatar;
 }
Esempio n. 11
0
 public void setContextPath(String contextPath) {
   this.contextPath = contextPath;
   if (context == null) {
     Host host = (Host) connector.getContainer();
     context = host.getContext(contextPath);
   }
 }
Esempio n. 12
0
  @Override
  public List<APITransaction> getInputTransactions(TID txId) throws BCSAPIException {
    log.trace("get input transactions " + txId);
    ConnectorMessage m;
    try (ConnectorSession session = connection.createSession()) {
      ConnectorProducer transactionRequestProducer =
          session.createProducer(session.createQueue("inputTransactionsRequest"));

      m = session.createMessage();
      BCSAPIMessage.Hash.Builder builder = BCSAPIMessage.Hash.newBuilder();
      builder.addHash(ByteString.copyFrom(txId.unsafeGetArray()));
      m.setPayload(builder.build().toByteArray());
      byte[] response = synchronousRequest(session, transactionRequestProducer, m);
      if (response != null) {
        List<BCSAPIMessage.OPTIONAL_TX> txsList =
            BCSAPIMessage.TXS.parseFrom(response).getTxsList();
        List<APITransaction> txs = new ArrayList<>(txsList.size());
        for (BCSAPIMessage.OPTIONAL_TX tx : txsList) {
          if (tx.getIsNull()) {
            txs.add(null);
          } else {
            txs.add(APITransaction.fromProtobuf(tx.getTransaction()));
          }
        }
        return txs;
      }
    } catch (ConnectorException | HyperLedgerException | InvalidProtocolBufferException e) {
      throw new BCSAPIException(e);
    }

    return null;
  }
Esempio n. 13
0
  @Override
  public void catchUp(List<BID> inventory, int limit, boolean headers, final TrunkListener listener)
      throws BCSAPIException {
    log.trace("catchUp");
    ConnectorMessage m;
    try (ConnectorSession session = connection.createSession()) {
      ConnectorProducer transactionRequestProducer =
          session.createProducer(session.createQueue("catchUpRequest"));

      m = session.createMessage();
      BCSAPIMessage.CatchUpRequest.Builder builder = BCSAPIMessage.CatchUpRequest.newBuilder();
      builder.setLimit(limit);
      builder.setHeaders(true);
      for (BID hash : inventory) {
        builder.addInventory(ByteString.copyFrom(hash.unsafeGetArray()));
      }
      m.setPayload(builder.build().toByteArray());
      byte[] response = synchronousRequest(session, transactionRequestProducer, m);
      if (response != null) {
        BCSAPIMessage.TrunkUpdate blockMessage = BCSAPIMessage.TrunkUpdate.parseFrom(response);
        List<APIBlock> blockList = new ArrayList<>();
        for (BCSAPIMessage.BLK b : blockMessage.getAddedList()) {
          blockList.add(APIBlock.fromProtobuf(b));
        }
        listener.trunkUpdate(blockList);
      }
    } catch (ConnectorException | HyperLedgerException | InvalidProtocolBufferException e) {
      throw new BCSAPIException(e);
    }
  }
Esempio n. 14
0
  private void getTrafficSpots() {
    controller.showProgressBar();
    String uploadWebsite =
        "http://" + controller.selectedCity.URL + "/php/trafficstatus.cache?dummy=ert43";
    String[] ArrayOfData = null;
    StreamConnection c = null;
    InputStream s = null;
    StringBuffer b = new StringBuffer();

    String url = uploadWebsite;
    System.out.print(url);
    try {
      c = (StreamConnection) Connector.open(url);
      s = c.openDataInputStream();
      int ch;
      int k = 0;
      while ((ch = s.read()) != -1) {
        System.out.print((char) ch);
        b.append((char) ch);
      }
      // System.out.println("b"+b);
      try {
        JSONObject ff1 = new JSONObject(b.toString());
        String data1 = ff1.getString("locations");
        JSONArray jsonArray1 = new JSONArray(data1);
        Vector TrafficStatus = new Vector();
        for (int i = 0; i < jsonArray1.length(); i++) {

          System.out.println(jsonArray1.getJSONArray(i).getString(3));
          double aDoubleLat = Double.parseDouble(jsonArray1.getJSONArray(i).getString(1));
          double aDoubleLon = Double.parseDouble(jsonArray1.getJSONArray(i).getString(2));
          System.out.println(aDoubleLat + " " + aDoubleLon);
          TrafficStatus.addElement(
              new LocationPointer(
                  jsonArray1.getJSONArray(i).getString(3),
                  (float) aDoubleLon,
                  (float) aDoubleLat,
                  1,
                  true));
        }
        controller.setCurrentScreen(controller.TrafficSpots(TrafficStatus));
      } catch (Exception E) {
        controller.setCurrentScreen(traf);
        new Thread() {
          public void run() {
            controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO);
          }
        }.start();
      }

    } catch (Exception e) {

      controller.setCurrentScreen(traf);
      new Thread() {
        public void run() {
          controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO);
        }
      }.start();
    }
  }
Esempio n. 15
0
 public void destroy() {
   try {
     if (connection != null) {
       connection.close();
     }
   } catch (Exception e) {
   }
 }
Esempio n. 16
0
 public void init() {
   try {
     log.debug("Initialize BCSAPI connector");
     connection = connectionFactory.getConnector();
     connection.start();
   } catch (Exception e) {
     log.error("Can not create connector", e);
   }
 }
Esempio n. 17
0
 private Object request(
     String url, boolean post, Hashtable params, boolean basicAuth, boolean processOutput)
     throws Exception {
   HttpConnection conn = null;
   Writer writer = null;
   InputStream is = null;
   try {
     if (!post && (params != null)) {
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       OutputStreamWriter osw = new OutputStreamWriter(baos, this.encoding);
       this.encodeParams(params, osw);
       osw.flush();
       osw.close();
       osw = null;
       url += "?" + new String(baos.toByteArray(), this.encoding);
       baos = null;
     }
     conn = (HttpConnection) Connector.open(url);
     conn.setRequestMethod(post ? HttpConnection.POST : HttpConnection.GET);
     if (basicAuth) {
       if (!this.areCredentialsSet()) throw new Exception("Credentials are not set");
       String token = base64Encode((this.user + ":" + this.pass).getBytes(this.encoding));
       conn.setRequestProperty("Authorization", "Basic " + token);
     }
     if (post && (params != null)) {
       OutputStream os = conn.openOutputStream();
       writer = new OutputStreamWriter(os, this.encoding);
       this.encodeParams(params, writer);
       writer.flush();
       writer.close();
       os = null;
       writer = null;
     }
     int code = conn.getResponseCode();
     if ((code != 200) && (code != 302))
       throw new Exception("Unexpected response code " + code + ": " + conn.getResponseMessage());
     is = conn.openInputStream();
     if (processOutput) {
       synchronized (this.json) {
         return this.json.parse(is);
       }
     } else {
       this.pump(is, System.out, 1024);
       return null;
     }
   } finally {
     if (writer != null) writer.close();
     if (is != null) is.close();
     if (conn != null) conn.close();
   }
 }
Esempio n. 18
0
 protected void setupServerFromConfig(List connectors) throws IOException, IDCreateException {
   for (final Iterator i = connectors.iterator(); i.hasNext(); ) {
     final Connector connector = (Connector) i.next();
     final String hostname = connector.getHostname();
     final int port = connector.getPort();
     final String hostnamePort = hostname + ":" + port; // $NON-NLS-1$
     SSLServerSOContainerGroup serverGroup = null;
     synchronized (serverGroups) {
       serverGroup = (SSLServerSOContainerGroup) serverGroups.get(hostnamePort);
       if (serverGroup == null) {
         System.out.println(
             "Putting server " + hostnamePort + " on the air..."); // $NON-NLS-1$ //$NON-NLS-2$
         serverGroup = new SSLServerSOContainerGroup(hostname, port);
         final List groups = connector.getGroups();
         for (final Iterator g = groups.iterator(); g.hasNext(); ) {
           final NamedGroup group = (NamedGroup) g.next();
           // Create
           final SSLServerSOContainer container =
               createServerContainer(
                   group.getIDForGroup(), serverGroup, group.getName(), connector.getTimeout());
           // Configure
           configureServerContainer(container);
         }
         serverGroup.putOnTheAir();
         serverGroups.put(hostnamePort, serverGroup);
         System.out.println(
             "GenericServerContainer "
                 + hostnamePort //$NON-NLS-1$
                 + " on the air."); //$NON-NLS-1$
       } else {
         System.out.println(
             "GenericServerContainer "
                 + hostnamePort //$NON-NLS-1$
                 + " already on the air.  No changes made."); //$NON-NLS-1$
       }
     }
   }
 }
Esempio n. 19
0
 @SuppressWarnings("unchecked")
 private <T> void addTopicListener(
     String topic, Object inner, ByteArrayConverter<T> converter, TypedListener<T> listener)
     throws ConnectorException {
   synchronized (messageDispatcher) {
     MessageDispatcher<T> dispatcher = messageDispatcher.get(topic);
     if (dispatcher == null) {
       ConnectorSession session = connection.createSession();
       ConnectorConsumer consumer = session.createConsumer(session.createTopic(topic));
       messageDispatcher.put(topic, dispatcher = new MessageDispatcher<T>(consumer, converter));
     }
     dispatcher.addListener(inner, listener);
   }
 }
Esempio n. 20
0
  private String[] GetDataFromSite() {

    String uploadWebsite = "http://" + controller.selectedCity.URL + "/cameras/mobile_cam_list.php";
    String[] ArrayOfData = null;
    StreamConnection c = null;
    InputStream s = null;
    StringBuffer b = new StringBuffer();

    String url = uploadWebsite;
    System.out.print(url);
    try {
      c = (StreamConnection) Connector.open(url);
      s = c.openDataInputStream();
      int ch;
      int k = 0;
      while ((ch = s.read()) != -1) {
        System.out.print((char) ch);
        b.append((char) ch);
      }

      String result = b.toString();
      if (!result.equals("")) {

        ArrayOfData = StringUtil.split(result.toString().trim(), "~~");
        if (ArrayOfData.length == 0) {
          controller.MainMenu();
          new Thread() {
            public void run() {
              controller.showAlert("Network Error", 0, AlertType.ERROR);
            }
          }.start();
        }
      }
    } catch (Exception e) {
      System.out.print(e);
      new Thread() {
        public void run() {
          controller.showProgressBar();
        }
      }.start();
      // controller.getDisp().setCurrent(this);

    }

    return ArrayOfData;
  }
Esempio n. 21
0
  @Override
  public int getChainHeight() throws BCSAPIException {
    try (ConnectorSession session = connection.createSession()) {
      log.trace("get chain height");

      ConnectorProducer heightRequestProducer =
          session.createProducer(session.createQueue("chainHeightRequest"));

      ConnectorMessage m = session.createMessage();
      byte[] response = synchronousRequest(session, heightRequestProducer, m);
      if (response != null) {
        return BCSAPIMessage.HEIGHT.parseFrom(response).getHeight();
      }
    } catch (ConnectorException | InvalidProtocolBufferException e) {
      throw new BCSAPIException(e);
    }
    return -1;
  }
Esempio n. 22
0
  @Override
  public void spendingTransactions(List<TID> tids, final TransactionListener listener)
      throws BCSAPIException {
    try (ConnectorSession session = connection.createSession()) {
      ConnectorMessage m = session.createMessage();

      ConnectorProducer scanAccountProducer =
          session.createProducer(session.createQueue("spendingTransactions"));
      BCSAPIMessage.Hash.Builder builder = BCSAPIMessage.Hash.newBuilder();
      for (TID tid : tids) {
        builder.addHash(ByteString.copyFrom(tid.unsafeGetArray()));
      }
      m.setPayload(builder.build().toByteArray());

      final ConnectorTemporaryQueue answerQueue = session.createTemporaryQueue();
      final ConnectorConsumer consumer = session.createConsumer(answerQueue);
      m.setReplyTo(answerQueue);
      final Semaphore ready = new Semaphore(0);
      consumer.setMessageListener(
          message -> {
            try {
              byte[] body = message.getPayload();
              if (body != null) {
                APITransaction t = APITransaction.fromProtobuf(BCSAPIMessage.TX.parseFrom(body));
                listener.process(t);
              } else {
                consumer.close();
                answerQueue.delete();
                ready.release();
              }
            } catch (ConnectorException | HyperLedgerException | InvalidProtocolBufferException e) {
              log.error("Malformed message received for spendingt ransactions request", e);
            }
          });

      scanAccountProducer.send(m);
      ready.acquireUninterruptibly();
    } catch (ConnectorException e) {
      throw new BCSAPIException(e);
    }
  }
Esempio n. 23
0
  private void scanRequest(
      Collection<Script> match, final TransactionListener listener, String requestQueue)
      throws BCSAPIException {
    try (ConnectorSession session = connection.createSession()) {
      ConnectorMessage m = session.createMessage();

      ConnectorProducer exactMatchProducer =
          session.createProducer(session.createQueue(requestQueue));
      BCSAPIMessage.ExactMatchRequest.Builder builder =
          BCSAPIMessage.ExactMatchRequest.newBuilder();
      for (Script d : match) {
        builder.addMatch(ByteString.copyFrom(d.toByteArray()));
      }
      m.setPayload(builder.build().toByteArray());
      final ConnectorTemporaryQueue answerQueue = session.createTemporaryQueue();
      final ConnectorConsumer consumer = session.createConsumer(answerQueue);
      m.setReplyTo(answerQueue);
      final Semaphore ready = new Semaphore(0);
      consumer.setMessageListener(
          message -> {
            try {
              byte[] body = message.getPayload();
              if (body != null) {
                APITransaction t = APITransaction.fromProtobuf(BCSAPIMessage.TX.parseFrom(body));
                listener.process(t);
              } else {
                consumer.close();
                answerQueue.delete();
                ready.release();
              }
            } catch (ConnectorException | HyperLedgerException | InvalidProtocolBufferException e) {
              log.error("Malformed message received for scan matching transactions", e);
            }
          });

      exactMatchProducer.send(m);
      ready.acquireUninterruptibly();
    } catch (ConnectorException e) {
      throw new BCSAPIException(e);
    }
  }
Esempio n. 24
0
  @Override
  public APIHeader mine(Address address) throws BCSAPIException {
    try (ConnectorSession session = connection.createSession()) {
      log.trace("mine to " + address);

      ConnectorProducer producer = session.createProducer(session.createTopic("mine"));

      ConnectorMessage m = session.createMessage();
      BCSAPIMessage.Script.Builder builder =
          BCSAPIMessage.Script.newBuilder()
              .setScript(ByteString.copyFrom(address.getAddressScript().toByteArray()));
      m.setPayload(builder.build().toByteArray());
      byte[] reply = synchronousRequest(session, producer, m);
      if (reply != null) {
        return APIHeader.fromProtobuf(BCSAPIMessage.BLK.parseFrom(reply));
      }
    } catch (ConnectorException | InvalidProtocolBufferException | HyperLedgerException e) {
      throw new BCSAPIException(e);
    }
    return null;
  }
Esempio n. 25
0
  @Override
  public void sendBlock(Block block) throws BCSAPIException {
    try (ConnectorSession session = connection.createSession()) {
      log.trace("send block " + block.getID());
      ConnectorProducer blockProducer = session.createProducer(session.createTopic("newBlock"));

      ConnectorMessage m = session.createMessage();
      m.setPayload(block.toBCSAPIMessage().toByteArray());
      byte[] reply = synchronousRequest(session, blockProducer, m);
      if (reply != null) {
        try {
          BCSAPIMessage.ExceptionMessage em = BCSAPIMessage.ExceptionMessage.parseFrom(reply);
          throw new BCSAPIException(em.getMessage(0));
        } catch (InvalidProtocolBufferException e) {
          throw new BCSAPIException("Invalid response", e);
        }
      }
    } catch (ConnectorException e) {
      throw new BCSAPIException(e);
    }
  }
Esempio n. 26
0
  private String getContent(String url) {
    HttpConnection httemp = null;
    InputStream istemp = null;
    String content = "";

    try {
      httemp = (HttpConnection) Connector.open(url);
      httemp.setRequestProperty("Connection", "cl" + "ose");
      if (HttpConnection.HTTP_OK != httemp.getResponseCode()) {
        throw new IOException();
      }

      istemp = httemp.openInputStream();
      int length = (int) httemp.getLength();
      if (-1 != length) {
        byte[] bytes = new byte[length];
        istemp.read(bytes);
        content = new String(bytes);

      } else {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        while (true) {
          int ch = istemp.read();
          if (-1 == ch) break;
          bytes.write(ch);
        }
        content = new String(bytes.toByteArray());
        bytes.close();
      }

    } catch (Exception e) {
      content = "Error: " + e.getMessage();
    }
    try {
      httemp.close();
      istemp.close();
    } catch (Exception e) {
    }
    return StringConvertor.removeCr(content);
  }
Esempio n. 27
0
  @Override
  public APIHeader getBlockHeader(BID hash) throws BCSAPIException {
    try (ConnectorSession session = connection.createSession()) {
      log.trace("get block header" + hash);

      ConnectorProducer blockHeaderRequestProducer =
          session.createProducer(session.createQueue("headerRequest"));

      ConnectorMessage m = session.createMessage();
      BCSAPIMessage.Hash.Builder builder = BCSAPIMessage.Hash.newBuilder();
      builder.addHash(ByteString.copyFrom(hash.unsafeGetArray()));
      m.setPayload(builder.build().toByteArray());
      byte[] response = synchronousRequest(session, blockHeaderRequestProducer, m);
      if (response != null) {
        return APIHeader.fromProtobuf(BCSAPIMessage.BLK.parseFrom(response));
      }
    } catch (ConnectorException | InvalidProtocolBufferException e) {
      throw new BCSAPIException(e);
    }

    return null;
  }
Esempio n. 28
0
  private void scanRequest(
      MasterPublicKey master, int lookAhead, final TransactionListener listener, String request)
      throws BCSAPIException {
    try (ConnectorSession session = connection.createSession()) {
      ConnectorMessage m = session.createMessage();

      ConnectorProducer scanAccountProducer = session.createProducer(session.createQueue(request));
      BCSAPIMessage.AccountRequest.Builder builder = BCSAPIMessage.AccountRequest.newBuilder();
      builder.setPublicKey(master.serialize(true));
      builder.setLookAhead(lookAhead);
      m.setPayload(builder.build().toByteArray());

      final ConnectorTemporaryQueue answerQueue = session.createTemporaryQueue();
      final ConnectorConsumer consumer = session.createConsumer(answerQueue);
      m.setReplyTo(answerQueue);
      final Semaphore ready = new Semaphore(0);
      consumer.setMessageListener(
          message -> {
            try {
              byte[] body = message.getPayload();
              if (body != null) {
                APITransaction t = APITransaction.fromProtobuf(BCSAPIMessage.TX.parseFrom(body));
                listener.process(t);
              } else {
                consumer.close();
                answerQueue.delete();
                ready.release();
              }
            } catch (ConnectorException | HyperLedgerException | InvalidProtocolBufferException e) {
              log.error("Malformed message received for account scan transactions", e);
            }
          });

      scanAccountProducer.send(m);
      ready.acquireUninterruptibly();
    } catch (ConnectorException e) {
      throw new BCSAPIException(e);
    }
  }
Esempio n. 29
0
  private BCSAPIMessage.Ping handshake(long nonce) throws BCSAPIException {
    try (ConnectorSession session = connection.createSession()) {
      log.trace("ping " + nonce);

      ConnectorMessage m = session.createMessage();
      BCSAPIMessage.Ping.Builder builder = BCSAPIMessage.Ping.newBuilder();
      builder.setNonce(nonce);
      builder.setClientVersion(getClientVersion());
      m.setPayload(builder.build().toByteArray());
      ConnectorProducer pingProducer = session.createProducer(session.createQueue("ping"));
      byte[] response = synchronousRequest(session, pingProducer, m);
      if (response != null) {
        BCSAPIMessage.Ping echo = BCSAPIMessage.Ping.parseFrom(response);
        if (echo.getNonce() != nonce) {
          throw new BCSAPIException("Incorrect echo nonce from ping");
        }
        return echo;
      }
      throw new BCSAPIException("no reply");
    } catch (ConnectorException | InvalidProtocolBufferException e) {
      throw new BCSAPIException(e);
    }
  }
Esempio n. 30
0
  @Override
  public APITransaction getTransaction(TID hash) throws BCSAPIException {
    log.trace("get transaction " + hash);
    ConnectorMessage m;
    try (ConnectorSession session = connection.createSession()) {
      ConnectorProducer transactionRequestProducer =
          session.createProducer(session.createQueue("transactionRequest"));

      m = session.createMessage();
      BCSAPIMessage.Hash.Builder builder = BCSAPIMessage.Hash.newBuilder();
      builder.addHash(ByteString.copyFrom(hash.unsafeGetArray()));
      m.setPayload(builder.build().toByteArray());
      byte[] response = synchronousRequest(session, transactionRequestProducer, m);
      if (response != null) {
        APITransaction t;
        t = APITransaction.fromProtobuf(BCSAPIMessage.TX.parseFrom(response));
        return t;
      }
    } catch (ConnectorException | HyperLedgerException | InvalidProtocolBufferException e) {
      throw new BCSAPIException(e);
    }

    return null;
  }