예제 #1
0
  private String exec(final String... cmd) throws IOException, InterruptedException {
    assert cmd != null;

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    Log.trace("Running: ", cmd);

    Process p = Runtime.getRuntime().exec(cmd);

    InputStream in = null;
    InputStream err = null;
    OutputStream out = null;
    try {
      int c;
      in = p.getInputStream();
      while ((c = in.read()) != -1) {
        bout.write(c);
      }
      err = p.getErrorStream();
      while ((c = err.read()) != -1) {
        bout.write(c);
      }
      out = p.getOutputStream();
      p.waitFor();
    } finally {
      close(in, out, err);
    }

    String result = bout.toString();

    Log.trace("Result: ", result);

    return result;
  }
예제 #2
0
  /** Filters input HTML using specified policy as white list of allowed tags. */
  @SuppressWarnings("unchecked")
  private String filter(String inputHtml, String policyFileName) {
    String filteredHtml = "";
    if (!StringUtils.isBlank(inputHtml)) {
      if (policyFileName == null) {
        LOG.warn("Provided policy file name is null.");
        policyFileName = DEFAULT_ANTISAMY_POLICY_FILE;
      }

      AntiSamy htmlScanner = getHtmlScannerByPolicyFileName(policyFileName);
      if (htmlScanner != null) {
        CleanResults scanResults;
        try {
          scanResults = htmlScanner.scan(inputHtml);
          filteredHtml = scanResults.getCleanHTML();
          ArrayList<String> scannerErrors = scanResults.getErrorMessages();
          if (!CollectionUtils.isNullOrEmpty(scannerErrors)) {
            LOG.trace("HTML input contains erorrs (" + scannerErrors.size() + "):");
            int i = 1;
            for (String error : scannerErrors) {
              LOG.trace("    " + i + ") " + error);
              i++;
            }
          }
        } catch (ScanException ex) {
          throw new HtmlScannerException(ex);
        } catch (PolicyException ex) {
          throw new HtmlScannerException(ex);
        }
      }
    }

    return filteredHtml;
  }
예제 #3
0
  private void writeNumber(Number obj, Buffer buf) {
    long value = obj.longValue();

    if (value >= -32 && value <= Byte.MAX_VALUE) {
      // Integer
      if (T) Log.trace("writing Integer value: " + value);
      buf.writeI8((byte) value);
    } else if (value >= Byte.MIN_VALUE && value < -32) {
      if (T) Log.trace("writing I8 value: " + value);
      buf.writeI8(TYPE_I8);
      buf.writeI8((byte) value);
    } else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) {
      // I16
      if (T) Log.trace("writing I16 value: " + value);
      buf.writeI8(TYPE_I16);
      buf.writeI16((short) value);
    } else if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) {
      // I32
      if (T) Log.trace("writing I32 value: " + value);
      buf.writeI8(TYPE_I32);
      buf.writeI32((int) value);
    } else {
      // I64
      if (T) Log.trace("writing I64 value: " + value);
      buf.writeI8(TYPE_I64);
      buf.writeI64(value);
    }
  }
예제 #4
0
  public void testLoggingWithNullParameters() {
    Log log = this.getLogObject();

    assertNotNull(log);

    log.debug(null);

    log.debug(null, null);

    log.debug(log.getClass().getName() + ": debug statement");

    log.debug(
        log.getClass().getName() + ": debug statement w/ null exception", new RuntimeException());

    log.error(null);

    log.error(null, null);

    log.error(log.getClass().getName() + ": error statement");

    log.error(
        log.getClass().getName() + ": error statement w/ null exception", new RuntimeException());

    log.fatal(null);

    log.fatal(null, null);

    log.fatal(log.getClass().getName() + ": fatal statement");

    log.fatal(
        log.getClass().getName() + ": fatal statement w/ null exception", new RuntimeException());

    log.info(null);

    log.info(null, null);

    log.info(log.getClass().getName() + ": info statement");

    log.info(
        log.getClass().getName() + ": info statement w/ null exception", new RuntimeException());

    log.trace(null);

    log.trace(null, null);

    log.trace(log.getClass().getName() + ": trace statement");

    log.trace(
        log.getClass().getName() + ": trace statement w/ null exception", new RuntimeException());

    log.warn(null);

    log.warn(null, null);

    log.warn(log.getClass().getName() + ": warn statement");

    log.warn(
        log.getClass().getName() + ": warn statement w/ null exception", new RuntimeException());
  }
예제 #5
0
 private void writeBoolean(Boolean obj, Buffer buf) {
   if (obj.booleanValue()) {
     // true
     if (T) Log.trace("writing true");
     buf.writeI8(TYPE_TRUE);
   } else {
     // false
     if (T) Log.trace("writing false");
     buf.writeI8(TYPE_FALSE);
   }
 }
예제 #6
0
  @Test
  @SuppressWarnings("deprecation")
  public void testOurLogLogging() {
    final Log logger = new Log();

    logger.trace("Foobar TRACE");
    AppenderForTests.hasNoLastEvent("at Trace level");
    assertFalse(logger.isTraceEnabled());

    logger.debug("Foobar DEBUG");
    AppenderForTests.hasNoLastEvent("at Debug level");
    assertFalse(logger.isDebugEnabled());

    logger.info("Foobar INFO");
    AppenderForTests.hasNoLastEvent("at Info level");
    assertFalse(logger.isInfoEnabled());

    logger.warn("Foobar WARN");
    AppenderForTests.hasLastEvent("at Warn level");
    assertTrue(logger.isWarnEnabled());

    logger.error("Foobar ERROR");
    AppenderForTests.hasLastEvent("at Error level");
    assertTrue(logger.isErrorEnabled());
  }
예제 #7
0
  private void servletEnv() {
    if (!log.isDebugEnabled()) return;

    try {
      java.net.URL url = servletContext.getResource("/");
      log.trace("Joseki base directory: " + url);
    } catch (Exception ex) {
    }

    if (servletConfig != null) {
      String tmp = servletConfig.getServletName();
      log.trace("Servlet = " + (tmp != null ? tmp : "<null>"));
      @SuppressWarnings("unchecked")
      Enumeration<String> en = servletConfig.getInitParameterNames();

      for (; en.hasMoreElements(); ) {
        String s = en.nextElement();
        log.trace("Servlet parameter: " + s + " = " + servletConfig.getInitParameter(s));
      }
    }
    if (servletContext != null) {
      // Name of webapp
      String tmp = servletContext.getServletContextName();
      // msg(Level.FINE, "Webapp = " + (tmp != null ? tmp : "<null>"));
      log.debug("Webapp = " + (tmp != null ? tmp : "<null>"));

      // NB This servlet may not have been loaded as part of a web app
      @SuppressWarnings("unchecked")
      Enumeration<String> en = servletContext.getInitParameterNames();
      for (; en.hasMoreElements(); ) {
        String s = en.nextElement();
        log.debug("Webapp parameter: " + s + " = " + servletContext.getInitParameter(s));
      }
    }
    /*
    for ( Enumeration enum = servletContext.getAttributeNames() ;  enum.hasMoreElements() ; )
    {
        String s = (String)enum.nextElement() ;
        logger.log(LEVEL, "Webapp attribute: "+s+" = "+context.getAttribute(s)) ;
    }
     */
  }
예제 #8
0
  private void writeList(List obj, Buffer buf) {
    if (T) Log.trace("writing List value: " + obj);

    int num = obj.size();
    if (num < MASK_LENGTH_1) {
      buf.writeI8(TYPE_LIST | (byte) num);
    } else {
      buf.writeI8(TYPE_LIST | MASK_LENGTH_1);
      buf.writeI32(num);
    }

    for (int i = 0; i < num; i++) {
      write(obj.get(i), buf);
    }
  }
예제 #9
0
  private void writeMap(Map obj, Buffer buf) {
    if (T) Log.trace("writing Map value: " + obj);

    int num = obj.size();
    if (num < MASK_LENGTH_2) {
      buf.writeI8(TYPE_MAP | (byte) num);
    } else {
      buf.writeI8(TYPE_MAP | MASK_LENGTH_2);
      buf.writeI32(num);
    }

    for (Iterator iter = obj.keySet().iterator(); iter.hasNext(); ) {
      Object k = iter.next();
      write(k, buf);
      write(obj.get(k), buf);
    }
  }
예제 #10
0
  private void writeString(String obj, Buffer buf) {
    try {
      if (T) Log.trace("writing String value: " + obj);

      byte[] str = obj.getBytes("UTF8");
      int strlen = str.length;

      if (strlen < MASK_LENGTH_1) {
        // length is encoded with type.
        buf.writeI8(TYPE_STRING | (byte) str.length);
      } else {
        buf.writeI8(TYPE_STRING | MASK_LENGTH_1);
        buf.writeI32(strlen);
      }
      buf.writeBytes(str, 0, str.length);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      throw new RemoteException("utf8 not supported");
    }
  }
예제 #11
0
  public static String rndUserID() {
    String nextUser = getNextUserIDFromDeck();
    if (Log.doTrace()) Log.trace("TradeConfig:rndUserID -- new trader = " + nextUser);

    return nextUser;
  }
예제 #12
0
 private void writeDouble(Double obj, Buffer buf) {
   if (T) Log.trace("writing F64 value: " + obj);
   buf.writeI8(TYPE_F64);
   buf.writeF64(obj.doubleValue());
 }
예제 #13
0
 private void writeFloat(Float obj, Buffer buf) {
   if (T) Log.trace("writing F32 value: " + obj);
   buf.writeI8(TYPE_F32);
   buf.writeF32(obj.floatValue());
 }
예제 #14
0
    @Override
    public void onReceiveLocation(BDLocation location) {
      if (null == location) return;

      if (isFirstLoc) {
        isFirstLoc = false;
        return;
      }

      int locType = location.getLocType();
      final double latitude = location.getLatitude();
      final double longitude = location.getLongitude();
      float radius = location.getRadius();

      String city = location.getCity();

      mCity = city;

      String strMsg = "error code is " + locType;
      strMsg += ", latitude is " + latitude;
      strMsg += ", longitude is " + longitude;
      strMsg += ", radius is " + radius;
      strMsg += ", city is " + city;

      boolean isStop;

      if (locType == BDLocation.TypeGpsLocation) {
        float speed = location.getSpeed();
        int statelliteNumber = location.getSatelliteNumber();

        strMsg += ", speed is " + speed;
        strMsg += ", statelliteNumber is " + statelliteNumber;

        isStop = true;
      } else if (locType == BDLocation.TypeNetWorkLocation) {
        String strAddrStr = location.getAddrStr();
        strMsg += ", strAddrStr is " + strAddrStr;

        isStop = true;
      } else {
        Log.trace(TAG, "异常:error code is " + locType + " 具体参数错误结果");

        isStop = false;
      }

      strMsg = "获取的位置是-->" + strMsg;

      Log.trace(TAG, strMsg);

      // 定位成功了,去停止定位服务
      stopLocation();

      if (isStop) {
        tran(latitude, longitude);
      } else {
        //              获取error code:
        //              61 : GPS定位结果
        //              62 : 扫描整合定位依据失败。此时定位结果无效。
        //              63 : 网络异常,没有成功向服务器发起请求。此时定位结果无效。
        //              65 : 定位缓存的结果。
        //              66 : 离线定位结果。通过requestOfflineLocaiton调用时对应的返回结果
        //              67 : 离线定位失败。通过requestOfflineLocaiton调用时对应的返回结果
        //              68 : 网络连接失败时,查找本地离线定位时对应的返回结果
        //              161: 表示网络定位结果
        //              162~167: 服务端定位失败
        //              502:key参数错误
        //              505:key不存在或者非法
        //              601:key服务被开发者自己禁用
        //              602:key mcode不匹配
        //              501~700:key验证失败

        if (null != mCallbackListener) {
          String msg = mContext.getResources().getString(R.string.cn_get_location_failed);
          mCallbackListener.onFailed(msg);
        }
      }
    }
  /**
   * Main service method for TradeScenarioServlet
   *
   * @param request Object that encapsulates the request to the servlet
   * @param response Object that encapsulates the response from the servlet
   */
  public void performTask(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    // Scenario generator for Trade2
    char action = ' ';
    String userID = null;

    // String to create full dispatch path to TradeAppServlet w/ request Parameters
    String dispPath = null; // Dispatch Path to TradeAppServlet

    String scenarioAction = (String) req.getParameter("action");
    if ((scenarioAction != null) && (scenarioAction.length() >= 1)) {
      action = scenarioAction.charAt(0);
      if (action == 'n') { // null;
        try {
          resp.setContentType("text/html");
          PrintWriter out = new PrintWriter(resp.getOutputStream());
          out.println("<HTML><HEAD>TradeScenarioServlet</HEAD><BODY>Hello</BODY></HTML>");
          out.close();
          return;

        } catch (Exception e) {
          Log.error(
              "trade_client.TradeScenarioServlet.service(...)"
                  + "error creating printwriter from responce.getOutputStream",
              e);

          resp.sendError(
              500,
              "trade_client.TradeScenarioServlet.service(...): erorr creating and writing to PrintStream created from response.getOutputStream()");
        } // end of catch
      } // end of action=='n'
    }

    ServletContext ctx = null;
    HttpSession session = null;
    try {
      ctx = getServletConfig().getServletContext();
      // These operations require the user to be logged in. Verify the user and if not logged in
      // change the operation to a login
      session = req.getSession(true);
      userID = (String) session.getAttribute("uidBean");
    } catch (Exception e) {
      Log.error(
          "trade_client.TradeScenarioServlet.service(...): performing "
              + scenarioAction
              + "error getting ServletContext,HttpSession, or UserID from session"
              + "will make scenarioAction a login and try to recover from there",
          e);
      userID = null;
      action = 'l';
    }

    if (userID == null) {
      action = 'l'; // change to login
      TradeConfig.incrementScenarioCount();
    } else if (action == ' ') {
      // action is not specified perform a random operation according to current mix
      // Tell getScenarioAction if we are an original user or a registered user
      // -- sellDeficits should only be compensated for with original users.
      action = TradeConfig.getScenarioAction(userID.startsWith(TradeConfig.newUserPrefix));
    }
    switch (action) {
      case 'q': // quote
        dispPath = tasPathPrefix + "quotes&symbols=" + TradeConfig.rndSymbols();
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
      case 'a': // account
        dispPath = tasPathPrefix + "account";
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
      case 'u': // update account profile
        dispPath = tasPathPrefix + "account";
        ctx.getRequestDispatcher(dispPath).include(req, resp);

        String fullName = "rnd" + System.currentTimeMillis();
        String address = "rndAddress";
        String password = "******";
        String email = "rndEmail";
        String creditcard = "rndCC";
        dispPath =
            tasPathPrefix
                + "update_profile&fullname="
                + fullName
                + "&password="******"&cpassword="******"&address="
                + address
                + "&email="
                + email
                + "&creditcard="
                + creditcard;
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
      case 'h': // home
        dispPath = tasPathPrefix + "home";
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
      case 'l': // login
        userID = TradeConfig.getUserID();
        String password2 = "xxx";
        dispPath = tasPathPrefix + "login&inScenario=true&uid=" + userID + "&passwd=" + password2;
        ctx.getRequestDispatcher(dispPath).include(req, resp);

        // login is successful if the userID is written to the HTTP session
        if (session.getAttribute("uidBean") == null) {
          System.out.println("TradeScenario login failed. Reset DB between runs");
        }
        break;
      case 'o': // logout
        dispPath = tasPathPrefix + "logout";
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
      case 'p': // portfolio
        dispPath = tasPathPrefix + "portfolio";
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
      case 'r': // register
        // Logout the current user to become a new user
        // see note in TradeServletAction
        req.setAttribute("TSS-RecreateSessionInLogout", Boolean.TRUE);
        dispPath = tasPathPrefix + "logout";
        ctx.getRequestDispatcher(dispPath).include(req, resp);

        userID = TradeConfig.rndNewUserID();
        String passwd = "yyy";
        fullName = TradeConfig.rndFullName();
        creditcard = TradeConfig.rndCreditCard();
        String money = TradeConfig.rndBalance();
        email = TradeConfig.rndEmail(userID);
        String smail = TradeConfig.rndAddress();
        dispPath =
            tasPathPrefix
                + "register&Full Name="
                + fullName
                + "&snail mail="
                + smail
                + "&email="
                + email
                + "&user id="
                + userID
                + "&passwd="
                + passwd
                + "&confirm passwd="
                + passwd
                + "&money="
                + money
                + "&Credit Card Number="
                + creditcard;
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
      case 's': // sell
        dispPath = tasPathPrefix + "portfolioNoEdge";
        ctx.getRequestDispatcher(dispPath).include(req, resp);

        Collection holdings = (Collection) req.getAttribute("holdingDataBeans");
        int numHoldings = holdings.size();
        if (numHoldings > 0) {
          // sell first available security out of holding

          Iterator it = holdings.iterator();
          boolean foundHoldingToSell = false;
          while (it.hasNext()) {
            HoldingDataBean holdingData = (HoldingDataBean) it.next();
            if (!(holdingData.getPurchaseDate().equals(new java.util.Date(0)))) {
              Integer holdingID = holdingData.getHoldingID();

              dispPath = tasPathPrefix + "sell&holdingID=" + holdingID;
              ctx.getRequestDispatcher(dispPath).include(req, resp);
              foundHoldingToSell = true;
              break;
            }
          }
          if (foundHoldingToSell) break;
          if (Log.doTrace())
            Log.trace(
                "TradeScenario: No holding to sell -switch to buy -- userID = "
                    + userID
                    + "  Collection count = "
                    + numHoldings);
        }
        // At this point: A TradeScenario Sell was requested with No Stocks in Portfolio
        // This can happen when a new registered user happens to request a sell before a buy
        // In this case, fall through and perform a buy instead

        /* Trade 2.037: Added sell_deficit counter to maintain correct buy/sell mix.
         * When a users portfolio is reduced to 0 holdings, a buy is requested instead of a sell.
         * This throws off the buy/sell mix by 1. This results in unwanted holding table growth
         * To fix this we increment a sell deficit counter to maintain the correct ratio in getScenarioAction
         * The 'z' action from getScenario denotes that this is a sell action that was switched from a buy
         * to reduce a sellDeficit
         */
        if (userID.startsWith(TradeConfig.newUserPrefix) == false) {
          TradeConfig.incrementSellDeficit();
        }
      case 'b': // buy
        String symbol = TradeConfig.rndSymbol();
        String amount = TradeConfig.rndQuantity() + "";

        dispPath = tasPathPrefix + "quotes&symbols=" + symbol;
        ctx.getRequestDispatcher(dispPath).include(req, resp);

        dispPath = tasPathPrefix + "buy&quantity=" + amount + "&symbol=" + symbol;
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
    } // end of switch statement
  }