@Override
 protected synchronized Class<?> loadClass(String name, boolean resolve)
     throws ClassNotFoundException {
   if (mFailClasses != null && mFailClasses.matcher(name).matches()) {
     SLF4JLoggerProxy.info(this, "Ignoring matched class {}", name);
     throw new ClassNotFoundException("Sorry!");
   }
   SLF4JLoggerProxy.info(this, "Fetching class {}", name);
   return super.loadClass(name, resolve);
 }
 @Override
 public boolean login() throws LoginException {
   Callback[] callbacks = new Callback[2];
   callbacks[0] = new NameCallback(Messages.PROMPT_USERNAME.getText());
   callbacks[1] = new PasswordCallback(Messages.PROMPT_PASSWORD.getText(), false);
   try {
     mCallback.handle(callbacks);
   } catch (UnsupportedCallbackException e) {
     final LoginException ex = new FailedLoginException(e.getMessage());
     ex.initCause(e);
     throw ex;
   } catch (IOException e) {
     final LoginException ex = new FailedLoginException(e.getMessage());
     ex.initCause(e);
     throw ex;
   }
   mUsername = ((NameCallback) callbacks[0]).getName();
   if (mUsername == null || mUsername.trim().length() == 0) {
     throw new AccountNotFoundException(Messages.EMPTY_USERNAME.getText());
   }
   char[] password = ((PasswordCallback) callbacks[1]).getPassword();
   try {
     if (!ClientLoginHelper.isValidCredentials(mUsername, password)) {
       Messages.USER_LOGIN_ERROR_LOG.warn(this, mUsername);
       throw new FailedLoginException(Messages.USER_LOGIN_FAIL.getText(mUsername));
     }
   } catch (ClientInitException e) {
     Messages.USER_LOGIN_ERROR_LOG.warn(this, e, mUsername);
     LoginException exception = new FailedLoginException(Messages.USER_LOGIN_ERROR.getText());
     exception.initCause(e);
     throw exception;
   }
   SLF4JLoggerProxy.debug(this, "login done for user {}", mUsername); // $NON-NLS-1$
   return true;
 }
 @Override
 public void reconnectFeed() {
   if (!reconnecting.compareAndSet(false, true)) {
     return;
   }
   try {
     if (marketDataClient != null) {
       marketDataClient.stop();
     }
     connect();
     mMarketData.resubmit();
     if (marketDataClient != null && marketDataClient.isRunning()) {
       SLF4JLoggerProxy.info(
           org.marketcetera.core.Messages.USER_MSG_CATEGORY,
           "Market Data Nexus connection established");
     }
   } catch (ConnectionException e) {
     SLF4JLoggerProxy.error(
         org.marketcetera.core.Messages.USER_MSG_CATEGORY,
         "Cannot connect to the Market Data Nexus at {}:{}",
         hostname,
         port);
     SLF4JLoggerProxy.error(
         this,
         e,
         "Cannot connect to the Market Data Nexus at {}:{}",
         e.getHostname(),
         e.getPort());
   } catch (UnknownHostException e) {
     SLF4JLoggerProxy.error(
         org.marketcetera.core.Messages.USER_MSG_CATEGORY,
         "Cannot connect to the Market Data Nexus at {}:{}",
         hostname,
         port);
     SLF4JLoggerProxy.error(
         this,
         e,
         "Cannot connect to the Market Data Nexus at {}:{}",
         e.getHostname(),
         e.getPort());
   } catch (CredentialsException e) {
     SLF4JLoggerProxy.error(
         org.marketcetera.core.Messages.USER_MSG_CATEGORY,
         "The Market Data Nexus rejected the login attempt as {}",
         e.getUsername());
     SLF4JLoggerProxy.error(
         this, e, "The Market Data Nexus rejected the login attempt as {}", e.getUsername());
   } catch (Exception e) {
     SLF4JLoggerProxy.error(this, e);
     throw new RuntimeException(e);
   } finally {
     reconnecting.set(false);
   }
 }
 /* (non-Javadoc)
  * @see org.marketcetera.module.SinkDataListener#receivedData(org.marketcetera.module.DataFlowID, java.lang.Object)
  */
 @Override
 public void receivedData(DataFlowID inDataFlowID, Object inData) {
   synchronized (data) {
     SLF4JLoggerProxy.debug(this, "Test DataSink received {}", inData);
     List<Object> dataForID = data.get(inDataFlowID);
     if (dataForID == null) {
       dataForID = new ArrayList<Object>();
       data.put(inDataFlowID, dataForID);
     }
     dataForID.add(inData);
   }
 }
  @Override
  public Enumeration<URL> getResources(String name) throws IOException {
    if (mFailResources != null && mFailResources.matcher(name).matches()) {
      SLF4JLoggerProxy.info(this, "Ignoring matched resource {}", name);
      return new Enumeration<URL>() {
        public boolean hasMoreElements() {
          return false;
        }

        public URL nextElement() {
          return null;
        }
      };
    }
    SLF4JLoggerProxy.info(this, "Finding resources {}", name);
    final Enumeration<URL> resources = super.getResources(name);
    return new Enumeration<URL>() {

      public boolean hasMoreElements() {
        while (resources.hasMoreElements()) {
          mNext = resources.nextElement();
          if (mFilterResources == null || !mFilterResources.matcher(mNext.toString()).matches()) {
            return true;
          } else {
            SLF4JLoggerProxy.info(this, "Ignoring URL {}", mNext);
          }
        }
        return false;
      }

      public URL nextElement() {
        SLF4JLoggerProxy.info(this, "Returning URL {}", mNext);
        return mNext;
      }

      private URL mNext;
    };
  }
 /* (non-Javadoc)
  * @see org.marketcetera.strategy.ExecutionEngine#prepare(org.marketcetera.strategy.Strategy, java.lang.String)
  */
 @Override
 public void prepare(Strategy inStrategy, String inProcessedScript) throws StrategyException {
   strategy = inStrategy;
   processedScript = inProcessedScript;
   SLF4JLoggerProxy.debug(
       this,
       "Preparing {}", //$NON-NLS-1$
       inStrategy);
   registerScriptEngines();
   String languageString = inStrategy.getLanguage().name();
   try {
     synchronized (scriptManager) {
       if (scriptEngine == null) {
         String classpath = System.getProperty(Strategy.CLASSPATH_PROPERTYNAME);
         SLF4JLoggerProxy.debug(
             this,
             "Setting classpath to {}", //$NON-NLS-1$
             classpath);
         scriptManager.setClassPath(classpath);
         scriptEngine = scriptManager.loadScriptingEngine(languageString);
         SLF4JLoggerProxy.debug(this, "Initializing engine..."); // $NON-NLS-1$
         scriptEngine.initialize(scriptManager, languageString, new Vector<Object>());
       } else {
         SLF4JLoggerProxy.debug(this, "Reusing intialized engine..."); // $NON-NLS-1$
       }
     }
   } catch (BSFException e) {
     StrategyModule.log(
         LogEventBuilder.error()
             .withMessage(NO_SUPPORT_FOR_LANGUAGE, languageString)
             .withException(e)
             .create(),
         strategy);
     throw new StrategyException(
         e, new I18NBoundMessage1P(NO_SUPPORT_FOR_LANGUAGE, languageString));
   }
 }
 /**
  * Verifies all constructor parameter checks.
  *
  * @throws Exception if there were unexpected test failures.
  */
 @Test
 public void constructorChecks() throws Exception {
   // strategy name
   new ExpectedFailure<NullPointerException>() {
     @Override
     protected void run() throws Exception {
       new CreateStrategyParameters("blah", null, "JAVA", new File("dontmatter"), null, false);
     }
   };
   // language
   new ExpectedFailure<NullPointerException>() {
     @Override
     protected void run() throws Exception {
       new CreateStrategyParameters("blah", "naah", null, new File("dontmatter"), null, false);
     }
   };
   // strategy script
   new ExpectedFailure<NullPointerException>() {
     @Override
     protected void run() throws Exception {
       new CreateStrategyParameters("blah", "naah", "JAVA", null, null, false);
     }
   };
   // non existent strategy script
   final File source = new File("doesnotexist");
   new ExpectedFailure<FileNotFoundException>(source.getAbsolutePath()) {
     @Override
     protected void run() throws Exception {
       new CreateStrategyParameters("blah", "naah", "JAVA", source, null, false);
     }
   };
   // non readable strategy script
   final File unreadable = File.createTempFile("strat", "txt");
   unreadable.deleteOnExit();
   unreadable.setReadable(false);
   unreadable.setReadable(false, false);
   // test unreadability failure only if we can make the file unreadable.
   if (!unreadable.canRead()) {
     new ExpectedFailure<FileNotFoundException>(unreadable.getAbsolutePath()) {
       @Override
       protected void run() throws Exception {
         new CreateStrategyParameters("blah", "naah", "JAVA", unreadable, null, false);
       }
     };
   } else {
     SLF4JLoggerProxy.info(this, "Cannot make a test file unreadable.");
   }
 }
  public void listChanged(ListEvent<ReportHolder> listChanges) {
    // all of these changes to this list happen "atomically"
    updates.beginEvent(true);
    // handle reordering events
    if (!listChanges.isReordering()) {
      // for all changes, one index at a time
      while (listChanges.next()) {
        // get the current change info
        int changeType = listChanges.getType();
        EventList<ReportHolder> sourceList = listChanges.getSourceList();
        // handle delete events
        if (changeType == ListEvent.UPDATE) {
          throw new UnsupportedOperationException();
        } else if (changeType == ListEvent.DELETE) {
          // assume a delete all since this is the only thing supported.
          clear();
          updates.commitEvent();
          return;
        } else if (changeType == ListEvent.INSERT) {
          ReportHolder deltaReportHolder = sourceList.get(listChanges.getIndex());
          Message deltaMessage = deltaReportHolder.getMessage();
          ReportBase deltaReport = deltaReportHolder.getReport();
          quickfix.field.Side orderSide = new quickfix.field.Side();
          try {
            deltaMessage.getField(orderSide);
          } catch (FieldNotFound e) {
            orderSide.setValue(quickfix.field.Side.UNDISCLOSED);
          }
          String side = String.valueOf(orderSide.getValue());
          Instrument instrument =
              InstrumentFromMessage.SELECTOR.forValue(deltaMessage).extract(deltaMessage);
          SymbolSide symbolSide = new SymbolSide(instrument, side);
          if (deltaReport instanceof ExecutionReport) {
            SLF4JLoggerProxy.debug(
                AveragePriceReportList.class,
                "Considering {}", //$NON-NLS-1$
                deltaReport);
            ExecutionReport execReport = (ExecutionReport) deltaReport;
            ExecutionType execType = execReport.getExecutionType();

            if (execType == null) {
              SLF4JLoggerProxy.debug(
                  AveragePriceReportList.class,
                  "Skipping {} because the execType was null", //$NON-NLS-1$
                  execReport);
              continue;
            }
            if (execType == null || !execType.isFill()) {
              SLF4JLoggerProxy.debug(
                  AveragePriceReportList.class,
                  "Skipping {} because its execution type {} is not a fill", //$NON-NLS-1$
                  execReport,
                  execReport.getExecutionType());
              continue;
            }

            if (!execReport.getOriginator().forOrders() || !execReport.getHierarchy().forOrders()) {
              SLF4JLoggerProxy.debug(
                  AveragePriceReportList.class,
                  "Skipping {} because it's not appropriate for FIX Message Views", //$NON-NLS-1$
                  execReport);
              continue;
            }
            BigDecimal lastQuantity = execReport.getLastQuantity();
            BigDecimal lastPrice = execReport.getLastPrice();
            if (lastQuantity == null || !(lastQuantity.compareTo(BigDecimal.ZERO) > 0)) {
              SLF4JLoggerProxy.debug(
                  AveragePriceReportList.class,
                  "Skipping {} because the last quantity was null/zero", //$NON-NLS-1$
                  execReport);
              continue;
            }
            if (lastPrice == null) {
              SLF4JLoggerProxy.debug(
                  AveragePriceReportList.class,
                  "Skipping {} because the last price was null", //$NON-NLS-1$
                  execReport);
              continue;
            }
            Integer averagePriceIndex = mAveragePriceIndexes.get(symbolSide);
            // decide if we've seen this symbol/side combination in the list of ERs before. if we
            // have, averagePriceIndex will be non-null
            if (averagePriceIndex != null) {
              // we have already processed at least one ER with this symbol/side combination. that
              // means the math must take into account the existing
              //  ERs as well as the current ER
              ReportHolder averagePriceReportHolder = mAveragePricesList.get(averagePriceIndex);
              Message averagePriceMessage = averagePriceReportHolder.getMessage();
              ExecutionReport averagePriceReport =
                  (ExecutionReport) averagePriceReportHolder.getReport();
              BigDecimal existingCumQty = averagePriceReport.getCumulativeQuantity();
              BigDecimal existingAvgPx = averagePriceReport.getAveragePrice();
              BigDecimal newLastQty = lastQuantity;
              BigDecimal newTotal = existingCumQty.add(newLastQty);
              if (!newTotal.equals(ZERO)) {
                BigDecimal numerator =
                    existingCumQty.multiply(existingAvgPx).add(newLastQty.multiply(lastPrice));
                BigDecimal newAvgPx = numerator.divide(newTotal, 4, RoundingMode.HALF_UP);
                averagePriceMessage.setDecimal(AvgPx.FIELD, newAvgPx);
                averagePriceMessage.setDecimal(CumQty.FIELD, newTotal);
                updates.elementUpdated(
                    averagePriceIndex, averagePriceReportHolder, averagePriceReportHolder);
              }
            } else {
              // we have not seen an ER with this instrument/side combination, make a new average
              // price entry
              Message averagePriceMessage = mMessageFactory.createMessage(MsgType.EXECUTION_REPORT);
              averagePriceMessage.setField(orderSide);
              InstrumentToMessage.SELECTOR
                  .forInstrument(instrument)
                  .set(instrument, mMessageFactory.getBeginString(), averagePriceMessage);
              averagePriceMessage.setField(new CumQty(lastQuantity));
              averagePriceMessage.setField(new AvgPx(lastPrice.setScale(4, RoundingMode.HALF_UP)));
              try {
                ReportHolder newReport =
                    new ReportHolder(
                        Factory.getInstance()
                            .createExecutionReport(
                                averagePriceMessage,
                                execReport.getBrokerID(),
                                Originator.Broker,
                                execReport.getActorID(),
                                execReport.getViewerID()),
                        deltaReportHolder.getUnderlying());
                mAveragePricesList.add(newReport);
                averagePriceIndex = mAveragePricesList.size() - 1;
                mAveragePriceIndexes.put(symbolSide, averagePriceIndex);
                updates.elementInserted(averagePriceIndex, newReport);

              } catch (MessageCreationException e) {
                Messages.UNEXPECTED_ERROR.error(this, e);
              }
            }
          } else {
            SLF4JLoggerProxy.debug(
                AveragePriceReportList.class,
                "Skipping {} because it's not an ExecutionReport", //$NON-NLS-1$
                deltaReport);
          }
        }
      }
    }
    // commit the changes and notify listeners
    updates.commitEvent();
  }
 @Override
 public boolean abort() throws LoginException {
   SLF4JLoggerProxy.debug(this, "Aborting login for user {}", mUsername); // $NON-NLS-1$
   clear();
   return true;
 }