예제 #1
0
  /**
   * Deliveres notification to the user that an email has been dropped. Typically due to size
   * restriction
   *
   * @param account
   * @param messageNumber
   * @param message
   * @throws Exception
   */
  public void saveMessageDroppedNotification(
      Account account, int messageNumber, Message message, int reportedSize) throws Exception {
    MessageParser parser = new MessageParser();

    Email email = new Email();
    email.setSubject(
        "Your email"); // ReceiverUtilsTools.subSubject(parser.parseMsgSubject(message),
                       // subjectSize));
    email.setFrom(parser.parseMsgAddress(message, "FROM", false));
    email.setTo(ReceiverUtilsTools.subAddress(parser.parseMsgAddress(message, "TO", true)));
    email.setCc(ReceiverUtilsTools.subAddress(parser.parseMsgAddress(message, "CC", true)));
    email.setBcc(ReceiverUtilsTools.subAddress(parser.parseMsgAddress(message, "BCC", true)));
    email.setMaildate(ReceiverUtilsTools.dateToStr(message.getSentDate()));
    email.setStatus("0");
    email.setUserId(account.getUser_id());
    email.setMessage_type("EMAIL");

    Body body = new Body();

    String droppedMessage =
        getEmailDroppedMessage(account, getMessageDate(message), reportedSize, email.getFrom());

    body.setData(droppedMessage.getBytes());
    email.setBodySize(droppedMessage.length());

    int saveStatus = DALDominator.newSaveMail(account, email, body);

    if (log.isDebugEnabled())
      log.debug(
          String.format(
              "[%s] msgNum=%d, saving completed for dropped message with status %s",
              account.getName(), messageNumber, saveStatus));
  }
  /** Creates a new instance of AccountPicker */
  public AccountSelect(Display display, boolean enableQuit) {
    super();
    // this.display=display;

    setTitleItem(new Title(SR.MS_ACCOUNTS));

    accountList = new Vector();
    Account a;

    int index = 0;
    activeAccount = Config.getInstance().accountIndex;
    do {
      a = Account.createFromStorage(index);
      if (a != null) {
        accountList.addElement(a);
        a.active = (activeAccount == index);
        index++;
      }
    } while (a != null);
    if (accountList.isEmpty()) {
      a = Account.createFromJad();
      if (a != null) {
        // a.updateJidCache();
        accountList.addElement(a);
        rmsUpdate();
      }
    }
    attachDisplay(display);
    addCommand(cmdAdd);

    if (enableQuit) addCommand(cmdQuit);

    commandState();
    setCommandListener(this);
  }
예제 #3
0
  static UserPrincipal fromSid(long sidAddress) throws IOException {
    String sidString;
    try {
      sidString = ConvertSidToStringSid(sidAddress);
      if (sidString == null) {
        // pre-Windows XP system?
        throw new AssertionError();
      }
    } catch (WindowsException x) {
      throw new IOException("Unable to convert SID to String: " + x.errorString());
    }

    // lookup account; if not available then use the SID as the name
    Account account = null;
    String name;
    try {
      account = LookupAccountSid(sidAddress);
      name = account.domain() + "\\" + account.name();
    } catch (WindowsException x) {
      name = sidString;
    }

    int sidType = (account == null) ? SidTypeUnknown : account.use();
    if ((sidType == SidTypeGroup)
        || (sidType == SidTypeWellKnownGroup)
        || (sidType == SidTypeAlias)) // alias for local group
    {
      return new Group(sidString, sidType, name);
    } else {
      return new User(sidString, sidType, name);
    }
  }
예제 #4
0
 /*@
  requires destination != null && source != null;
  requires source != destination;
  ensures \result ==> source.isLocked() && destination.isLocked();
 @*/
 private static synchronized boolean lock(Account source, Account destination) {
   if (source.isLocked()) return false;
   if (destination.isLocked()) return false;
   source.lock();
   destination.lock();
   return true;
 }
예제 #5
0
  public synchronized String transferFromBankToPlayer(Request request, Response response) {
    lamport.Add();
    if (banks.containsKey(request.params(":gameid"))) {
      Collection<Account> accounts = banks.get(request.params(":gameid"));
      for (Account account : accounts) {
        if (account.getPlayer().getId().equals(request.params(":to"))) {
          int am = Integer.parseInt(request.params(":amount"));
          account.AddAmount(am);
          banks.put(request.params(":gameid"), accounts);

          String uri = localUri + "transfers/" + UniqueId++;
          Transfer trans =
              new Transfer(
                  request.params(":from"), request.params(":to"), am, request.body(), "", uri);
          Event event =
              new Event(
                  "bank transfer",
                  request.body(),
                  request.body(),
                  uri,
                  account.getPlayer().getId());
          transfers.add(trans);
          BanksService.sendUpdate(trans, request.params(":gameid"));

          response.status(201);
          return gson.toJson(event);
        }
      }
      response.status(404);
      return "Player not found.";
    } else {
      response.status(404);
      return "Game not found.";
    }
  }
예제 #6
0
  public void update() {
    infoPanel.update();

    Object[][] history = new Object[account.getHistory().size()][5];
    int i = 0;
    for (Transaction t : account.getHistory()) {
      history[i][0] = t.getType();
      BigDecimal amount;
      BigDecimal balance;
      if (account.getType().isLoan()) {
        amount = (t.getType().isPositive() ? t.getAmount().negate() : t.getAmount());
        balance = t.getBalance().negate();
      } else {
        amount = (t.getType().isPositive() ? t.getAmount() : t.getAmount().negate());
        balance = t.getBalance();
      }
      history[i][1] = FORMATTER.valueToString(amount);
      history[i][2] = FORMATTER.valueToString(balance);
      history[i][3] = t.getTimestamp();
      history[i][4] = t.getFraudStatus();
      i++;
    }
    historyTable.setModel(
        new javax.swing.table.DefaultTableModel(
            history, new String[] {"Type", "Amount", "Balance", "Month", "Flag"}) {
          @Override
          public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
          }
        });
    historyTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    historyTable.revalidate();
  }
예제 #7
0
  public Account newAccount(String name, Account.Type type) {
    // Split name at ':'
    String names[] = name.split(":");

    // Build tree of accounts
    Account lastAccount = null;
    for (int i = 0; i < names.length; i++) {
      String accountName = names[i];

      // Fetch the existing account with names[i]
      Account a = accounts.get(accountName);

      // If account doesn't exist then create it with <names[i], type>
      if (a == null) {
        a = new Account(accountName, type);
      }

      // Add this account to the ledger or the last account found
      if (i == 0) {
        accounts.put(accountName, a);
      } else {
        // Add new account to the previous account
        lastAccount.addSubAccount(a);
      }

      lastAccount = a;
    }

    return lastAccount;
  }
 @Test
 @Transactional
 public void updateAccount() {
   Query query = entityManager.createQuery("from Account a where a.id=:id").setParameter("id", 1L);
   Account a = (Account) query.getSingleResult();
   a.setName("foo");
 }
예제 #9
0
  public void printAllAccounts(String customerID) {
    // Sorts the customer based on ID, then prints the accounts information

    // change the withdrawal funcitons and deposit functions too
    ajf.dispose();
    ajf = new AdminRunningFrame(this);

    Collections.sort(cust, Customer.CompareIDs);
    String searchString = ajf.getCustomerID();

    StringBuilder stringResults = new StringBuilder();
    String header = header();
    stringResults.append(header);
    for (Customer customer : cust) {
      String id = customer.returnID();
      String name = customer.getName().toUpperCase();
      String pin = customer.returnPin();
      if (searchString.equals(id)) {
        ArrayList<Account> accounts = customer.getAccounts();
        if (!accounts.isEmpty()) {
          for (Account account : accounts) {
            if (account.checkActive()) {
              String accountNumber = account.returnNumber();
              double balance = account.returnBalance();
              String balanceAsString = formatter.format(balance);
              String customerInfo = printAdminInfo(name, id, accountNumber, pin, balanceAsString);
              stringResults.append(customerInfo);
            }
          }
        }
      }
    }
    String resultsAsString = stringResults.toString();
    ajf.printInfo(resultsAsString);
  }
  /**
   * Method fired when "add" button is clicked.
   *
   * @param v add button's <tt>View</tt>
   */
  public void onAddClicked(View v) {
    Spinner accountsSpiner = (Spinner) findViewById(R.id.selectAccountSpinner);

    Account selectedAcc = (Account) accountsSpiner.getSelectedItem();
    if (selectedAcc == null) {
      logger.error("No account selected");
      return;
    }

    ProtocolProviderService pps = selectedAcc.getProtocolProvider();
    if (pps == null) {
      logger.error("No provider registered for account " + selectedAcc.getAccountName());
      return;
    }

    View content = findViewById(android.R.id.content);
    String contactAddress = ViewUtil.getTextViewValue(content, R.id.editContactName);

    String displayName = ViewUtil.getTextViewValue(content, R.id.editDisplayName);
    if (displayName != null && displayName.length() > 0) {
      addRenameListener(pps, null, contactAddress, displayName);
    }

    Spinner groupSpinner = (Spinner) findViewById(R.id.selectGroupSpinner);
    ContactListUtils.addContact(
        pps, (MetaContactGroup) groupSpinner.getSelectedItem(), contactAddress);
    finish();
  }
  public static void main(String[] args) {

    Account momsSavings = new Account(1000);
    momsSavings.addInterest(10);

    System.out.println("The balance in momsSavings is $" + momsSavings.getBalance());
  }
예제 #12
0
  void acctSelected(ServiceAcctInfo info) {
    Account acct = new Account();
    acct.name = info.desc;
    acct.service = info;

    DialogInterface.OnClickListener emptyClickListener =
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {}
        };

    AcctTables db = new AcctTables(this);
    try {
      db.openWritable();

      try {
        db.pushAccount(acct);
      } catch (SQLiteException e) {
        AlertDialog dlg =
            Utilities.buildAlert(
                this, e, "Unable to add account", "Internal Error", emptyClickListener);
        dlg.show();
        return;
      }
    } finally {
      db.close();
    }

    Intent i = getIntent();
    i.putExtra("acct_id", acct.ID);
    setResult(RESULT_OK, i);
    finish();
  }
예제 #13
0
 private void refreshFolder(Account account, String folderName) {
   // There has to be a cheaper way to get at the localFolder object than this
   Folder localFolder = null;
   try {
     if (account != null && folderName != null) {
       if (!account.isAvailable(FolderList.this)) {
         Log.i(K9.LOG_TAG, "not refreshing folder of unavailable account");
         return;
       }
       localFolder = account.getLocalStore().getFolder(folderName);
       int unreadMessageCount = localFolder.getUnreadMessageCount();
       FolderInfoHolder folderHolder = getFolder(folderName);
       if (folderHolder != null) {
         folderHolder.populate(context, localFolder, mAccount, unreadMessageCount);
         mHandler.dataChanged();
       }
     }
   } catch (Exception e) {
     Log.e(K9.LOG_TAG, "Exception while populating folder", e);
   } finally {
     if (localFolder != null) {
       localFolder.close();
     }
   }
 }
예제 #14
0
  @Override
  public void onNewIntent(Intent intent) {
    setIntent(intent); // onNewIntent doesn't autoset our "internal" intent

    String initialFolder;

    mUnreadMessageCount = 0;
    String accountUuid = intent.getStringExtra(EXTRA_ACCOUNT);
    mAccount = Preferences.getPreferences(this).getAccount(accountUuid);

    if (mAccount == null) {
      // This shouldn't normally happen. But apparently it does. See issue 2261.
      finish();
      return;
    }

    initialFolder = intent.getStringExtra(EXTRA_INITIAL_FOLDER);
    boolean fromNotification = intent.getBooleanExtra(EXTRA_FROM_NOTIFICATION, false);
    if (fromNotification && mAccount.goToUnreadMessageSearch()) {
      MessagingController.getInstance(getApplication()).notifyAccountCancel(this, mAccount);
      openUnreadSearch(this, mAccount);
      finish();
    } else if (initialFolder != null && !K9.FOLDER_NONE.equals(initialFolder)) {
      onOpenFolder(initialFolder);
      finish();
    } else if (intent.getBooleanExtra(EXTRA_FROM_SHORTCUT, false)
        && !K9.FOLDER_NONE.equals(mAccount.getAutoExpandFolderName())) {
      onOpenFolder(mAccount.getAutoExpandFolderName());
      finish();
    } else {

      initializeActivityView();
    }
  }
예제 #15
0
  private BigDecimal transferAmount(Account account1, Account account2, BigDecimal amount1) {
    if (account1.getCurrency().equals(account2.getCurrency())) return amount1;

    BigDecimal rate1 = currencyRates.get(account1.getCurrencyCode());
    BigDecimal rate2 = currencyRates.get(account2.getCurrencyCode());
    return amount1.multiply(rate1).divide(rate2, 0, RoundingMode.HALF_UP);
  }
  public ServerSolution() {
    accountMap = new HashMap<String, Account>();
    File file = new File(fileName);
    ObjectInputStream in = null;
    try {
      if (file.exists()) {
        System.out.println("Reading from file " + fileName + "...");
        in = new ObjectInputStream(new FileInputStream(file));

        Integer sizeI = (Integer) in.readObject();
        int size = sizeI.intValue();
        for (int i = 0; i < size; i++) {
          Account acc = (Account) in.readObject();
          if (acc != null) accountMap.put(acc.getName(), acc);
        }
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    }
  }
예제 #17
0
 public static void main(String[] args) {
   // init object
   Account account1 = new Account(50.00);
   Account account2 = new Account(-7.53);
   // print objects balance
   System.out.printf("account1 balance: $%.2f\n", account1.getBalance());
   System.out.printf("account2 balance: $%.2f\n", account2.getBalance());
   // create scanner to read user input
   Scanner input = new Scanner(System.in);
   double depositAmount; // deposite amount read from user
   System.out.print("Enter deposit amount for account 1: ");
   depositAmount = input.nextDouble();
   System.out.printf("\nadding %.2f to account1 balance\n\n", depositAmount);
   account1.credit(depositAmount);
   // display message
   System.out.printf("account1 balance $%.2f\n", account1.getBalance());
   System.out.printf("account2 balance $%.2f\n", account2.getBalance());
   // prompt
   System.out.print("Enter deposit amount for account2: ");
   depositAmount = input.nextDouble();
   System.out.printf("\nadding %.2f to account2 balance\n\n", depositAmount);
   account2.credit(depositAmount);
   // display balance
   System.out.printf("account1 balance $%.2f\n", account1.getBalance());
   System.out.printf("account2 balance $%.2f\n", account2.getBalance());
 }
예제 #18
0
 @Test
 public void testGetCash()
     throws NotEnoughMoneyInAccountException, NotEnoughMoneyInATMException,
         NoCardInsertedException {
   System.out.println("getCashNotZeroBalance");
   double atmMoney = 1000.0;
   ATM atmTest = new ATM(atmMoney);
   Card mockCard = mock(Card.class);
   Account mockAccount = mock(Account.class);
   atmTest.insertCard(mockCard); // ver.2
   double balance = 600.0;
   double amount = 100.0;
   int pinCode = 7777;
   when(mockCard.getAccount()).thenReturn(mockAccount);
   when(mockCard.checkPin(pinCode)).thenReturn(true);
   when(mockCard.isBlocked()).thenReturn(false);
   when(mockAccount.getBalance()).thenReturn(balance);
   when(mockAccount.withdrow(amount)).thenReturn(amount);
   atmTest.validateCard(mockCard, pinCode);
   atmTest.getCash(amount);
   when(mockAccount.getBalance()).thenReturn(balance - amount);
   assertEquals(atmTest.getMoneyInATM(), atmMoney - amount, 0.0);
   assertEquals(atmTest.checkBalance(), balance - amount, 0.0);
   InOrder inOrder = inOrder(mockCard, mockAccount);
   inOrder.verify(mockCard).isBlocked();
   inOrder.verify(mockCard).checkPin(pinCode);
   inOrder.verify(mockCard, atLeastOnce()).getAccount();
   verify(mockAccount).withdrow(amount);
   inOrder.verify(mockAccount).getBalance();
 }
예제 #19
0
 /** Assigns a worker by name to a ticket by ID. */
 public static void assignWorker(int ticketNum, String workername) {
   DBHelper db = DBHelperFactory.createDBHelper();
   Account temp = db.retrieveAccount(workername);
   db.updateTicketWorker(ticketNum, temp.get_id());
   db.updateTicketQueue(ticketNum, 1);
   db.close();
 }
예제 #20
0
 @Override
 public int setAmount(String accountId, int amount) throws RemoteException {
   Account account = getAccount(accountId);
   account.setAmount(amount);
   accounts.put(accountId, account);
   return amount;
 }
예제 #21
0
  public void onTransactionResult(TransactionResult tr) {
    log(Level.INFO, "Transaction {0} is validated", tr.hash);
    Map<AccountID, STObject> affected = tr.modifiedRoots();

    if (affected != null) {
      Hash256 transactionHash = tr.hash;
      UInt32 transactionLedgerIndex = tr.ledgerIndex;

      for (Map.Entry<AccountID, STObject> entry : affected.entrySet()) {
        Account account = accounts.get(entry.getKey());
        if (account != null) {
          STObject rootUpdates = entry.getValue();
          account
              .getAccountRoot()
              .updateFromTransaction(transactionHash, transactionLedgerIndex, rootUpdates);
        }
      }
    }

    Account initator = accounts.get(tr.initiatingAccount());
    if (initator != null) {
      log(Level.INFO, "Found initiator {0}, notifying transactionManager", initator);
      initator.transactionManager().notifyTransactionResult(tr);
    } else {
      log(Level.INFO, "Can't find initiating account!");
    }
    emit(OnValidatedTransaction.class, tr);
  }
 public void updateBeneficiaries(Account account) {
   String sql = "update T_ACCOUNT_BENEFICIARY SET SAVINGS = ? where ACCOUNT_ID = ? and NAME = ?";
   Connection conn = null;
   PreparedStatement ps = null;
   try {
     conn = dataSource.getConnection();
     ps = conn.prepareStatement(sql);
     for (Beneficiary beneficiary : account.getBeneficiaries()) {
       ps.setBigDecimal(1, beneficiary.getSavings().asBigDecimal());
       ps.setLong(2, account.getEntityId());
       ps.setString(3, beneficiary.getName());
       ps.executeUpdate();
     }
   } catch (SQLException e) {
     throw new RuntimeException("SQL exception occurred updating beneficiary savings", e);
   } finally {
     if (ps != null) {
       try {
         // Close to prevent database cursor exhaustion
         ps.close();
       } catch (SQLException ex) {
       }
     }
     if (conn != null) {
       try {
         // Close to prevent database connection exhaustion
         conn.close();
       } catch (SQLException ex) {
       }
     }
   }
 }
예제 #23
0
 public static void main(String[] args) throws DataFormatException {
   String line = "manager         AA 001000.00";
   Account manager = new Account(line);
   System.out.println(manager.toString());
   Account copy = new Account(manager.toString());
   System.out.println(line);
 }
 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (resultCode == RESULT_OK) {
     if (Intent.ACTION_EDIT.equals(getIntent().getAction())) {
       boolean isPushCapable = false;
       try {
         Store store = mAccount.getRemoteStore();
         isPushCapable = store.isPushCapable();
       } catch (Exception e) {
         Log.e(VisualVoicemail.LOG_TAG, "Could not get remote store", e);
       }
       if (isPushCapable && mAccount.getFolderPushMode() != FolderMode.NONE) {
         MailService.actionRestartPushers(this, null);
       }
       mAccount.save(Preferences.getPreferences(this));
       finish();
     } else {
       // first time setup, return to AccountSetup activity to save account
       setResult(RESULT_OK);
       finish();
     }
   } else {
     if (!Intent.ACTION_EDIT.equals(
         getIntent().getAction())) { // remove account if failed initial setup
       if (mAccount != null) Preferences.getPreferences(this).deleteAccount(mAccount);
     }
   }
 }
 private void validateAccountResultsFormDefinitions(Account account, StringBuffer problems) {
   boolean appendComma = problems.length() > 0;
   Map formDefinitions = account.getResultsFormDefinitions();
   // if there are no results form definitions defined for the account, return an error
   if (formDefinitions.isEmpty()) {
     if (appendComma) {
       problems.append(",");
     }
     problems.append(
         " account with id = " + account.getId() + " has no results form definitions defined.");
     appendComma = true;
   } else {
     Iterator iterator = formDefinitions.keySet().iterator();
     while (iterator.hasNext()) {
       ResultsFormDefinition formDef =
           (ResultsFormDefinition) formDefinitions.get(iterator.next());
       if (!LabelPrintingConfigurationUtils.isResultsFormDefinitionValid(formDef)) {
         if (appendComma) {
           problems.append(",");
         }
         problems.append(
             " results form definition with id = "
                 + formDef.getFormDefinitionId()
                 + " in account with id = "
                 + account.getId()
                 + " is invalid.");
         appendComma = true;
       }
     }
   }
 }
예제 #26
0
  @Given("^I have deposited \\$(\\d+) in my account$")
  public void iHaveDeposited$InMyAccount(int amount) throws Throwable {
    Account myAccount = new Account();
    myAccount.deposit(amount);

    Assert.assertEquals("Incorrect account balance -", amount, myAccount.getBalance());
  }
예제 #27
0
  /**
   * Generate a new universally unique ID for an account.
   *
   * @return the uuid
   */
  public String getNewAccountUUID() {

    // inits
    String uuid;
    Random rng = new Random();
    int len = 10;
    boolean nonUnique = false;

    // continue looping until we get a unique ID
    do {

      // generate the number
      uuid = "";
      for (int c = 0; c < len; c++) {
        uuid += ((Integer) rng.nextInt(10)).toString();
      }

      // check to make sure it's unique
      for (Account a : this.accounts) {
        if (uuid.compareTo(a.getUUID()) == 0) {
          nonUnique = true;
          break;
        }
      }

    } while (nonUnique);

    return uuid;
  }
예제 #28
0
  private void transfer(final Date date, final Account account1, final Account account2) {
    persistence.runInTransaction(
        em -> {
          BigDecimal amount1 = randomExpenseAmount(account1, date, 0.5);
          if (BigDecimal.ZERO.compareTo(amount1) >= 0) return;

          BigDecimal amount2 = transferAmount(account1, account2, amount1);

          Operation operation = metadata.create(Operation.class);
          operation.setOpType(OperationType.TRANSFER);
          operation.setOpDate(date);
          operation.setAcc1(account1);
          operation.setAmount1(amount1);
          operation.setAcc2(account2);
          operation.setAmount2(amount2);
          em.persist(operation);

          log.info(
              "Transfer: "
                  + date
                  + ", "
                  + account1.getName()
                  + ", "
                  + amount1
                  + ", "
                  + account2.getName()
                  + ", "
                  + amount2);
        });
  }
 /**
  * Tries to call the given consistent operation while holding the given lock.
  *
  * <p>If this is the first execution of this method on the call stack of the current thread, then
  * the lock gets acquired using {@link Lock#lock()}. Once the lock has been acquired the operation
  * gets called. If this fails for some reason and the thrown exception chain contains a {@link
  * FsNeedsLockRetryException}, then the lock gets temporarily released and the current thread gets
  * paused for a small random time interval before this procedure starts over again. Otherwise, the
  * exception chain gets just passed on to the caller.
  *
  * <p>If this is <em>not</em> the first execution of this method on the call stack of the current
  * thread, then the lock gets acquired using {@link Lock#tryLock()} instead. If this fails, an
  * {@code FsNeedsLockRetryException} gets created and passed to the given exception handler for
  * mapping before finally throwing the resulting exception by executing {@code throw
  * handler.fail(new FsNeedsLockRetryException())}. Once the lock has been acquired the operation
  * gets called. If this fails for some reason then the exception chain gets just passed on to the
  * caller.
  *
  * <p>This algorithm prevents dead locks effectively by temporarily unwinding the stack and
  * releasing all locks for a small random time interval. Note that this requires some minimal
  * cooperation by the operation: Whenever it throws an exception, it MUST leave its resources in a
  * consistent state so that it can get retried again! Mind that this is standard requirement for
  * any {@link FsController}.
  *
  * @param  <T> The return type of the operation.
  * @param operation The atomic operation.
  * @param lock The lock to hold while calling the operation.
  * @return The result of the operation.
  * @throws IOException As thrown by the operation.
  * @throws FsNeedsLockRetryException See above.
  */
 private <T> T locked(final Operation<T> operation, final Lock lock) throws IOException {
   final Account account = accounts.get();
   if (0 < account.lockCount) {
     if (!lock.tryLock()) throw FsNeedsLockRetryException.get();
     account.lockCount++;
     try {
       return operation.call();
     } finally {
       account.lockCount--;
       lock.unlock();
     }
   } else {
     try {
       while (true) {
         try {
           lock.lock();
           account.lockCount++;
           try {
             return operation.call();
           } finally {
             account.lockCount--;
             lock.unlock();
           }
         } catch (FsNeedsLockRetryException ex) {
           account.pause();
         }
       }
     } finally {
       accounts.remove();
     }
   }
 }
예제 #30
0
  public boolean isAccountBeingUsed(Account account) {
    if (log.isDebugEnabled())
      log.debug(
          String.format(
              "Checking account %s, user_id %s for last registration with location service",
              account.getId(), account.getUser_id()));

    IPeekLocationService locationService = new PeekLocationService();
    Date lastUpdated = null;
    try {
      lastUpdated = locationService.getLastUpdatedTimestamp(account.getUser_id());
    } catch (DALException e) {
      log.error(UtilsTools.getExceptionStackTrace(e));
    }
    if (lastUpdated == null) {
      log.debug("Last updated value not found, so we should still check this account");
      return true;
    }
    Date now = new Date();
    Long interval = dayMultiplier * mailcheckDisableIntervalInHours;
    Long sinceLastConnection = now.getTime() - lastUpdated.getTime();
    if (sinceLastConnection > interval) {
      if (log.isDebugEnabled())
        log.debug(
            String.format(
                "Last mail check was %s hours ago, > %s hour interval , we will not check this account",
                sinceLastConnection / dayMultiplier, interval / dayMultiplier));
      return false;
    }

    return true;
  }