private void init() {
   String s = settings.get(LAST_TRANSACTION_ID);
   if (s != null) {
     lastTransactionId = Long.parseLong(s);
     lastTransactionIdStored = lastTransactionId;
   }
   Long lastKey = openTransactions.lastKey();
   if (lastKey != null && lastKey.longValue() > lastTransactionId) {
     throw DataUtils.newIllegalStateException("Last transaction not stored");
   }
   Cursor<Long> cursor = openTransactions.keyIterator(null);
   while (cursor.hasNext()) {
     long id = cursor.next();
     Object[] data = openTransactions.get(id);
     int status = (Integer) data[0];
     String name = (String) data[1];
     long[] next = {id + 1, -1};
     long[] last = undoLog.floorKey(next);
     if (last == null) {
       // no entry
     } else if (last[0] == id) {
       Transaction t = new Transaction(this, id, status, name, last[1]);
       t.setStored(true);
       openTransactionMap.put(id, t);
     }
   }
 }
  @Test
  public void createTransactionFromTransparentRedirectSpecifyingLevel2Attributes() {
    TransactionRequest request =
        new TransactionRequest()
            .amount(TransactionAmount.AUTHORIZE.amount)
            .creditCard()
            .number(CreditCardNumber.VISA.number)
            .expirationDate("05/2009")
            .done();

    TransactionRequest trParams =
        new TransactionRequest()
            .type(Transaction.Type.SALE)
            .taxAmount(new BigDecimal("10.00"))
            .taxExempt(true)
            .purchaseOrderNumber("12345");

    String queryString =
        TestHelper.simulateFormPostForTR(
            gateway, trParams, request, gateway.transparentRedirect().url());
    Result<Transaction> result = gateway.transparentRedirect().confirmTransaction(queryString);

    assertTrue(result.isSuccess());
    Transaction transaction = result.getTarget();
    assertEquals(new BigDecimal("10.00"), transaction.getTaxAmount());
    assertTrue(transaction.isTaxExempt());
    assertEquals("12345", transaction.getPurchaseOrderNumber());
  }
 @Test
 public void shouldRollbackViaStatus() throws Exception {
   new TransactionTemplate(neo4jTransactionManager)
       .execute(
           new TransactionCallbackWithoutResult() {
             @Override
             protected void doInTransactionWithoutResult(final TransactionStatus status) {
               neo4jTemplate.exec(
                   new GraphCallback.WithoutResult() {
                     @Override
                     public void doWithGraphWithoutResult(GraphDatabase graph) throws Exception {
                       graph
                           .getReferenceNode()
                           .setProperty("test", "shouldRollbackTransactionOnException");
                       status.setRollbackOnly();
                     }
                   });
             }
           });
   Transaction tx = graphDatabase.beginTx();
   try {
     Assert.assertThat(
         (String) graphDatabase.getReferenceNode().getProperty("test", "not set"),
         not("shouldRollbackTransactionOnException"));
   } finally {
     tx.success();
     tx.finish();
   }
 }
 /**
  * Abort txn.
  *
  * @param txnId the id of the transaction
  * @throws js.co.uk.tuplespace.store.TransactionException the transaction exception
  */
 public synchronized Collection<TimeoutEntry<V>> abortTxn(final TransactionID txnId)
     throws TransactionException {
   final Transaction<V> txn = idToTxnMap.remove(txnId);
   final Collection<TimeoutEntry<V>> items = txn.abort();
   txnTimeoutQueue.remove(txn);
   return items;
 }
 /**
  * Prepare a transaction.
  *
  * @param transactionId the transaction id
  */
 void prepare(Transaction t) {
   storeTransaction(t);
   Object[] old = openTransactions.get(t.getId());
   Object[] v = {Transaction.STATUS_PREPARED, old[1]};
   openTransactions.put(t.getId(), v);
   store.commit();
 }
 /**
  * Updates the outputs on the payment contract transaction and re-signs it. The state must be
  * READY in order to call this method. The signature that is returned should be sent to the server
  * so it has the ability to broadcast the best seen payment when the channel closes or times out.
  *
  * <p>The returned signature is over the payment transaction, which we never have a valid copy of
  * and thus there is no accessor for it on this object.
  *
  * <p>To spend the whole channel increment by {@link PaymentChannelClientState#getTotalValue()} -
  * {@link PaymentChannelClientState#getValueRefunded()}
  *
  * @param size How many satoshis to increment the payment by (note: not the new total).
  * @throws ValueOutOfRangeException If size is negative or the channel does not have sufficient
  *     money in it to complete this payment.
  */
 public synchronized IncrementedPayment incrementPaymentBy(Coin size)
     throws ValueOutOfRangeException {
   checkState(state == State.READY);
   checkNotExpired();
   checkNotNull(size); // Validity of size will be checked by makeUnsignedChannelContract.
   if (size.signum() < 0) throw new ValueOutOfRangeException("Tried to decrement payment");
   Coin newValueToMe = valueToMe.subtract(size);
   if (newValueToMe.compareTo(Transaction.MIN_NONDUST_OUTPUT) < 0 && newValueToMe.signum() > 0) {
     log.info(
         "New value being sent back as change was smaller than minimum nondust output, sending all");
     size = valueToMe;
     newValueToMe = Coin.ZERO;
   }
   if (newValueToMe.signum() < 0)
     throw new ValueOutOfRangeException(
         "Channel has too little money to pay " + size + " satoshis");
   Transaction tx = makeUnsignedChannelContract(newValueToMe);
   log.info("Signing new payment tx {}", tx);
   Transaction.SigHash mode;
   // If we spent all the money we put into this channel, we (by definition) don't care what the
   // outputs are, so
   // we sign with SIGHASH_NONE to let the server do what it wants.
   if (newValueToMe.equals(Coin.ZERO)) mode = Transaction.SigHash.NONE;
   else mode = Transaction.SigHash.SINGLE;
   TransactionSignature sig = tx.calculateSignature(0, myKey, multisigScript, mode, true);
   valueToMe = newValueToMe;
   updateChannelInWallet();
   IncrementedPayment payment = new IncrementedPayment();
   payment.signature = sig;
   payment.amount = size;
   return payment;
 }
 private static void sendTransactionsToListener(
     StoredBlock block,
     NewBlockType blockType,
     BlockChainListener listener,
     int relativityOffset,
     List<Transaction> transactions,
     boolean clone,
     Set<Sha256Hash> falsePositives)
     throws VerificationException {
   for (Transaction tx : transactions) {
     try {
       if (listener.isTransactionRelevant(tx)) {
         falsePositives.remove(tx.getHash());
         if (clone) tx = new Transaction(tx.params, tx.bitcoinSerialize());
         listener.receiveFromBlock(tx, block, blockType, relativityOffset++);
       }
     } catch (ScriptException e) {
       // We don't want scripts we don't understand to break the block chain so just note that this
       // tx was
       // not scanned here and continue.
       log.warn("Failed to parse a script: " + e.toString());
     } catch (ProtocolException e) {
       // Failed to duplicate tx, should never happen.
       throw new RuntimeException(e);
     }
   }
 }
Example #8
0
  @Override
  public List<Forum> getForumsOfaUser(int userId) {
    // TODO Auto-generated method stub
    List<Forum> forums = new ArrayList<Forum>();
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();
      Query query = session.createQuery("from Subscription where userId = :userId");
      query.setString("userId", String.valueOf(userId));
      List<Subscription> userSubscribedGroups = query.list();
      for (Subscription subsc : userSubscribedGroups) {
        query = session.createQuery("from Forum where forumId = :forumId");
        query.setParameter("forumId", subsc.getForumId());
        // add this to a list variable query.uniqueResult();
        forums.add((Forum) query.uniqueResult());
      }

    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
        e.printStackTrace();
      }
    } finally {
      session.close();
    }
    return forums;
  }
Example #9
0
  public int getCountOfSubscribers(int forumId, int userId) {
    // TODO Auto-generated method stub
    Session session = this.sessionFactory.openSession();
    Transaction tx = null;
    int countOfSubscribers = 0;
    try {
      tx = session.beginTransaction();
      Query query = null;
      if (userId == 0) {
        query = session.createQuery("select count(*) from Subscription where forumId = :forumId");
        query.setParameter("forumId", forumId);
      } else {
        query =
            session.createQuery(
                "select count(*) from Subscription where forumId = :forumId and userId = :userId");
        query.setParameter("forumId", forumId);
        query.setParameter("userId", userId);
      }

      Long count = (Long) query.uniqueResult();
      countOfSubscribers = count.intValue();
      // System.out.println("No of subscribers.."+countOfSubscribers);
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
        e.printStackTrace();
      }
    } finally {
      session.close();
    }
    return countOfSubscribers;
  }
  @Test
  public void testCreateRelationship() {
    Node n1 = restAPI.createNode(map("name", "newnode1"));
    final Transaction tx = restAPI.beginTx();

    Node n2 = restAPI.createNode(map("name", "newnode2"));
    RestRelationship rel = restAPI.createRelationship(n1, n2, Type.TEST, map("name", "rel"));
    Iterable<Relationship> allRelationships = n1.getRelationships();

    tx.success();
    tx.finish();
    Relationship foundRelationship =
        TestHelper.firstRelationshipBetween(
            n1.getRelationships(Type.TEST, Direction.OUTGOING), n1, n2);
    Assert.assertNotNull("found relationship", foundRelationship);
    assertEquals("same relationship", rel, foundRelationship);
    assertEquals("rel", rel.getProperty("name"));

    assertThat(
        n1.getRelationships(Type.TEST, Direction.OUTGOING),
        new IsRelationshipToNodeMatcher(n1, n2));
    assertThat(n1.getRelationships(Direction.OUTGOING), new IsRelationshipToNodeMatcher(n1, n2));
    assertThat(n1.getRelationships(Direction.BOTH), new IsRelationshipToNodeMatcher(n1, n2));
    assertThat(n1.getRelationships(Type.TEST), new IsRelationshipToNodeMatcher(n1, n2));
    assertThat(allRelationships, new IsRelationshipToNodeMatcher(n1, n2));
  }
Example #11
0
  public void rn() throws IOException {
    List<RoadLink> links = loadToDatabase("/Users/duduba/gj.mif", "/Users/duduba/gj.mid", false);

    GraphDatabaseService graphDb = neo.getDb();
    Index<Node> nodeIndex = neo.getNodeIndex();

    for (RoadLink link : links) {
      Transaction tx = graphDb.beginTx();
      try {

        Node fromNode = nodeIndex.get("id", link.fromNode).getSingle();
        if (fromNode == null) {
          fromNode = graphDb.createNode();
          fromNode.setProperty("id", link.fromNode);
          nodeIndex.add(fromNode, "id", link.fromNode);
        }
        Node toNode = nodeIndex.get("id", link.toNode).getSingle();
        if (toNode == null) {
          toNode = graphDb.createNode();
          toNode.setProperty("id", link.toNode);
          nodeIndex.add(toNode, "id", link.toNode);
        }

        Relationship r = fromNode.createRelationshipTo(toNode, Neo.RelTypes.TO);
        r.setProperty("no", link.no);
        r.setProperty("name", link.name);

        tx.success();
      } finally {
        tx.finish();
      }
    }
    logger.debug("haha, it's ok!");
  }
  @Test
  public void createTransactionFromTransparentRedirectSpecifyingDescriptor() {
    TransactionRequest request =
        new TransactionRequest()
            .amount(TransactionAmount.AUTHORIZE.amount)
            .creditCard()
            .number(CreditCardNumber.VISA.number)
            .expirationDate("05/2009")
            .done();

    TransactionRequest trParams =
        new TransactionRequest()
            .type(Transaction.Type.SALE)
            .descriptor()
            .name("123*123456789012345678")
            .phone("3334445555")
            .done();

    String queryString =
        TestHelper.simulateFormPostForTR(
            gateway, trParams, request, gateway.transparentRedirect().url());
    Result<Transaction> result = gateway.transparentRedirect().confirmTransaction(queryString);

    assertTrue(result.isSuccess());
    Transaction transaction = result.getTarget();
    assertEquals("123*123456789012345678", transaction.getDescriptor().getName());
    assertEquals("3334445555", transaction.getDescriptor().getPhone());
  }
Example #13
0
 private static Block createGenesis(NetworkParameters n) {
   Block genesisBlock = new Block(n);
   Transaction t = new Transaction(n);
   try {
     // A script containing the difficulty bits and the following message:
     //
     //   "Mar-17-2014 Harvard Scientists: First Direct Evidence of Cosmic Inflation"
     byte[] bytes =
         Hex.decode(
             "04ffff001d0104494d61722d31372d32303134204861727661726420536369656e74697374733a204669727374204469726563742045766964656e6365206f6620436f736d696320496e666c6174696f6e");
     t.addInput(new TransactionInput(n, t, bytes));
     ByteArrayOutputStream scriptPubKeyBytes = new ByteArrayOutputStream();
     Script.writeBytes(
         scriptPubKeyBytes,
         Hex.decode(
             "04c6c6a01450f2b8bbb176b98f593623b04a5f5761a7d0adae4d21f77c366e01e147217a9d8864a871d95d182e01d2b003168f0fa7851278a86ac0aa682919f9a6"));
     scriptPubKeyBytes.write(ScriptOpCodes.OP_CHECKSIG);
     t.addOutput(
         new TransactionOutput(n, t, Utils.toNanoCoins(1, 0), scriptPubKeyBytes.toByteArray()));
   } catch (Exception e) {
     // Cannot happen.
     throw new RuntimeException(e);
   }
   genesisBlock.addTransaction(t);
   return genesisBlock;
 }
  /** {@inheritDoc} */
  @Override
  public void txEnd(GridCacheTx tx, boolean commit) throws GridException {
    init();

    Session ses = tx.removeMeta(ATTR_SES);

    if (ses != null) {
      Transaction hTx = ses.getTransaction();

      if (hTx != null) {
        try {
          if (commit) {
            ses.flush();

            hTx.commit();
          } else hTx.rollback();

          if (log.isDebugEnabled())
            log.debug("Transaction ended [xid=" + tx.xid() + ", commit=" + commit + ']');
        } catch (HibernateException e) {
          throw new GridException(
              "Failed to end transaction [xid=" + tx.xid() + ", commit=" + commit + ']', e);
        } finally {
          ses.close();
        }
      }
    }
  }
  public boolean sendCoinsMulti(Map<Address, Double> toSend) {
    Transaction tx = new Transaction(Craftcoinish.network);
    double totalSend = 0.0;

    for (Entry<Address, Double> current : toSend.entrySet()) {
      totalSend += current.getValue() / Craftcoinish.mult;
      tx.addOutput(Craftcoinish.econ.inGameToBitcoin(current.getValue()), current.getKey());
    }

    if (totalSend < 0.01) {
      return false;
    }

    Wallet.SendRequest request = Wallet.SendRequest.forTx(tx);

    if (!localWallet.completeTx(request)) {
      return false;
    } else {
      localPeerGroup.broadcastTransaction(request.tx);
      try {
        localWallet.commitTx(request.tx);
      } catch (VerificationException e) {
        e.printStackTrace();
      }
      return true;
    }
  }
Example #16
0
 @Override
 public List<Reply> getRepliesToPost(int postId) {
   // TODO Auto-generated method stub
   Session session = sessionFactory.openSession();
   Transaction tx = null;
   List<Reply> replyArr = new ArrayList<Reply>();
   try {
     tx = session.beginTransaction();
     Query query =
         session.createQuery("from Reply where postId = :postId order by createdDate desc");
     query.setParameter("postId", postId);
     replyArr = query.list();
     /*			for(Reply reply : replyArr){
     	System.out.println("Reply - id----"+reply.getReplyId());
     	System.out.println("Reply - Description----"+reply.getDescription());
     	System.out.println("Reply - Post id----"+reply.getPostId());
     }*/
   } catch (HibernateException e) {
     if (tx != null) {
       tx.rollback();
       e.printStackTrace();
     }
   } finally {
     session.close();
   }
   return replyArr;
 }
Example #17
0
 @Override
 public void deleteSubscription(int userId, int forumId) {
   // TODO Auto-generated method stub
   Session session = this.sessionFactory.openSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     Query query =
         session.createQuery(
             "delete from Subscription where userId = :userId and forumId = :forumId");
     query.setParameter("userId", userId);
     query.setParameter("forumId", forumId);
     int result = query.executeUpdate();
     System.out.println("Execute query..");
     if (result > 0) {
       tx.commit();
       // System.out.println("Subscription Removed..");
     } else {
       // System.out.println("Subscription does not exist");
       tx.rollback();
     }
   } catch (HibernateException e) {
     if (tx != null) {
       tx.rollback();
       e.printStackTrace();
     }
   } finally {
     session.close();
   }
 }
  @Test
  public void testAddToIndex() {
    final MatrixDataGraph matrixDataGraph = new MatrixDataGraph(getGraphDatabase());
    matrixDataGraph.createNodespace();
    final RestNode neoNode = restAPI.getNodeById(matrixDataGraph.getNeoNode().getId());

    final Transaction tx = restAPI.beginTx();
    restAPI.index().forNodes("heroes").add(neoNode, "indexname", "Neo2");
    Node n1 = restAPI.createNode(map("name", "Apoc"));
    final Index<Node> index = restAPI.index().forNodes("heroes");
    index.add(n1, "indexname", "Apoc");
    final Node indexResult =
        getGraphDatabase().index().forNodes("heroes").get("indexname", "Neo2").getSingle();
    assertNull(indexResult);
    final IndexHits<Node> heroes = index.query("indexname:Apoc");
    tx.success();
    tx.finish();
    assertEquals("1 hero", 1, heroes.size());
    IndexManager realIndex = getGraphDatabase().index();
    Index<Node> goodGuys = realIndex.forNodes("heroes");
    IndexHits<Node> hits = goodGuys.get("indexname", "Apoc");
    Node apoc = hits.getSingle();

    assertEquals("Apoc indexed", apoc, heroes.iterator().next());
  }
Example #19
0
  @Override
  public void saveEventDetails(Event event) {
    // TODO Auto-generated method stub

    // Opening a session to create a database connection
    Session session = this.sessionFactory.openSession();

    // for CRUD operations, we need to create a transaction
    Transaction tx = null;

    // adding a try catch block for maintaining the atomicity of transaction
    try {
      tx = session.beginTransaction();
      System.out.println("DbHelper..saveEventDetails");

      // session save inserts the object into DB
      session.save(event);

      tx.commit();
      System.out.println("Event saved");
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
        e.printStackTrace();
      }
    } finally {
      session.close();
    }
  }
Example #20
0
 public void save(Treatment treatment) {
   Session session = this.sessionFactory.openSession();
   Transaction tx = session.beginTransaction();
   session.persist(treatment);
   tx.commit();
   session.close();
 }
Example #21
0
 public List<User> getUserSearchResults(int topicId) {
   // TODO Auto-generated method stub
   List<User> userArr = new ArrayList<User>();
   Session session = sessionFactory.openSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     Query query1 = session.createQuery("select userId from UserTopic where topicId = :topicId");
     query1.setString("topicId", String.valueOf(topicId));
     Query query2 = session.createQuery("from User where userId in (:userList)");
     query2.setParameterList("userList", query1.list());
     userArr = query2.list();
     /*for(Topic topic : topicArr){
     	System.out.println("Topic Description----"+topic.getTopicDescription());
     	System.out.println("Topic Id----"+topic.getTopicId());
     }*/
   } catch (HibernateException e) {
     if (tx != null) {
       tx.rollback();
       e.printStackTrace();
     }
   } finally {
     session.close();
   }
   return userArr;
 }
        public void onTransactionCreate(final TransactionBuildUpEvent<BaseSipMessage> event) {
          assert SIP_REINVITE_CLIENT == event.getTransaction().getTransactionType();

          Dialog dialog = (Dialog) event.getEntity();
          final Transaction<Boolean, BaseSipMessage> transaction = event.getTransaction();

          // DIALOG.putCustomParameter(Dialog.ParamKey.REINVITE_IN_PROGRESS, Boolean.TRUE);
          dialog.markReInviteInProgress(InitiateParty.LOCAL);

          // listener will un-subscribe automatically on transaction complete
          transaction.addListener(new AuthChallengeListener<BaseSipMessage>(transaction, dialog));
          // listener will un-subscribe automatically on transaction complete
          transaction.addListener(
              new MiddleManForClientMessageBuildingSupport<BaseSipMessage>(transaction, dialog));
          // listener will un-subscribe automatically on transaction complete
          transaction.addListener(
              new ReInviteStateMiddleMan<BaseSipMessage>(
                  transaction, dialog, dialogStateListenerHolder) {

                protected void onDialogCleanUp(final Dialog dialog) {
                  getStackContext().getDialogStorage().cleanUpDialog(dialog);
                }
              });
          // listener will un-subscribe automatically on transaction complete
          transaction.addListener(
              new ReinviteInProgressListener<BaseSipMessage>(
                  transaction, dialog, InitiateParty.LOCAL));
        }
 /**
  * When the servers signature for the refund transaction is received, call this to verify it and
  * sign the complete refund ourselves.
  *
  * <p>If this does not throw an exception, we are secure against the loss of funds and can safely
  * provide the server with the multi-sig contract to lock in the agreement. In this case, both the
  * multisig contract and the refund transaction are automatically committed to wallet so that it
  * can handle broadcasting the refund transaction at the appropriate time if necessary.
  */
 public synchronized void provideRefundSignature(byte[] theirSignature)
     throws VerificationException {
   checkNotNull(theirSignature);
   checkState(state == State.WAITING_FOR_SIGNED_REFUND);
   TransactionSignature theirSig = TransactionSignature.decodeFromBitcoin(theirSignature, true);
   if (theirSig.sigHashMode() != Transaction.SigHash.NONE || !theirSig.anyoneCanPay())
     throw new VerificationException("Refund signature was not SIGHASH_NONE|SIGHASH_ANYONECANPAY");
   // Sign the refund transaction ourselves.
   final TransactionOutput multisigContractOutput = multisigContract.getOutput(0);
   try {
     multisigScript = multisigContractOutput.getScriptPubKey();
   } catch (ScriptException e) {
     throw new RuntimeException(e); // Cannot happen: we built this ourselves.
   }
   TransactionSignature ourSignature =
       refundTx.calculateSignature(0, myKey, multisigScript, Transaction.SigHash.ALL, false);
   // Insert the signatures.
   Script scriptSig = ScriptBuilder.createMultiSigInputScript(ourSignature, theirSig);
   log.info("Refund scriptSig: {}", scriptSig);
   log.info("Multi-sig contract scriptPubKey: {}", multisigScript);
   TransactionInput refundInput = refundTx.getInput(0);
   refundInput.setScriptSig(scriptSig);
   refundInput.verify(multisigContractOutput);
   state = State.SAVE_STATE_IN_WALLET;
 }
        public void onTransactionCreate(final TransactionBuildUpEvent<BaseSipMessage> event) {
          assert SIP_UPDATE_SERVER == event.getTransaction().getTransactionType();

          Dialog dialog = (Dialog) event.getEntity();
          final Transaction<Boolean, BaseSipMessage> transaction = event.getTransaction();

          // DIALOG.putCustomParameter(Dialog.ParamKey.REINVITE_IN_PROGRESS, Boolean.TRUE);
          // TODo reinvire is used for update too
          // dialog.markReInviteInProgress(InitiateParty.REMOTE);

          // listener will un-subscribe automatically on transaction complete

          transaction.addListener(
              new IncomingReInviteListener<BaseSipMessage>(
                  dialog,
                  createSafeInviteAcceptable(dialog),
                  transaction,
                  incomingCallListenerHolder));

          transaction.addListener(
              new DialogStateMiddleMan<BaseSipMessage>(
                  transaction, dialog, dialogStateListenerHolder));

          // listener will un-subscribe automatically on transaction complete
          transaction.addListener(
              new MiddleManForServerMessageBuildingSupport(transaction, dialog));

          transaction.addListener(
              new UpdateInProgressListener<BaseSipMessage>(
                  transaction, dialog, InitiateParty.REMOTE));
        }
  /**
   * This method collects payment for the current transaction.
   *
   * @param amount the amount of money collected from the customer.
   * @param payment no idea what this is (TODO: ask about class diagram)
   * @return no idea what this is suppose to return.
   * @throws SQLException if sql error.
   * @throws ClassNotFoundException if sql error.
   * @throws IllegalStateException if there are no items on the invoice.
   */
  public double pay(String paymentMethod, int amount)
      throws IllegalStateException, SQLException, ClassNotFoundException, Exception {
    if (myTransaction.getNumberOfItems() == 0) {
      throw new IllegalStateException("There are no items on the Invoice.");
    }
    JDBCConnection JDBC = new JDBCConnection();
    Statement st = JDBC.createStatement();
    String table = "invoice";
    String column = "invoiceID";
    String SQL = "SELECT " + column + " FROM " + table + " GROUP BY " + column;
    ResultSet rs = st.executeQuery(SQL);
    // rs.last();
    int nextInvoiceID = 0;
    if (rs.last()) {
      int LastID = rs.getInt(column);
      nextInvoiceID = LastID + 1;
    }

    // use these two lines if you want invoices to be numbered 1000 and up
    // int starting = 999;
    // int nextInvoiceID = mySQLhelper.getTotalNumberOfInvoices() + 1;
    //		int nextInvoiceID = mySQLhelper.getTotalNumberOfRows(SQLhelper.TRANSACTION_TABLE_NAME,
    // SQLhelper.TRANSACTION_TABLE_PK) + 1;
    // Payment myPayment = new Payment(amount, paymentMethod);
    double change = myTransaction.markPaid(paymentMethod, amount, nextInvoiceID);
    myTransaction.UpdateItem();
    process();
    return change;
  }
Example #26
0
 private Node createLabeledNode(Label... labels) {
   try (Transaction tx = dbRule.getGraphDatabaseService().beginTx()) {
     Node node = dbRule.getGraphDatabaseService().createNode(labels);
     tx.success();
     return node;
   }
 }
Example #27
0
 public synchronized void queueTransaction(Transaction transaction) {
   // Store transaction in outgoing buffer, so we can broadcast it
   // later
   byte[] rawTransaction = transaction.toBytes();
   _backing.putOutgoingTransaction(transaction.getHash(), rawTransaction);
   markTransactionAsSpent(transaction);
 }
Example #28
0
 @Override
 public synchronized boolean deleteTransaction(Sha256Hash transactionId) {
   TransactionEx tex = _backing.getTransaction(transactionId);
   if (tex == null) return false;
   Transaction tx = TransactionEx.toTransaction(tex);
   _backing.beginTransaction();
   try {
     // See if any of the outputs are stored locally and remove them
     for (int i = 0; i < tx.outputs.length; i++) {
       TransactionOutput output = tx.outputs[i];
       OutPoint outPoint = new OutPoint(tx.getHash(), i);
       TransactionOutputEx utxo = _backing.getUnspentOutput(outPoint);
       if (utxo != null) {
         _backing.deleteUnspentOutput(outPoint);
       }
     }
     // remove it from the backing
     _backing.deleteTransaction(transactionId);
     _backing.setTransactionSuccessful();
   } finally {
     _backing.endTransaction();
   }
   updateLocalBalance(); // will still need a new sync besides re-calculating
   return true;
 }
  /**
   * Called when the client provides the multi-sig contract. Checks that the previously-provided
   * refund transaction spends this transaction (because we will use it as a base to create payment
   * transactions) as well as output value and form (ie it is a 2-of-2 multisig to the correct
   * keys).
   *
   * @param multisigContract The provided multisig contract. Do not mutate this object after this
   *     call.
   * @return A future which completes when the provided multisig contract successfully broadcasts,
   *     or throws if the broadcast fails for some reason Note that if the network simply rejects
   *     the transaction, this future will never complete, a timeout should be used.
   * @throws VerificationException If the provided multisig contract is not well-formed or does not
   *     meet previously-specified parameters
   */
  public synchronized ListenableFuture<PaymentChannelServerState> provideMultiSigContract(
      final Transaction multisigContract) throws VerificationException {
    checkNotNull(multisigContract);
    checkState(state == State.WAITING_FOR_MULTISIG_CONTRACT);
    try {
      multisigContract.verify();
      this.multisigContract = multisigContract;
      this.multisigScript = multisigContract.getOutput(0).getScriptPubKey();

      // Check that multisigContract's first output is a 2-of-2 multisig to the correct pubkeys in
      // the correct order
      final Script expectedScript =
          ScriptBuilder.createMultiSigOutputScript(2, Lists.newArrayList(clientKey, serverKey));
      if (!Arrays.equals(multisigScript.getProgram(), expectedScript.getProgram()))
        throw new VerificationException(
            "Multisig contract's first output was not a standard 2-of-2 multisig to client and server in that order.");

      this.totalValue = multisigContract.getOutput(0).getValue();
      if (this.totalValue.signum() <= 0)
        throw new VerificationException(
            "Not accepting an attempt to open a contract with zero value.");
    } catch (VerificationException e) {
      // We couldn't parse the multisig transaction or its output.
      log.error("Provided multisig contract did not verify: {}", multisigContract.toString());
      throw e;
    }
    log.info("Broadcasting multisig contract: {}", multisigContract);
    state = State.WAITING_FOR_MULTISIG_ACCEPTANCE;
    final SettableFuture<PaymentChannelServerState> future = SettableFuture.create();
    Futures.addCallback(
        broadcaster.broadcastTransaction(multisigContract).future(),
        new FutureCallback<Transaction>() {
          @Override
          public void onSuccess(Transaction transaction) {
            log.info(
                "Successfully broadcast multisig contract {}. Channel now open.",
                transaction.getHashAsString());
            try {
              // Manually add the multisigContract to the wallet, overriding the isRelevant checks
              // so we can track
              // it and check for double-spends later
              wallet.receivePending(multisigContract, null, true);
            } catch (VerificationException e) {
              throw new RuntimeException(
                  e); // Cannot happen, we already called multisigContract.verify()
            }
            state = State.READY;
            future.set(PaymentChannelServerState.this);
          }

          @Override
          public void onFailure(Throwable throwable) {
            // Couldn't broadcast the transaction for some reason.
            log.error("Broadcast multisig contract failed", throwable);
            state = State.ERROR;
            future.setException(throwable);
          }
        });
    return future;
  }
Example #30
0
  /**
   * Reads in external transaction file that the user chooses to import.
   *
   * @param splitFile - file that user chooses to upload.
   * @return - arraylist containing the user's imported holdings. Created by: Kimberly Sookoo.
   */
  public static ArrayList<Transaction> readTransactionImports(ArrayList<String[]> splitFile) {

    ArrayList<Transaction> allTransactions = new ArrayList<>();

    for (String[] line : splitFile) {
      Date date = null;
      try {
        date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(line[2]);
      } catch (ParseException e) {
        e.printStackTrace();
      }
      double amount = Double.parseDouble(line[1]);
      // (double amount, String dateMade, String type, String cashAccountName) {

      String cashAccountName = line[0];
      String type = line[3];
      Transaction trans;
      if (type.equals("Withdrawal")) {
        trans = new Withdrawal(amount, date);
        trans.setCashAccountName(cashAccountName);
      } else { // if(stringType.equals("Deposit")){
        trans = new Deposit(amount, date);
        trans.setCashAccountName(cashAccountName);
      }

      allTransactions.add(trans);
    }

    return allTransactions;
  }