예제 #1
0
  public static void main(String args[]) {
    Database database;

    database = Database.getInstance("products");

    System.out.println("This is the " + database.getName() + " databse.");

    database = Database.getInstance("employees");

    System.out.println("This is the " + database.getName() + " databse.");
  }
예제 #2
0
 public static void updateLastParsedBlock(Integer block_index) {
   Database db = Database.getInstance();
   db.executeUpdate(
       "REPLACE INTO sys_parameters (para_name,para_value) values ('last_parsed_block','"
           + block_index.toString()
           + "');");
 }
예제 #3
0
 public static BigInteger getBalance(String address, String asset) {
   Database db = Database.getInstance();
   Blocks blocks = Blocks.getInstance();
   if (asset.equals("BTC")) {
     /*
     BigInteger totalBalance = BigInteger.ZERO;
     LinkedList<TransactionOutput> unspentOutputs = blocks.wallet.calculateAllSpendCandidates(true);
     Set<Transaction> txs = blocks.wallet.getTransactions(true);
     for (TransactionOutput out : unspentOutputs) {
     	Script script = out.getScriptPubKey();
     	if (script.getToAddress(blocks.params).toString().equals(address) && out.isAvailableForSpending()) {
     		totalBalance = totalBalance.add(out.getValue());
     	}
     }
     return totalBalance;
      */
     return getBTCBalance(address);
   } else {
     ResultSet rs =
         db.executeQuery(
             "select sum(amount) as amount from balances where address='"
                 + address
                 + "' and asset='"
                 + asset
                 + "';");
     try {
       if (rs.next()) {
         return BigInteger.valueOf(rs.getLong("amount"));
       }
     } catch (SQLException e) {
     }
   }
   return BigInteger.ZERO;
 }
예제 #4
0
 public static BigInteger nbcSupply() {
   Database db = Database.getInstance();
   ResultSet rs = db.executeQuery("select sum(amount) as amount from balances where asset='NBC';");
   try {
     if (rs.next()) {
       return BigInteger.valueOf(rs.getLong("amount"));
     }
   } catch (SQLException e) {
   }
   return BigInteger.ZERO;
 }
예제 #5
0
 public static Integer getLastBlockTimestamp() {
   Database db = Database.getInstance();
   ResultSet rs = db.executeQuery("select * from blocks order by block_index desc limit 1;");
   try {
     while (rs.next()) {
       return rs.getInt("block_time");
     }
   } catch (SQLException e) {
   }
   return 0;
 }
예제 #6
0
 /**
  * fetch this items tags from the database. should be called AT MOST once per item.
  *
  * @throws Exception General sql errors (Should not be raised)
  */
 public final void fetchTags() throws Exception {
   Connection conn = Database.getInstance().getConnection();
   String query = "SELECT * FROM itemtags WHERE itemid = ?";
   PreparedStatement st = conn.prepareStatement(query);
   st.setInt(1, id);
   ResultSet rs = st.executeQuery();
   while (rs.next()) {
     tags.add(rs.getString(2));
   }
   conn.close();
 }
예제 #7
0
 public static Integer getLastBlock() {
   Blocks blocks = Blocks.getInstance();
   Database db = Database.getInstance();
   ResultSet rs = db.executeQuery("select * from blocks order by block_index desc limit 1;");
   try {
     while (rs.next()) {
       return rs.getInt("block_index");
     }
   } catch (SQLException e) {
   }
   return blocks.newbiecoinBlock;
 }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.conversations);

    gcm = Gcm.getInstance(getApplicationContext());
    billing = Billing.getInstance(getApplicationContext());
    database = Database.getInstance(getApplicationContext());
    preferences = Preferences.getInstance(getApplicationContext());

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    ViewCompat.setElevation(toolbar, getResources().getDimension(R.dimen.toolbar_elevation));
    setSupportActionBar(toolbar);

    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    adapter = new ConversationsRecyclerViewAdapter(this, layoutManager);
    recyclerView = (RecyclerView) findViewById(R.id.list);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);

    actionMode = null;
    actionModeEnabled = false;

    SwipeRefreshLayout swipeRefreshLayout =
        (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    swipeRefreshLayout.setOnRefreshListener(
        new SwipeRefreshLayout.OnRefreshListener() {
          @Override
          public void onRefresh() {
            preFullUpdate();
          }
        });
    swipeRefreshLayout.setColorSchemeResources(R.color.accent);

    ImageButton button = (ImageButton) findViewById(R.id.new_button);
    ViewCompat.setElevation(button, getResources().getDimension(R.dimen.fab_elevation));
    button.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            if (!preferences.getEmail().equals("")
                && !preferences.getPassword().equals("")
                && !preferences.getDid().equals("")) {
              Intent intent = new Intent(conversationsActivity, NewConversationActivity.class);
              startActivity(intent);
            }
          }
        });

    SynchronizationIntervalReceiver.setupSynchronizationInterval(getApplicationContext());
  }
예제 #9
0
 public static Integer getLastParsedBlock() {
   Database db = Database.getInstance();
   ResultSet rs =
       db.executeQuery(
           "SELECT para_value FROM sys_parameters WHERE para_name='last_parsed_block'");
   try {
     while (rs.next()) {
       return rs.getInt("para_value");
     }
   } catch (SQLException e) {
   }
   return 0;
 }
예제 #10
0
 public static Integer getLastTxIndex() {
   Database db = Database.getInstance();
   ResultSet rs =
       db.executeQuery(
           "SELECT * FROM transactions WHERE tx_index = (SELECT MAX(tx_index) from transactions);");
   try {
     while (rs.next()) {
       return rs.getInt("tx_index");
     }
   } catch (SQLException e) {
   }
   return 0;
 }
예제 #11
0
 public static String getBlockHash(Integer blockIndex) {
   Database db = Database.getInstance();
   ResultSet rs =
       db.executeQuery(
           "select block_hash from blocks where block_index='" + blockIndex.toString() + "';");
   try {
     if (rs.next()) {
       return rs.getString("block_hash");
     }
   } catch (SQLException e) {
   }
   return null;
 }
예제 #12
0
 public static BigInteger btcBurned(String destination) {
   Database db = Database.getInstance();
   ResultSet rs =
       db.executeQuery(
           "select sum(burned) as amount from burns "
               + (destination == null ? "" : " where destination='" + destination + "'")
               + ";");
   try {
     if (rs.next()) {
       return BigInteger.valueOf(rs.getLong("amount"));
     }
   } catch (SQLException e) {
   }
   return BigInteger.ZERO;
 }
 public static void main(String[] args) {
   Database.getInstance();
   LoginFrame frame = new LoginFrame();
   frame.setLocation(300, 300);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setVisible(true);
   Runtime.getRuntime()
       .addShutdownHook(
           new Thread(
               new Runnable() {
                 public void run() {
                   Database.closeConnection();
                 }
               },
               "Shutdown-thread"));
 }
예제 #14
0
 public static Boolean hasBalance(String address, String asset) {
   Database db = Database.getInstance();
   ResultSet rs =
       db.executeQuery(
           "select amount from balances where address='"
               + address
               + "' and asset='"
               + asset
               + "';");
   try {
     if (rs.next()) {
       return true;
     }
   } catch (SQLException e) {
   }
   return false;
 }
예제 #15
0
 public static void credit(
     String address,
     String asset,
     BigInteger amount,
     String callingFunction,
     String event,
     Integer blockIndex) {
   Database db = Database.getInstance();
   if (hasBalance(address, asset)) {
     BigInteger existingAmount = getBalance(address, asset);
     BigInteger newAmount = existingAmount.add(amount);
     db.executeUpdate(
         "update balances set amount='"
             + newAmount.toString()
             + "' where address='"
             + address
             + "' and asset='"
             + asset
             + "';");
   } else {
     db.executeUpdate(
         "insert into balances(address, asset, amount) values('"
             + address
             + "','"
             + asset
             + "','"
             + amount.toString()
             + "');");
   }
   db.executeUpdate(
       "insert into credits(address, asset, amount, calling_function, event, block_index) values('"
           + address
           + "','"
           + asset
           + "','"
           + amount.toString()
           + "', '"
           + callingFunction
           + "', '"
           + event
           + "', '"
           + blockIndex.toString()
           + "');");
 }
예제 #16
0
  public static BigInteger getReserved(String address, String asset) {
    Database db = Database.getInstance();
    Blocks blocks = Blocks.getInstance();

    ResultSet rs =
        db.executeQuery(
            "select sum(give_amount) as amount from orders  where source='"
                + address
                + "' and give_asset='"
                + asset
                + "' and validity='valid'");
    try {
      if (rs.next()) {
        return BigInteger.valueOf(rs.getLong("amount"));
      }
    } catch (SQLException e) {
    }

    return BigInteger.ZERO;
  }
예제 #17
0
/** Created by hengguancui on 10/7/15. tests logging to a file */
public class DatabaseTest {
  private static Logger logger = LogManager.getLogger(Database.class);
  private Database dataModel = Database.getInstance();

  @org.junit.Test
  public void testUpdateEntry() throws Exception {
    TreeMap<String, ContactEntry> dataTree = dataModel.getTreeMap();
    dataTree.put("testOne", new ContactEntry("testOne", "123 456 7890"));
    dataModel.updateEntry("testOne", "7890 123 456");

    assertEquals(dataTree.get("testOne").getNumber(), "7890 123 456");
    logger.info("UpdateEntry testcase passed!");
  }

  @org.junit.Test
  public void testWriteData() throws Exception {
    logger.info("WriteDate testcase passed!");
  }

  @org.junit.Test
  public void testReadData() throws Exception {
    logger.info("ReadData testcase passed!");
  }
}
예제 #18
0
  public static void resolve() {
    // resolve bets

    logger.info("Resolving bets");

    Database db = Database.getInstance();
    ResultSet rs =
        db.executeQuery(
            "select block_time,blocks.block_index as block_index,tx_index,tx_hash,source,bet,payout,chance,cha_supply from bets,blocks where bets.block_index=blocks.block_index and bets.validity='valid' and bets.resolved IS NOT 'true';");
    // if (true) return;

    SimpleDateFormat dateFormatStandard = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    SimpleDateFormat dateFormatDateTimeLotto = new SimpleDateFormat("MM/dd/yyyy HH:mm");
    SimpleDateFormat dateFormatDateLotto = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat dateFormatHour = new SimpleDateFormat("HH");
    SimpleDateFormat dateFormatMinute = new SimpleDateFormat("mm");
    TimeZone newYork = TimeZone.getTimeZone("America/New_York");
    TimeZone UTC = TimeZone.getTimeZone("UTC");
    dateFormatStandard.setTimeZone(UTC);
    dateFormatDateLotto.setTimeZone(newYork);
    dateFormatDateTimeLotto.setTimeZone(newYork);
    dateFormatHour.setTimeZone(newYork);
    dateFormatMinute.setTimeZone(newYork);

    try {
      while (rs.next()) {
        String source = rs.getString("source");
        String txHash = rs.getString("tx_hash");
        Integer txIndex = rs.getInt("tx_index");
        Integer blockIndex = rs.getInt("block_index");
        BigInteger bet = BigInteger.valueOf(rs.getLong("bet"));
        Double payout = rs.getDouble("payout");
        Double chance = rs.getDouble("chance");
        BigInteger chaSupply = BigInteger.valueOf(rs.getLong("cha_supply"));
        Date blockTime = new Date((long) rs.getLong("block_time") * 1000);

        logger.info("Attempting to resolve bet " + txHash);

        String lottoDate = dateFormatDateLotto.format(blockTime);
        Integer hour = Integer.parseInt(dateFormatHour.format(blockTime));
        Integer minute = Integer.parseInt(dateFormatMinute.format(blockTime));
        if (hour >= 23 && minute >= 56) {
          lottoDate = dateFormatDateLotto.format(addDays(blockTime, 1));
        }
        String lottoUrl =
            "http://nylottery.ny.gov/wps/PA_NYSLNumberCruncher/NumbersServlet?game=quick&action=winningnumbers&startSearchDate="
                + lottoDate
                + "&endSearchDate=&pageNo=&last=&perPage=999&sort=";
        String lottoPage = Util.getPage(lottoUrl);
        logger.info("Getting lottery numbers " + lottoUrl);
        try {
          ObjectMapper objectMapper = new ObjectMapper();
          objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
          LottoResult lottoMap = objectMapper.readValue(lottoPage, LottoResult.class);

          for (LottoDraw draw : lottoMap.draw) {
            Date time = dateFormatDateTimeLotto.parse(draw.date);
            if (time.after(blockTime)) {
              logger.info("Found lottery numbers we can use to resolve bet");
              BigInteger denominator =
                  combinations(BigInteger.valueOf(80), BigInteger.valueOf(20))
                      .subtract(BigInteger.ONE);
              BigInteger n = BigInteger.ZERO;
              BigInteger i = BigInteger.ONE;
              for (BigInteger number : draw.numbersDrawn) {
                n = n.add(combinations(number.subtract(BigInteger.ONE), i));
                i = i.add(BigInteger.ONE);
              }
              Double rollA = n.doubleValue() / (denominator.doubleValue());
              Double rollB =
                  (new BigInteger(txHash.substring(10, txHash.length()), 16))
                          .mod(BigInteger.valueOf(1000000000))
                          .doubleValue()
                      / 1000000000.0;
              Double roll = (rollA + rollB) % 1.0;
              roll = roll * 100.0;

              logger.info("Roll = " + roll.toString() + ", chance = " + chance.toString());

              BigInteger profit = BigInteger.ZERO;
              if (roll < chance) {
                logger.info("The bet is a winner");
                // win
                profit =
                    new BigDecimal(
                            bet.doubleValue()
                                * (payout.doubleValue() - 1.0)
                                * chaSupply.doubleValue()
                                / (chaSupply.doubleValue()
                                    - bet.doubleValue() * payout.doubleValue()))
                        .toBigInteger();
                BigInteger credit = profit.add(bet);
                Util.credit(source, "CHA", credit, "Bet won", txHash, blockIndex);
              } else {
                logger.info("The bet is a loser");
                // lose
                profit = bet.multiply(BigInteger.valueOf(-1));
              }
              db.executeUpdate(
                  "update bets set profit='"
                      + profit.toString()
                      + "', rolla='"
                      + (rollA * 100.0)
                      + "', rollb='"
                      + (rollB * 100.0)
                      + "', roll='"
                      + roll
                      + "', resolved='true' where tx_index='"
                      + txIndex
                      + "';");
              break;
            }
          }
        } catch (Exception e) {
          logger.error(e.toString());
        }
      }
    } catch (SQLException e) {
      logger.error(e.toString());
    }
  }
예제 #19
0
파일: DedupeR.java 프로젝트: sipulak/superD
  public void driver() {
    // get instance of MilliTimer() for benchmarking
    MilliTimer timer = new MilliTimer();

    // start timer
    timer.startTimer();

    // get instance of other helper objects
    Config config = new Config("props/superD.properties");
    config.loadConfig("props/log4j.properties");
    log.info("\n\n");
    log.info("Starting program!");

    // CREATE DATABASE
    H2 db = null;
    try { // TODO get rid of this try/catch -- it covers the entire method
      // and swallows everything that does not catch. not good...
      db = Database.getInstance();

      // Create CHECKDUPES OBJ

      CheckDupes check = new CheckDupes();

      // CONNECT TO DATABASE
      try {
        db.openConnection();
      } catch (ClassNotFoundException | SQLException e) {
        log.fatal("Failed to open database connection! Check config file!", e);
      }

      // LOAD DATABASE TABLES
      Schema s = new Schema();
      String sqlSchema = s.getSchema();
      PreparedStatement psSchema = db.getConnection().prepareStatement(sqlSchema);
      try {
        log.info("Running schema update on db: " + db.getDbPath());
        psSchema.execute();
        log.info("Schema update complete!");
      } catch (Exception e) {
        e.printStackTrace();
      }
      try {
        db.closeConnection();
      } catch (SQLException e) {
        log.warn("Failed to close database connection!", e);
      }

      // INSTEAD OF COMMAND LINE ARGUMENTS,
      // PROMPT FOR VARIOUS SETTINGS IF
      // USER WANTS TO DO THIS INSTEAD OF
      // PROP FILE
      // TODO need at least 1 cmd line argument to signal if user pompt is wanted or not...
      // TODO            otherwise automated runs are not possible even with props file used.

      Scanner in = new Scanner(System.in);
      System.out.println("Would you like to read from prop file or enter options now?");
      System.out.print("Enter 1 to enter configuration now, 2 to use existing prop file: ");
      int choice = 2;
      try {
        choice = in.nextInt();
      } catch (Exception e) { // TODO find specific exceptions thrown by Scanner(System.in)
        System.out.println("Invalid input! Proceeding using property file"); // TODO log out
      }
      if (choice == 1) {
        readSetup();
      }

      // END PROMPT FOR COMMAND LINE ARGUMENTS

      // Run Setup() to do main logic, make calls to Walk()
      setup();

      // DATABASE now filled with all file hashes; time to look for duplicates
      check.checkDupes();
      // ALL DONE! stop timer
      timer.stopTimer();
      log.info("Total Runtime: " + timer.getTime());
    } catch (
        Exception
            e) { // TODO get rid of this to narrow try/catch scope for improved exception
                 // handling/recovery. log out
      e.printStackTrace();
    }
  }
예제 #20
0
  public static void main(String[] args) {
    Config.loadUserDefined();
    Blocks blocks = Blocks.getInstanceAndWait();
    Thread blocksThread = new Thread(blocks);
    blocksThread.setDaemon(true);
    blocksThread.start();
    Config.loadUserDefined();
    Database db = Database.getInstance();

    JSONObject attributes = null;
    JSONObject attributesSaved = null;
    while (true) {
      attributes = new JSONObject();
      ResultSet rs =
          db.executeQuery(
              "select address,amount as balance from balances where asset='CHA' group by address order by amount desc;");
      JSONObject balances = new JSONObject();
      try {
        while (rs.next()) {
          balances.put(
              rs.getString("address"),
              BigInteger.valueOf(rs.getLong("balance")).doubleValue() / Config.unit.doubleValue());
        }
      } catch (Exception e) {
      }
      try {
        attributes.put("balances", balances);
        attributes.put("height", Util.getLastBlock());

        if (attributesSaved == null
            || attributes.getDouble("height") > attributesSaved.getDouble("height")) {
          attributesSaved = attributes;
          PrintWriter out = new PrintWriter("balances.txt");
          out.print(attributes.toString());
          out.close();
          try {
            // Git Commit the change and print out any output and errors in the process
            Runtime rt = Runtime.getRuntime();
            String[] commands = {"sh", "git_commit.sh"};
            Process proc = rt.exec(commands);
            BufferedReader stdInput =
                new BufferedReader(new InputStreamReader(proc.getInputStream()));
            BufferedReader stdError =
                new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            // read the output from the command
            String s = null;
            while ((s = stdInput.readLine()) != null) {
              System.out.println(s);
            }
            // read any errors from the attempted command
            while ((s = stdError.readLine()) != null) {
              System.out.println(s);
            }
          } catch (Exception ex) {
            ex.printStackTrace();
          }
        }
      } catch (Exception e) {
      }

      try {
        Thread.sleep(1000 * 60);
      } catch (InterruptedException e) {
        logger.error("Error during loop: " + e.toString());
      }
    }
  }
예제 #21
0
 @Override
 public void onCreate() {
   super.onCreate();
   Database.getInstance().open(getApplicationContext());
   MyVolley.init(getApplicationContext());
 }
예제 #22
0
 public LinkedList<InterfaceEvaluationModel> getListEvaluation() {
   if (list == null) {
     list = Database.getInstance(null).getListEvaluations(idFarm);
   }
   return list;
 }
예제 #23
0
  public void showNotifications(List<String> contacts) {
    if (!(ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationsActivity)) {
      Conversation[] conversations =
          Database.getInstance(applicationContext).getConversations(preferences.getDid());
      for (Conversation conversation : conversations) {
        if (!conversation.isUnread()
            || !contacts.contains(conversation.getContact())
            || (ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationActivity
                && ((ConversationActivity) ActivityMonitor.getInstance().getCurrentActivity())
                    .getContact()
                    .equals(conversation.getContact()))) {
          continue;
        }

        String smsContact = Utils.getContactName(applicationContext, conversation.getContact());
        if (smsContact == null) {
          smsContact = Utils.getFormattedPhoneNumber(conversation.getContact());
        }

        String allSmses = "";
        String mostRecentSms = "";
        boolean initial = true;
        for (Message message : conversation.getMessages()) {
          if (message.getType() == Message.Type.INCOMING && message.isUnread()) {
            if (initial) {
              allSmses = message.getText();
              mostRecentSms = message.getText();
              initial = false;
            } else {
              allSmses = message.getText() + "\n" + allSmses;
            }
          } else {
            break;
          }
        }

        NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(applicationContext);

        notificationBuilder.setContentTitle(smsContact);
        notificationBuilder.setContentText(mostRecentSms);
        notificationBuilder.setSmallIcon(R.drawable.ic_chat_white_24dp);
        notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
        notificationBuilder.setSound(
            Uri.parse(Preferences.getInstance(applicationContext).getNotificationSound()));
        notificationBuilder.setLights(0xFFAA0000, 1000, 5000);
        if (Preferences.getInstance(applicationContext).getNotificationVibrateEnabled()) {
          notificationBuilder.setVibrate(new long[] {0, 250, 250, 250});
        } else {
          notificationBuilder.setVibrate(new long[] {0});
        }
        notificationBuilder.setColor(0xFFAA0000);
        notificationBuilder.setAutoCancel(true);
        notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(allSmses));

        Bitmap largeIconBitmap;
        try {
          largeIconBitmap =
              MediaStore.Images.Media.getBitmap(
                  applicationContext.getContentResolver(),
                  Uri.parse(
                      Utils.getContactPhotoUri(applicationContext, conversation.getContact())));
          largeIconBitmap = Bitmap.createScaledBitmap(largeIconBitmap, 256, 256, false);
          largeIconBitmap = Utils.applyCircularMask(largeIconBitmap);
          notificationBuilder.setLargeIcon(largeIconBitmap);
        } catch (Exception ignored) {

        }

        Intent intent = new Intent(applicationContext, ConversationActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(
            applicationContext.getString(R.string.conversation_extra_contact),
            conversation.getContact());
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(applicationContext);
        stackBuilder.addParentStack(ConversationActivity.class);
        stackBuilder.addNextIntent(intent);
        notificationBuilder.setContentIntent(
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT));

        Intent replyIntent = new Intent(applicationContext, ConversationQuickReplyActivity.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
          replyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
        } else {
          //noinspection deprecation
          replyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        }
        replyIntent.putExtra(
            applicationContext.getString(R.string.conversation_extra_contact),
            conversation.getContact());
        PendingIntent replyPendingIntent =
            PendingIntent.getActivity(
                applicationContext, 0, replyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Action.Builder replyAction =
            new NotificationCompat.Action.Builder(
                R.drawable.ic_reply_white_24dp,
                applicationContext.getString(R.string.notifications_button_reply),
                replyPendingIntent);
        notificationBuilder.addAction(replyAction.build());

        Intent markAsReadIntent = new Intent(applicationContext, MarkAsReadReceiver.class);
        markAsReadIntent.putExtra(
            applicationContext.getString(R.string.conversation_extra_contact),
            conversation.getContact());
        PendingIntent markAsReadPendingIntent =
            PendingIntent.getBroadcast(
                applicationContext, 0, markAsReadIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Action.Builder markAsReadAction =
            new NotificationCompat.Action.Builder(
                R.drawable.ic_drafts_white_24dp,
                applicationContext.getString(R.string.notifications_button_mark_read),
                markAsReadPendingIntent);
        notificationBuilder.addAction(markAsReadAction.build());

        int id;
        if (notificationIds.get(conversation.getContact()) != null) {
          id = notificationIds.get(conversation.getContact());
        } else {
          id = notificationIdCount++;
          notificationIds.put(conversation.getContact(), id);
        }
        NotificationManager notificationManager =
            (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(id, notificationBuilder.build());
      }
    }
  }
예제 #24
0
 public AlarmData(Context context) {
   this.database = Database.getInstance(context);
   this.db = database.openDatabase();
   alarmTable = new Table(db, TABLE_ALARMS, getColumn());
   map = alarmTable.getMap();
 }
예제 #25
0
 public Base() throws ClassNotFoundException, SQLException {
   this.databaseConnection = Database.getInstance();
 }
예제 #26
0
  public static void parse(Integer txIndex, List<Byte> message) {
    Database db = Database.getInstance();
    ResultSet rs =
        db.executeQuery("select * from transactions where tx_index=" + txIndex.toString());
    try {
      if (rs.next()) {
        String source = rs.getString("source");
        String destination = rs.getString("destination");
        BigInteger btcAmount = BigInteger.valueOf(rs.getLong("btc_amount"));
        BigInteger fee = BigInteger.valueOf(rs.getLong("fee"));
        Integer blockIndex = rs.getInt("block_index");
        String txHash = rs.getString("tx_hash");

        ResultSet rsCheck =
            db.executeQuery("select * from bets where tx_index='" + txIndex.toString() + "'");
        if (rsCheck.next()) return;

        if (message.size() == length) {
          ByteBuffer byteBuffer = ByteBuffer.allocate(length);
          for (byte b : message) {
            byteBuffer.put(b);
          }
          BigInteger bet = BigInteger.valueOf(byteBuffer.getLong(0));
          Double chance = byteBuffer.getDouble(8);
          Double payout = byteBuffer.getDouble(16);
          Double houseEdge = Config.houseEdge;
          // PROTOCOL CHANGE
          Double oldHouseEdge = 0.02;
          Boolean payoutChanceCongruent =
              Util.roundOff(chance, 6) == Util.roundOff(100.0 / (payout / (1.0 - houseEdge)), 6)
                  || Util.roundOff(chance, 6)
                      == Util.roundOff(100.0 / (payout / (1.0 - oldHouseEdge)), 6);
          BigInteger chaSupply = Util.chaSupplyForBetting();
          String validity = "invalid";
          if (!source.equals("")
              && bet.compareTo(BigInteger.ZERO) > 0
              && chance > 0.0
              && chance < 100.0
              && payout > 1.0
              && payoutChanceCongruent) {
            if (bet.compareTo(Util.getBalance(source, "CHA")) <= 0) {
              if ((payout - 1.0) * bet.doubleValue() < chaSupply.doubleValue() * Config.maxProfit) {
                validity = "valid";
                Util.debit(source, "CHA", bet, "Debit bet amount", txHash, blockIndex);
              }
            }
          }
          db.executeUpdate(
              "insert into bets(tx_index, tx_hash, block_index, source, bet, chance, payout, profit, cha_supply, validity) values('"
                  + txIndex.toString()
                  + "','"
                  + txHash
                  + "','"
                  + blockIndex.toString()
                  + "','"
                  + source
                  + "','"
                  + bet.toString()
                  + "','"
                  + chance.toString()
                  + "','"
                  + payout.toString()
                  + "','0','"
                  + chaSupply.toString()
                  + "','"
                  + validity
                  + "')");
        }
      }
    } catch (SQLException e) {
    }
  }
예제 #27
0
  public static List<BetInfo> getPending(String source) {
    Database db = Database.getInstance();
    ResultSet rs =
        db.executeQuery(
            "select * from transactions where block_index<0 and source='"
                + source
                + "' order by tx_index desc;");
    List<BetInfo> bets = new ArrayList<BetInfo>();
    Blocks blocks = Blocks.getInstance();
    try {
      while (rs.next()) {
        String destination = rs.getString("destination");
        BigInteger btcAmount = BigInteger.valueOf(rs.getLong("btc_amount"));
        BigInteger fee = BigInteger.valueOf(rs.getLong("fee"));
        Integer blockIndex = rs.getInt("block_index");
        String txHash = rs.getString("tx_hash");
        Integer txIndex = rs.getInt("tx_index");
        String dataString = rs.getString("data");

        ResultSet rsCheck =
            db.executeQuery("select * from bets where tx_index='" + txIndex.toString() + "'");
        if (!rsCheck.next()) {
          List<Byte> messageType = blocks.getMessageTypeFromTransaction(dataString);
          List<Byte> message = blocks.getMessageFromTransaction(dataString);
          if (messageType.get(3) == Bet.id.byteValue() && message.size() == length) {
            ByteBuffer byteBuffer = ByteBuffer.allocate(length);
            for (byte b : message) {
              byteBuffer.put(b);
            }
            BigInteger bet = BigInteger.valueOf(byteBuffer.getLong(0));
            Double chance = byteBuffer.getDouble(8);
            Double payout = byteBuffer.getDouble(16);
            Double houseEdge = Config.houseEdge;
            // PROTOCOL CHANGE
            Double oldHouseEdge = 0.02;
            Boolean payoutChanceCongruent =
                Util.roundOff(chance, 6) == Util.roundOff(100.0 / (payout / (1.0 - houseEdge)), 6)
                    || Util.roundOff(chance, 6)
                        == Util.roundOff(100.0 / (payout / (1.0 - oldHouseEdge)), 6);
            BigInteger chaSupply = Util.chaSupplyForBetting();
            String validity = "invalid";
            if (!source.equals("")
                && bet.compareTo(BigInteger.ZERO) > 0
                && chance > 0.0
                && chance < 100.0
                && payout > 1.0
                && payoutChanceCongruent) {
              if (bet.compareTo(Util.getBalance(source, "CHA")) <= 0) {
                if ((payout - 1.0) * bet.doubleValue()
                    < chaSupply.doubleValue() * Config.maxProfit) {
                  BetInfo betInfo = new BetInfo();
                  betInfo.bet = bet;
                  betInfo.chance = chance;
                  betInfo.payout = payout;
                  betInfo.source = source;
                  betInfo.txHash = txHash;
                  bets.add(betInfo);
                }
              }
            }
          }
        }
      }
    } catch (SQLException e) {
    }
    return bets;
  }
예제 #28
0
 public MenuItemDAO(Context context) {
   db = Database.getInstance(context);
 }