Example #1
0
  @Override
  public void run() {
    try {
      if (!streamsReady) openStreams();
      while (true) {
        Packet p = new Packet(account, dis);
        parent.processPacket(this, p);
      }
    } catch (SocketTimeoutException ex) {
      Log.print(uid + " (" + account + ") отключился по таймауту.");
    } catch (SocketException ex) {
      if (ex.getMessage().hashCode() == "Connection reset".hashCode()) {
        Log.print(uid + " (" + account + ") отключился.");
      } else {
        Log.error("Страшная хуйня на соединении " + uid + " (" + account + ").", ex);
      }
    } catch (EOFException ex) {
      Log.print(uid + " (" + account + ") отключился.");
    } catch (IOException ex) {
      Log.error("Страшная хуйня на соединении " + uid + " (" + account + ").", ex);
    } finally {
      parent.connections.remove(this);

      try {
        parent.accountDisonnected(account);
      } catch (IOException ex) {
        // Да похуй уже.
      }
    }
  }
Example #2
0
  /** Utility method to validate the state of a bundle. Log invalid bundles to log file. */
  public static boolean bundleHasValidState(Bundle bundle) {
    if (bundle == null
        || bundle.getState() == Bundle.UNINSTALLED
        || bundle.getState() == Bundle.INSTALLED) {

      if (bundle == null)
        Log.error("Universal Welcome tried accessing a NULL bundle.", null); // $NON-NLS-1$
      else {
        String msg =
            StringUtil.concat(
                    "Universal Welcome tried accessing Bundle: ",
                    getBundleHeader( //$NON-NLS-1$
                        bundle, Constants.BUNDLE_NAME),
                    " vendor: ", //$NON-NLS-1$
                    getBundleHeader(bundle, Constants.BUNDLE_VENDOR),
                    " bundle state: ",
                    String.valueOf(bundle.getState()))
                .toString(); //$NON-NLS-1$
        Log.error(msg, null);
      }
      return false;
    }

    return true;
  }
Example #3
0
  /**
   * Stop the proxy. Proxy must either implement {@link Closeable} or must have associated {@link
   * RpcInvocationHandler}.
   *
   * @param proxy the RPC proxy object to be stopped
   * @throws HadoopIllegalArgumentException if the proxy does not implement {@link Closeable}
   *     interface or does not have closeable {@link InvocationHandler}
   */
  public static void stopProxy(Object proxy) {
    if (proxy == null) {
      throw new HadoopIllegalArgumentException("Cannot close proxy since it is null");
    }
    try {
      if (proxy instanceof Closeable) {
        ((Closeable) proxy).close();
        return;
      } else {
        InvocationHandler handler = Proxy.getInvocationHandler(proxy);
        if (handler instanceof Closeable) {
          ((Closeable) handler).close();
          return;
        }
      }
    } catch (IOException e) {
      LOG.error("Closing proxy or invocation handler caused exception", e);
    } catch (IllegalArgumentException e) {
      LOG.error("RPC.stopProxy called on non proxy: class=" + proxy.getClass().getName(), e);
    }

    // If you see this error on a mock object in a unit test you're
    // developing, make sure to use MockitoUtil.mockProtocol() to
    // create your mock.
    throw new HadoopIllegalArgumentException(
        "Cannot close proxy - is not Closeable or "
            + "does not provide closeable invocation handler "
            + proxy.getClass());
  }
  private void handleRemoveFeedPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {
    LOG.info("removing feed");
    User user = userHelpers.getUser(request);

    try {
      if (user == null) {
        LOG.error("User not found");
        return;
      }

      String feedId = request.getParameter(PARAM_FEED_ID);

      LOG.info(String.format("Removing feed %s for user %s", feedId, user));

      // ttt1 add some validation; probably best try to actually get data, set the title, ...
      if (feedId == null || feedId.equals("")) {
        LOG.error("feed not specified");
        // ttt1 show some error
        return;
      }

      if (user.feedIds.remove(
          feedId)) { // ttt2 clean up the global feed table; that's probably better done if nobody
                     // accesses a feed for 3 months or so
        userDb.updateFeeds(user);
        LOG.info(String.format("Removed feed %s for user %s", feedId, user));
      } else {
        LOG.info(String.format("No feed found with ID %s for user %s", feedId, user));
      }
    } finally {
      httpServletResponse.sendRedirect(PATH_FEED_ADMIN);
    }
  }
Example #5
0
 private KeyboardEvent getKeyboardEventFromRegistry(String path) {
   NullCheck.notNull(path, "path");
   final Settings.HotKey proxy = Settings.createHotKey(registry, path);
   KeyboardEvent.Special special = null;
   char c = ' ';
   final String specialStr = proxy.getSpecial("");
   if (!specialStr.trim().isEmpty()) {
     special = KeyboardEvent.translateSpecial(specialStr);
     if (special == null) {
       Log.error(
           "core",
           "registry path "
               + path
               + " tries to use an unknown special keyboard code \'"
               + specialStr
               + "\'");
       return null;
     }
   } else {
     final String charStr = proxy.getCharacter("");
     if (charStr.isEmpty()) {
       Log.error(
           "core",
           "registry path "
               + path
               + " does not contain neither \'special\' nor \'character\' values");
       return null;
     }
     c = charStr.charAt(0);
   }
   final boolean withControl = proxy.getWithControl(false);
   final boolean withShift = proxy.getWithShift(false);
   final boolean withAlt = proxy.getWithAlt(false);
   return new KeyboardEvent(special != null, special, c, withShift, withControl, withAlt);
 }
 public JilterStatus eom(JilterEOMActions eomActions, Properties properties) {
   logger.debug("jilter eom()");
   try {
     bos.close(); // close stream
   } catch (IOException io) {
     logger.error("jilter failed to close io stream during eom", io);
   }
   byte[] messageBytes = bos.toByteArray();
   bos = new ByteArrayOutputStream();
   ByteArrayInputStream bis = new ByteArrayInputStream(messageBytes);
   try {
     logger.debug("jilter store callback execute");
     Config.getStopBlockFactory()
         .detectBlock("milter server", Thread.currentThread(), this, IDLE_TIMEOUT);
     callback.store(bis, host);
     logger.debug("jilter store callback finished");
   } catch (ArchiveException e) {
     logger.error("failed to store the message via milter", e);
     if (e.getRecoveryDirective() == ArchiveException.RecoveryDirective.REJECT) {
       logger.debug("jilter reject");
       return JilterStatus.SMFIS_REJECT;
     } else if (e.getRecoveryDirective() == ArchiveException.RecoveryDirective.RETRYLATER) {
       logger.debug("jilter temp fail");
       return JilterStatus.SMFIS_TEMPFAIL;
     }
   } catch (Throwable oome) {
     logger.error("failed to store message:" + oome.getMessage(), oome);
     return JilterStatus.SMFIS_REJECT;
   } finally {
     Config.getStopBlockFactory().endDetectBlock(Thread.currentThread());
   }
   return JilterStatus.SMFIS_CONTINUE;
 }
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() instanceof TextField) {
      TextField tf = (TextField) e.getSource();
      String text = tf.getText();
      String fields[] = FILE.split(text, " ,");
      int r = 0;
      int g = 0;
      int b = 0;
      if (fields.length == 3) {
        // assumed decimal rgb values
        r = FILE.readInteger(fields[0]);
        g = FILE.readInteger(fields[1]);
        b = FILE.readInteger(fields[2]);
      } else if (fields.length == 1) {
        // assume 6 digit hex code
        int crgb = Color32.getColorFromName(fields[0]);
        r = (crgb & 0xff0000) >> 16;
        g = (crgb & 0xff00) >> 8;
        b = (crgb & 0xff);
      } else {
        Log.error("illegal colour format");
        Log.error("should be 0xabcdef or 255 0 255 or colorname");
        return;
      }

      Color c = new Color(r, g, b);

      updateColor(c, e.getSource());
    }
  }
  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());
  }
Example #9
0
 private void logSomething(boolean expectedDebug) {
   Log log = LogFactory.getLog(Object.class);
   log.warn("Warning message.");
   log.debug("Debug message.");
   log.error("Error message.");
   log.error("Error with Exception.", new Exception("Test exception."));
   assertEquals(expectedDebug, log.isDebugEnabled());
 }
  /**
   * this is the main method of the servlet that will service all get requests.
   *
   * @param request HttpServletRequest
   * @param responce HttpServletResponce
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = null;
    try {
      try {
        session = request.getSession(true);
      } catch (Exception e) {
        Log.error(e, "PingSession2.doGet(...): error getting session");
        // rethrow the exception for handling in one place.
        throw e;
      }

      // Get the session data value
      Integer ival = (Integer) session.getAttribute("sessiontest.counter");
      // if there is not a counter then create one.
      if (ival == null) {
        ival = new Integer(1);
      } else {
        ival = new Integer(ival.intValue() + 1);
      }
      session.setAttribute("sessiontest.counter", ival);
      // if the session count is equal to five invalidate the session
      if (ival.intValue() == 5) {
        session.invalidate();
      }

      try {
        // Output the page
        response.setContentType("text/html");
        response.setHeader("SessionTrackingTest-counter", ival.toString());

        PrintWriter out = response.getWriter();
        out.println(
            "<html><head><title>Session Tracking Test 2</title></head><body><HR><BR><FONT size=\"+2\" color=\"#000066\">HTTP Session Test 2: Session create/invalidate <BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time: "
                + initTime
                + "</FONT><BR><BR>");
        hitCount++;
        out.println(
            "<B>Hit Count: " + hitCount + "<BR>Session hits: " + ival + "</B></body></html>");
      } catch (Exception e) {
        Log.error(e, "PingSession2.doGet(...): error getting session information");
        // rethrow the exception for handling in one place.
        throw e;
      }

    } catch (Exception e) {
      // log the excecption
      Log.error(e, "PingSession2.doGet(...): error.");
      // set the server responce to 500 and forward to the web app defined error page
      response.sendError(500, "PingSession2.doGet(...): error. " + e.toString());
    }
  } // end of the method
 public int getInt(String key) {
   String value = getProperty(key);
   if (value != null) {
     try {
       return Integer.parseInt(value);
     } catch (NumberFormatException e) {
       Log.error(this, "Invalid integer property: %s=%s", key, value);
     }
   } else {
     Log.error(this, "Undefined integer property: %s", key);
   }
   return 0;
 }
 public double getDbl(String key) {
   String value = getProperty(key);
   if (value != null) {
     try {
       return Double.parseDouble(value);
     } catch (NumberFormatException e) {
       Log.error(this, "Invalid double property: %s=%s", key, value);
     }
   } else {
     Log.error(this, "Undefined double property: %s", key);
   }
   return 0.0;
 }
Example #13
0
  /**
   * Connect by tcp.
   *
   * @param host the host
   * @param port the port
   * @return the t conn
   */
  public static synchronized TConn connectByTcp(String host, int port, long timeout) {

    TimeStamp t = TimeStamp.create();

    try {
      if (tcpconnector == null) {
        tcpconnector = new TDCConnector();
      }

      tcpconnector.connector.setConnectTimeoutMillis(timeout);

      ConnectFuture connFuture = tcpconnector.connector.connect(new InetSocketAddress(host, port));

      connFuture.awaitUninterruptibly(timeout);
      IoSession session = connFuture.getSession();

      TConn c = new TConn(session);

      session.setAttribute("conn", c);
      return c;
    } catch (Exception e) {
      log.error(
          "error, [" + host + ":" + port + "], cost: " + t.past() + "ms, timeout=" + timeout, e);
    }

    return null;
  }
Example #14
0
  /**
   * Submit an HTTP post to the given url, sending the data specified
   *
   * @param url url to post to
   * @param length number of bytes in the dataToSend to, er, send
   * @param dataToSend stream of bytes to be sent
   */
  public static boolean postData(URL url, long length, InputStream dataToSend) {
    try {
      HttpURLConnection con = (HttpURLConnection) url.openConnection();
      con.setDoInput(true);
      con.setDoOutput(true);
      con.setUseCaches(false);
      con.setRequestMethod("POST");
      con.setRequestProperty("Content-length", "" + length);

      OutputStream out = con.getOutputStream();
      byte buf[] = new byte[1 * 1024];
      int read;
      long sent = 0;
      GZIPOutputStream zipOut = new GZIPOutputStream(out);
      while ((read = dataToSend.read(buf)) != -1) {
        zipOut.write(buf, 0, read);
        sent += read;
        if (sent >= length) break;
      }

      zipOut.flush();
      zipOut.finish();
      zipOut.close();
      out.close();

      int rv = con.getResponseCode();
      _log.debug("Posted " + sent + " bytes: " + rv);
      return length == sent;
    } catch (IOException ioe) {
      _log.error("Error posting the data", ioe);
      return false;
    }
  }
 public void run() {
   while (true) {
     LinkedList<PacketCallbackStruct> list = null;
     try {
       queuedPacketCallbacksLock.lock();
       try {
         queuedPacketCallbacksNotEmpty.await();
       } catch (Exception e) {
         Log.error(
             "RDPServer.PacketCallbackThread: queuedPacketCallbacksNotEmpty.await() caught exception "
                 + e.getMessage());
       }
       list = queuedPacketCallbacks;
       queuedPacketCallbacks = new LinkedList<PacketCallbackStruct>();
     } finally {
       queuedPacketCallbacksLock.unlock();
     }
     if (Log.loggingNet)
       Log.net("RDPServer.PacketCallbackThread: Got " + list.size() + " queued packets");
     for (PacketCallbackStruct pcs : list) {
       try {
         callbackProcessPacket(pcs.cb, pcs.con, pcs.packet);
       } catch (Exception e) {
         Log.exception("RDPServer.PacketCallbackThread: ", e);
       }
     }
   }
 }
Example #16
0
 public String generateImage(OutputStream os, int numImage, FileFormatOption fileFormatOption)
     throws IOException {
   if (blocks.size() == 0) {
     final GraphicStrings error = new GraphicStrings(Arrays.asList("No @startuml found"));
     error.writeImage(os, fileFormatOption);
     return null;
   }
   try {
     for (BlockUml b : blocks) {
       final PSystem system = b.getSystem();
       final int nbInSystem = system.getNbImages();
       if (numImage < nbInSystem) {
         final CMapData cmap = new CMapData();
         system.exportDiagram(os, cmap, numImage, fileFormatOption);
         if (cmap.containsData()) {
           return system.getDescription() + "\n" + cmap.asString("plantuml");
         }
         return system.getDescription();
       }
       numImage -= nbInSystem;
     }
   } catch (InterruptedException e) {
     return null;
   }
   Log.error("numImage is too big = " + numImage);
   return null;
 }
Example #17
0
  /**
   * Reads file into byte array, detects charset and converts from this charset to UTF8
   *
   * @param file file to decode and convert to UTF8
   * @return
   * @throws IOException
   * @throws CharacterCodingException
   */
  public static synchronized byte[] convertFileToUTF8ByteArray(File file)
      throws IOException, CharacterCodingException {
    FileInputStream in = null;
    DataInputStream inStream = null;
    try {
      in = new FileInputStream(file);
      inStream = new DataInputStream(in);
      byte[] buf = new byte[(int) file.length()];
      int nrRead = inStream.read(buf);

      UniversalDetector detector = new UniversalDetector(null);
      detector.handleData(buf, 0, nrRead);
      detector.dataEnd();

      String encoding = detector.getDetectedCharset();
      detector.reset();
      if (encoding != null) {
        if (!encoding.equals(Jeeves.ENCODING)) {
          Log.error(Log.JEEVES, "Detected character set " + encoding + ", converting to UTF-8");
          return convertByteArrayToUTF8ByteArray(buf, encoding);
        }
      }
      return buf;
    } finally {
      if (in != null) {
        IOUtils.closeQuietly(in);
      }
      if (inStream != null) {
        IOUtils.closeQuietly(inStream);
      }
    }
  }
  /**
   * Sell a current holding of stock shares for the given trader. Dispatch to the Trade Portfolio
   * JSP for display
   *
   * @param userID The User buying shares
   * @param symbol The stock to sell
   * @param indx The unique index identifying the users holding to sell
   * @param ctx the servlet context
   * @param req the HttpRequest object
   * @param resp the HttpResponse object
   * @exception javax.servlet.ServletException If a servlet specific exception is encountered
   * @exception javax.io.IOException If an exception occurs while writing results back to the user
   */
  void doSell(
      ServletContext ctx,
      HttpServletRequest req,
      HttpServletResponse resp,
      String userID,
      Integer holdingID)
      throws ServletException, IOException {
    String results = "";
    try {
      OrderDataBean orderData = tAction.sell(userID, holdingID, TradeConfig.orderProcessingMode);

      req.setAttribute("orderData", orderData);
      req.setAttribute("results", results);
    } catch (java.lang.IllegalArgumentException e) { // this is a user error so I will
      // just log the exception and then later on I will redisplay the portfolio page
      // because this is just a user exception
      Log.error(
          e,
          "TradeServletAction.doSell(...)",
          "illegal argument, information should be in exception string",
          "user error");
    } catch (Exception e) {
      // log the exception with error page
      throw new ServletException(
          "TradeServletAction.doSell(...)"
              + " exception selling holding "
              + holdingID
              + " for user ="
              + userID,
          e);
    }
    requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.ORDER_PAGE));
  }
 public String getStr(String key) {
   String value = getProperty(key);
   if (value == null) {
     Log.error(this, "Undefined string property: %s", key);
   }
   return value;
 }
 public void handleUpdateWorldNode(long oid, WorldManagerClient.UpdateWorldNodeMessage wnodeMsg) {
   PerceiverData perceiverData = perceiverDataMap.get(oid);
   if (perceiverData == null) {
     if (Log.loggingDebug)
       Log.debug(
           "ProximityTracker.handleMessage: ignoring updateWNMsg for oid "
               + oid
               + " because PerceptionData for oid not found");
     return;
   }
   BasicWorldNode bwnode = wnodeMsg.getWorldNode();
   if (Log.loggingDebug)
     Log.debug(
         "ProximityTracker.handleMessage: UpdateWnode for "
             + oid
             + ", loc "
             + bwnode.getLoc()
             + ", dir "
             + bwnode.getDir());
   if (perceiverData.wnode != null) {
     perceiverData.previousLoc = perceiverData.lastLoc;
     perceiverData.wnode.setDirLocOrient(bwnode);
     perceiverData.wnode.setInstanceOid(bwnode.getInstanceOid());
     perceiverData.lastLoc = perceiverData.wnode.getLoc();
   } else
     Log.error(
         "ProximityTracker.handleMessage: In UpdateWorldNodeMessage for oid "
             + oid
             + ", perceiverData.wnode is null!");
   updateEntity(perceiverData);
 }
 public void handleMessage(Message msg, int flags) {
   try {
     lock.lock();
     if (activated == false) return; // return true;
     if (msg.getMsgType() == Behavior.MSG_TYPE_COMMAND) {
       Behavior.CommandMessage cmdMsg = (Behavior.CommandMessage) msg;
       String command = cmdMsg.getCmd();
       // Remove the executor, because anything we do will
       // end the current execution.
       Engine.getExecutor().remove(this);
       if (Log.loggingDebug)
         Log.debug(
             "BaseBehavior.onMessage: command = "
                 + command
                 + "; oid = "
                 + obj.getOid()
                 + "; name "
                 + obj.getName());
       if (command.equals(MSG_CMD_TYPE_GOTO)) {
         GotoCommandMessage gotoMsg = (GotoCommandMessage) msg;
         Point destination = gotoMsg.getDestination();
         mode = MSG_CMD_TYPE_GOTO;
         roamingBehavior = true;
         gotoSetup(destination, gotoMsg.getSpeed());
       } else if (command.equals(MSG_CMD_TYPE_STOP)) {
         followTarget = null;
         pathState.clear();
         obj.getWorldNode().setDir(new MVVector(0, 0, 0));
         obj.updateWorldNode();
         mode = MSG_CMD_TYPE_STOP;
         // If roamingBehavior is set, that means that we
         // used formerly had a roaming behavior, so send
         // an ArrivedEventMessage so that the other
         // behavior starts up again.
         if (roamingBehavior) {
           try {
             Engine.getAgent().sendBroadcast(new ArrivedEventMessage(obj));
           } catch (Exception e) {
             Log.error(
                 "BaseBehavior.onMessage: Error sending ArrivedEventMessage, error was '"
                     + e.getMessage()
                     + "'");
             throw new RuntimeException(e);
           }
         }
       } else if (command.equals(BaseBehavior.MSG_CMD_TYPE_FOLLOW)) {
         FollowCommandMessage followMsg = (FollowCommandMessage) msg;
         mode = MSG_CMD_TYPE_FOLLOW;
         followSetup(followMsg.getTarget(), followMsg.getSpeed());
       }
     } else if (msg.getMsgType() == WorldManagerClient.MSG_TYPE_MOB_PATH_CORRECTION) {
       Engine.getExecutor().remove(this);
       interpolatePath();
       interpolatingPath = false;
     }
     // return true;
   } finally {
     lock.unlock();
   }
 }
Example #22
0
    public Writable call(Class<?> protocol, Writable param, long receivedTime) throws IOException {
      try {
        Invocation call = (Invocation) param;
        if (verbose) log("Call: " + call);

        Method method = protocol.getMethod(call.getMethodName(), call.getParameterClasses());
        method.setAccessible(true);

        int qTime = (int) (System.currentTimeMillis() - receivedTime);
        long startNanoTime = System.nanoTime();
        Object value = method.invoke(instance, call.getParameters());
        long processingMicroTime = (System.nanoTime() - startNanoTime) / 1000;
        if (LOG.isDebugEnabled()) {
          LOG.debug(
              "Served: "
                  + call.getMethodName()
                  + " queueTime (millisec)= "
                  + qTime
                  + " procesingTime (microsec)= "
                  + processingMicroTime);
        }
        rpcMetrics.rpcQueueTime.inc(qTime);
        rpcMetrics.rpcProcessingTime.inc(processingMicroTime);

        MetricsTimeVaryingRate m =
            (MetricsTimeVaryingRate) rpcMetrics.registry.get(call.getMethodName());
        if (m == null) {
          try {
            m = new MetricsTimeVaryingRate(call.getMethodName(), rpcMetrics.registry);
          } catch (IllegalArgumentException iae) {
            // the metrics has been registered; re-fetch the handle
            LOG.debug("Error register " + call.getMethodName(), iae);
            m = (MetricsTimeVaryingRate) rpcMetrics.registry.get(call.getMethodName());
          }
        }
        // record call time in microseconds
        m.inc(processingMicroTime);

        if (verbose) log("Return: " + value);

        return new ObjectWritable(method.getReturnType(), value);

      } catch (InvocationTargetException e) {
        Throwable target = e.getTargetException();
        if (target instanceof IOException) {
          throw (IOException) target;
        } else {
          IOException ioe = new IOException(target.toString());
          ioe.setStackTrace(target.getStackTrace());
          throw ioe;
        }
      } catch (Throwable e) {
        if (!(e instanceof IOException)) {
          LOG.error("Unexpected throwable object ", e);
        }
        IOException ioe = new IOException(e.toString());
        ioe.setStackTrace(e.getStackTrace());
        throw ioe;
      }
    }
 public void addTrackedPerceiver(
     Long perceiverOid, InterpolatedWorldNode wnode, Integer reactionRadius) {
   lock.lock();
   try {
     if (perceiverDataMap.containsKey(perceiverOid)) {
       // Don't add the object more than once.
       Log.error(
           "ProximityTracker.addTrackedPerceiver: perceiverOid "
               + perceiverOid
               + " is already in the set of local objects, for ProximityTracker instance "
               + this);
       return;
     }
     PerceiverData perceiverData = new PerceiverData(perceiverOid, reactionRadius, wnode);
     perceiverDataMap.put(perceiverOid, perceiverData);
   } finally {
     lock.unlock();
   }
   if (Log.loggingDebug)
     Log.debug(
         "ProximityTracker.addTrackedPerceiver: perceiverOid="
             + perceiverOid
             + " reactionRadius="
             + reactionRadius
             + " instanceOid="
             + instanceOid);
 }
Example #24
0
 public void stop() {
   if (!this.running) {
     Log.error("CountLogger.stop: CountLogger thread isn't running!");
   } else {
     this.running = false;
   }
 }
Example #25
0
 public final void exportDiagram(
     OutputStream os, StringBuilder cmap, int index, FileFormatOption fileFormatOption)
     throws IOException {
   List<BufferedImage> flashcodes = null;
   try {
     if ("split".equalsIgnoreCase(getSkinParam().getValue("flashcode"))
         && fileFormatOption.getFileFormat() == FileFormat.PNG) {
       final String s = getSource().getPlainString();
       flashcodes = exportSplitCompress(s);
     } else if ("compress".equalsIgnoreCase(getSkinParam().getValue("flashcode"))
         && fileFormatOption.getFileFormat() == FileFormat.PNG) {
       final String s = getSource().getPlainString();
       flashcodes = exportFlashcodeCompress(s);
     } else if (getSkinParam().getValue("flashcode") != null
         && fileFormatOption.getFileFormat() == FileFormat.PNG) {
       final String s = getSource().getPlainString();
       flashcodes = exportFlashcodeSimple(s);
     }
   } catch (WriterException e) {
     Log.error("Cannot generate flashcode");
     e.printStackTrace();
     flashcodes = null;
   }
   if (fileFormatOption.getFileFormat() == FileFormat.PDF) {
     exportDiagramInternalPdf(os, cmap, index, flashcodes);
     return;
   }
   if (fileFormatOption.getFileFormat() == FileFormat.MJPEG) {
     // exportDiagramInternalMjpeg(os);
     // return;*
     throw new UnsupportedOperationException();
   }
   lastInfo = exportDiagramInternal(os, cmap, index, fileFormatOption, flashcodes);
 }
  @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());
  }
  public static int getRowContains(String sTestCaseName, int colNum) throws Exception {

    int i;

    try {

      int rowCount = ExcelUtils.getRowUsed();

      for (i = 0; i < rowCount; i++) {

        if (ExcelUtils.getCellData(i, colNum).equalsIgnoreCase(sTestCaseName)) {

          break;
        }
      }

      return i;

    } catch (Exception e) {

      Log.error("Class ExcelUtil | Method getRowContains | Exception desc : " + e.getMessage());

      throw (e);
    }
  }
Example #28
0
  public void logData(File file, PSystem system) {
    final String warnOrError = system.getWarningOrError();
    if (warnOrError == null) {
      return;
    }
    synchronized (logDataInitized) {
      if (logData == null && logDataInitized.get() == false) {
        final String s = GraphvizUtils.getenvLogData();
        if (s != null) {
          setLogData(new File(s));
        }
        logDataInitized.set(true);
      }

      if (logData == null) {
        return;
      }
      // final PSystemError systemError = (PSystemError) system;
      PrintStream ps = null;
      try {
        ps = new PrintStream(new FileOutputStream(logData, true));
        ps.println("Start of " + file.getName());
        ps.println(warnOrError);
        ps.println("End of " + file.getName());
        ps.println();
      } catch (FileNotFoundException e) {
        Log.error("Cannot open " + logData);
        e.printStackTrace();
      } finally {
        if (ps != null) {
          ps.close();
        }
      }
    }
  }
Example #29
0
  /**
   * Loads an xml file from a URL after posting content to the URL.
   *
   * @param url
   * @param xmlQuery
   * @return
   * @throws IOException
   * @throws JDOMException
   */
  public static Element loadFile(URL url, Element xmlQuery) throws IOException, JDOMException {
    Element result = null;
    try {
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", "application/xml");
      connection.setRequestProperty(
          "Content-Length",
          "" + Integer.toString(getString(xmlQuery).getBytes(Jeeves.ENCODING).length));
      connection.setRequestProperty("Content-Language", "en-US");
      connection.setDoOutput(true);
      PrintStream out = new PrintStream(connection.getOutputStream(), true, Jeeves.ENCODING);
      out.print(getString(xmlQuery));
      out.close();

      SAXBuilder builder = getSAXBuilderWithoutXMLResolver(false); // new SAXBuilder();
      Document jdoc = builder.build(connection.getInputStream());

      result = (Element) jdoc.getRootElement().detach();
    } catch (Exception e) {
      Log.error(Log.ENGINE, "Error loading URL " + url.getPath() + " .Threw exception " + e);
      e.printStackTrace();
    }
    return result;
  }
  /**
   * Display User Profile information such as address, email, etc. for the given Trader Dispatch to
   * the Trade Account JSP for display
   *
   * @param userID The User to display profile info
   * @param ctx the servlet context
   * @param req the HttpRequest object
   * @param resp the HttpResponse object
   * @param results A short description of the results/success of this web request provided on the
   *     web page
   * @exception javax.servlet.ServletException If a servlet specific exception is encountered
   * @exception javax.io.IOException If an exception occurs while writing results back to the user
   */
  void doAccount(
      ServletContext ctx,
      HttpServletRequest req,
      HttpServletResponse resp,
      String userID,
      String results)
      throws javax.servlet.ServletException, java.io.IOException {
    try {

      AccountDataBean accountData = tAction.getAccountData(userID);
      AccountProfileDataBean accountProfileData = tAction.getAccountProfileData(userID);
      ArrayList orderDataBeans =
          (TradeConfig.getLongRun() ? new ArrayList() : (ArrayList) tAction.getOrders(userID));

      req.setAttribute("accountData", accountData);
      req.setAttribute("accountProfileData", accountProfileData);
      req.setAttribute("orderDataBeans", orderDataBeans);
      req.setAttribute("results", results);
      requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.ACCOUNT_PAGE));
    } catch (java.lang.IllegalArgumentException e) { // this is a user error so I will
      // forward them to another page rather than throw a 500
      req.setAttribute("results", results + "could not find account for userID = " + userID);
      requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.HOME_PAGE));
      // log the exception with an error level of 3 which means, handled exception but would
      // invalidate a automation run
      Log.error(
          "TradeServletAction.doAccount(...)",
          "illegal argument, information should be in exception string",
          e);
    } catch (Exception e) {
      // log the exception with error page
      throw new ServletException(
          "TradeServletAction.doAccount(...)" + " exception user =" + userID, e);
    }
  }