private void logEx(String msg, Throwable ex, Level level) {
   if (this.verbose) {
     log.log(level, msg, ex);
   } else {
     log.log(level, msg + ex.getMessage());
   }
 }
 /**
  * Print usage information about threads from this factory to logger with the provided priority
  *
  * @param logger
  */
 public synchronized void printUsageInformation(final Logger logger, final Priority priority) {
   logger.debug("Number of threads monitored: " + getnThreadsAnalyzed());
   logger.debug(
       "Total runtime " + new AutoFormattingTime(TimeUnit.MILLISECONDS.toNanos(getTotalTime())));
   for (final State state : State.values()) {
     logger.debug(
         String.format(
             "\tPercent of time spent %s is %.2f",
             state.getUserFriendlyName(), getStatePercent(state)));
   }
   logger.log(
       priority,
       String.format(
           "CPU      efficiency : %6.2f%% of time spent %s",
           getStatePercent(State.USER_CPU), State.USER_CPU.getUserFriendlyName()));
   logger.log(
       priority,
       String.format(
           "Walker inefficiency : %6.2f%% of time spent %s",
           getStatePercent(State.BLOCKING), State.BLOCKING.getUserFriendlyName()));
   logger.log(
       priority,
       String.format(
           "I/O    inefficiency : %6.2f%% of time spent %s",
           getStatePercent(State.WAITING_FOR_IO), State.WAITING_FOR_IO.getUserFriendlyName()));
   logger.log(
       priority,
       String.format(
           "Thread inefficiency : %6.2f%% of time spent %s",
           getStatePercent(State.WAITING), State.WAITING.getUserFriendlyName()));
 }
  private void requestNextLinks(LevelLink levelLink) throws InterruptedException {

    int currentLevel = levelLink.getLevel() + 1;

    String ch = "";
    for (int i = 0; i < currentLevel; i++) {
      ch = ch + "--";
    }

    if (currentLevel >= maxDeep) {
      return;
    }

    randomPause();

    Elements links = getLinks(levelLink.getLink());

    if (links == null) {
      return;
    }

    LOG.log(
        Level.DEBUG,
        " "
            + ch
            + " "
            + levelLink.getLink()
            + " ||| Thread: "
            + Thread.currentThread().getName()
            + " ||| level: "
            + currentLevel
            + " newLinks="
            + links.size());

    // get all ref on a page
    for (Element element : links) {
      URL url = null;
      try {
        url = new URL(element.attr("abs:href"));
      } catch (MalformedURLException e) {
        LOG.log(Level.INFO, "Exception: ", e);
      }
      String newURI = Utils.toFullForm(url, false);
      if (newURI == null) {
        continue;
      }
      putLink(new LevelLink(newURI, currentLevel));
    }

    LevelLink nextLevelLink = readNextLink();
    if (nextLevelLink != null) {
      requestNextLinks(nextLevelLink);
    }
  }
  /**
   * Do session filter
   *
   * @param request HttpServletRequest
   * @param response ServletResponse
   * @param chain A FilterChain is an object provided by the servlet container to the developer
   *     giving a view into the invocation chain of a filtered request for a resource. Filters use
   *     the FilterChain to invoke the next filter in the chain, or if the calling filter is the
   *     last filter in the chain, to invoke the resource at the end of the chain.
   */
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    // Instance HttpServletRequest
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    // Get submit URL
    String url = httpServletRequest.getRequestURI();

    // Print URL
    if (logger.isDebugEnabled()) {
      logger.log(ComLogger.DEBUG, url);
    }

    // 过滤/page/ 路径.jsp|.html
    if (url.matches("^(\\w|\\W)*\\.(jsp|html)$")) {

      HttpSession session = httpServletRequest.getSession();
      UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USER_INFO_SESSION);

      if (userInfo == null || "".equals(userInfo)) {
        session.invalidate();

        if (logger.isDebugEnabled()) {
          logger.log(ComLogger.DEBUG, "SESSION过期,url:" + url);
        }

        if (url.matches("^.+(/page/|/main\\.html).*$")) {

          String QueryString = httpServletRequest.getQueryString();
          if ("hash=".equals(QueryString) || QueryString == null || "".equals(QueryString)) {
            QueryString = "";
          } else {
            QueryString = "?" + QueryString;
          }
          httpServletRequest.setAttribute(
              "url", url.substring(Constants.getProjectUrl().length() + 1) + QueryString);
          httpServletRequest
              .getRequestDispatcher("/login.jsp")
              .forward(httpServletRequest, response);

        } else {
          HttpServletResponse newResponse = (HttpServletResponse) response;
          newResponse.setHeader("sessiontimeout", "1");
          //					newResponse.setStatus(998);
          newResponse.setContentType("text/plain;charset=UTF-8");
          newResponse.getWriter().write("{success:false,msg:\"您的登陆信息已过期,请先登录。\"}");
        }

        return;
      }
    }
    chain.doFilter(httpServletRequest, response);
  }
Exemple #5
0
  private void init() {
    try {
      Method[] mh = IHook.class.getMethods();

      for (Method method : mh) {
        if (!method.isAnnotationPresent(HookEnumType.class)) {
          continue;
        }

        HookEnumType annot = method.getAnnotation(HookEnumType.class);

        if (annot.value() == this) {
          invokingMethod = method;
          return;
        }
      }

      throw new Exception(
          "No method found for HookType."
              + this
              + " enum in IHook.java! Are you missing annotations?");
    } catch (Exception e) {
      _log.log(Level.ERROR, "", e);
    }
  }
Exemple #6
0
  private void kill(L2PcInstance activeChar, L2Character target) {
    if (target instanceof L2PcInstance) {
      if (!target.isGM()) {
        target.stopAllEffects(); // e.g. invincibility effect
      }
      target.reduceCurrentHp(target.getMaxHp() + target.getMaxCp() + 1, activeChar, null);
    } else {
      boolean targetIsInvul = false;
      if (target.isInvul()) {
        targetIsInvul = true;
        target.setIsInvul(false);
      }

      target.reduceCurrentHp(target.getMaxHp() + 1, activeChar, null);

      if (targetIsInvul) {
        target.setIsInvul(true);
      }
    }
    if (Config.DEBUG) {
      _log.log(
          Level.DEBUG,
          "GM: "
              + activeChar.getName()
              + '('
              + activeChar.getObjectId()
              + ')'
              + " killed character "
              + target.getObjectId());
    }
  }
  public static ChanceCondition parse(StatsSet set) {
    try {
      TriggerType trigger = set.getEnum("chanceType", TriggerType.class, null);
      int chance = set.getInteger("activationChance", -1);
      int mindmg = set.getInteger("activationMinDamage", -1);
      String elements = set.getString("activationElements", null);
      String activationSkills = set.getString("activationSkills", null);
      boolean pvpOnly = set.getBool("pvpChanceOnly", false);
      int bySkillId = set.getInteger("triggeredById", -1);

      if (trigger != null) {
        return new ChanceCondition(
            trigger,
            chance,
            mindmg,
            parseElements(elements),
            parseActivationSkills(activationSkills),
            pvpOnly,
            bySkillId);
      }
    } catch (Exception e) {
      _log.log(Level.ERROR, "", e);
    }
    return null;
  }
 private void logStats(MemoryPoolMXBean memPool, Level level) {
   boolean supported = memPool.isUsageThresholdSupported();
   String n = "\n";
   log.log(
       level,
       n
           + "MemoryPool name      : "
           + memPool.getName()
           + n
           + "MemoryPool usage     : "
           + niceFormat(memPool)
           + n
           + "MemoryPool peak      : "
           + getPeakFormat(memPool)
           + n
           + "MemoryPool threshold : "
           + getThresholdFormat(memPool)
           + n
           + "MemoryPool count     : "
           + ((supported) ? memPool.getUsageThresholdCount() : "n/a")
           + n
           + "MemoryPool exceeded  : "
           + ((supported) ? memPool.isUsageThresholdExceeded() : "n/a")
           + n
           + "MemoryPool isHeap?   : "
           + ((memPool.getType() == MemoryType.HEAP) ? "HEAP" : "NOT HEAP")
           + n
           + "---");
 }
 void stop(Runnable callback) {
   if (player != null) {
     new Tween(player.getVolume())
         .tweenToZero(
             0.06,
             10L,
             (curVolume) -> {
               player.setVolume(curVolume);
             },
             (zeroVolume) -> {
               isPlaying = false;
               try {
                 if (currentAudioIn != null) {
                   currentAudioIn.close();
                 }
                 player.stop();
                 callback.run();
               } catch (IOException | IllegalStateException | NullPointerException ex) {
                 log.log(Level.ERROR, null, ex);
               }
             });
   } else {
     callback.run();
   }
 }
  @Override
  public boolean deleteAll(List<Role> entities) throws SQLException {
    boolean retval = false;

    try {

      con = new DBConnection();

      if (con.connect()) {

        Iterator<Role> iterator = entities.iterator();

        while (iterator.hasNext()) {

          Role entity = iterator.next();

          cstmt = (CallableStatement) con.getConnection().prepareCall("{call sp_del_role(?)}");
          cstmt.setString(1, entity.getRolename());

          con.customQuery(cstmt);
        }
      }

      retval = true;

    } catch (ClassNotFoundException ex) {
      logger.log(Priority.ERROR, ex.toString());
    } catch (SQLException ex) {
      throw ex;
    } finally {
      con.disconnect();
    }
    return retval;
  }
  public static ChanceCondition parse(
      String chanceType,
      int chance,
      int mindmg,
      String elements,
      String activationSkills,
      boolean pvpOnly,
      int bySkillId) {
    try {
      if (chanceType == null) {
        return null;
      }

      TriggerType trigger = Enum.valueOf(TriggerType.class, chanceType);

      if (trigger != null) {
        return new ChanceCondition(
            trigger,
            chance,
            mindmg,
            parseElements(elements),
            parseActivationSkills(activationSkills),
            pvpOnly,
            bySkillId);
      }
    } catch (Exception e) {
      _log.log(Level.ERROR, "", e);
    }

    return null;
  }
  // com.feilong.spring.aspects.UserManager
  @Around(value = "pointcut()")
  public void around(ProceedingJoinPoint joinPoint) throws Throwable {
    // LoggerFactory.
    // log.
    Method method = getMethod(joinPoint, Log.class);
    String methodName = method.getName();
    Date begin = new Date();
    // 通过反射执行目标对象的连接点处的方法
    joinPoint.proceed();
    // 在来得到方法名吧,就是通知所要织入目标对象中的方法名称
    Date end = new Date();
    Object[] args = joinPoint.getArgs();
    // for (Object arg : args){
    // log.info("arg:{}", arg.toString());
    // }
    // log.info("{},{}", begin, end);

    _log = (Log) getAnnotation(joinPoint, Log.class);
    String level = _log.level();
    // log.debug("level:{}", level);
    // 输出的日志 怪怪的 02:13:10 INFO (NativeMethodAccessorImpl.java:?) [invoke0()] method:addUser([1018,
    // Jummy]),耗时:0
    // ReflectUtil.invokeMethod(log, level, "method:{}({}),耗时:{}", objects);

    String format = "method:%s(%s),耗时:%s";
    Object[] objects = {methodName, args, DateUtil.getIntervalForView(begin, end)};
    Object message = StringUtil.format(format, objects);
    log.log(Level.toLevel(level), message);
  }
  @Override
  public boolean delete(String key) throws SQLException {
    boolean retval = false;
    ResultSet rs = null;

    try {

      con = new DBConnection();

      if (con.connect()) {

        cstmt = (CallableStatement) con.getConnection().prepareCall("{call sp_del_role(?)}");

        cstmt.setString(1, key);

        rs = con.customQuery(cstmt);
      }

      retval = true;

    } catch (ClassNotFoundException ex) {
      logger.log(Priority.ERROR, ex.toString());
    } catch (SQLException ex) {
      throw ex;
    } finally {
      con.disconnect();
    }

    return retval;
  }
Exemple #14
0
  public void send(NetInfMessage message) throws NetInfCheckedException {
    // Set the encoding format directly at the beginning.
    message.setSerializeFormat(this.serializeFormat);

    LOG.debug("NetInfMessage to be send: \n" + message);

    int encoding = this.messageEncoder.getUniqueEncoderId();
    LOG.debug("Encoding message with encoder " + encoding);

    byte[] payload = this.messageEncoder.encodeMessage(message);
    LOG.debug("Payload size: " + payload.length);

    LOG.log(
        DemoLevel.DEMO,
        "(COMM ) Sending " + message.describe() + " (size: " + payload.length + "B)");

    try {
      this.connection.send(new AtomicMessage(encoding, payload));
    } catch (IOException e) {
      try {
        LOG.warn("Error sending message: Retry...");
        setup(this.host, this.port);
        this.connection.send(new AtomicMessage(encoding, payload));
      } catch (IOException ex) {
        throw new NetInfCheckedException(ex);
      }
    }
  }
  private void logResultInfo(
      int queryNr,
      int queryMixRun,
      double timeInSeconds,
      String queryString,
      byte queryType,
      int resultCount) {
    StringBuffer sb = new StringBuffer(1000);
    sb.append("\n\n\tQuery " + queryNr + " of run " + queryMixRun + " has been executed ");
    sb.append("in " + String.format("%.6f", timeInSeconds) + " seconds.\n");
    sb.append("\n\tQuery string:\n\n");
    sb.append(queryString);
    sb.append("\n\n");

    // Log results
    if (queryType == Query.DESCRIBE_TYPE)
      sb.append("\tQuery(Describe) result (" + resultCount + " Bytes): \n\n");
    else if (queryType == Query.CONSTRUCT_TYPE)
      sb.append("\tQuery(Construct) result (" + resultCount + " Bytes): \n\n");
    else sb.append("\tQuery results (" + resultCount + " results): \n\n");

    sb.append(
        "\n__________________________________________________________________________________\n");
    logger.log(Level.ALL, sb.toString());
  }
Exemple #16
0
 public void logStats(String _preString) {
   log.log(Level.INFO, _preString + "\n\n" + getHeapComposite());
   if (verbose) {
     for (MemoryPoolMXBean memPool : memoryPoolMap.values()) {
       logStats(memPool, Level.INFO);
     }
   }
 }
  protected void onIncomingBrokerMessage(String message) {

    LOGGER.log(Level.TRACE, "broker (" + this.getClass() + ") received message: " + message);

    LinkedList<MessageMiddleware> messageCommon = translator.toMiddlewareMessageList(message);

    processor.processBrokerMessage(service, messageCommon);
  }
 /**
  * Print usage information about threads from this factory to logger with the provided priority
  *
  * @param logger
  */
 public synchronized void printUsageInformation(final Logger logger, final Priority priority) {
   logger.log(priority, "Number of activeThreads used: " + getNThreadsCreated());
   logger.log(priority, "Total runtime " + new AutoFormattingTime(getTotalTime() / 1000.0));
   for (final Thread.State state : TRACKED_STATES) {
     logger.log(
         priority,
         String.format(
             "  Fraction of time spent %s is %.2f (%s)",
             prettyName(state),
             getStateFraction(state),
             new AutoFormattingTime(getStateTime(state) / 1000.0)));
   }
   logger.log(
       priority,
       String.format(
           "Efficiency of multi-threading: %.2f%% of time spent doing productive work",
           getStateFraction(Thread.State.RUNNABLE) * 100));
 }
 public void log(String str, int level, Object obj, Throwable t) {
   if (logger == null) {
     logger = org.apache.log4j.Logger.getLogger("NullLogger");
     logger.error("Logger was reset to null. Creating null logger");
   }
   if (logger != null) {
     logger.log(str, Priority.toPriority(level), obj, t);
   }
 }
 public synchronized LogEvent log(LogEvent ev) {
   org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ev.getRealm());
   if (logger.isEnabledFor(_level)) {
     ByteArrayOutputStream w = new ByteArrayOutputStream();
     PrintStream p = new PrintStream(w);
     ev.dump(p, "");
     logger.log(_level, w.toString());
   }
   return ev;
 }
 public List<VendorRequestHistoryBean> getRows()
     throws DataSourceLookupException, DataAccessException {
   if (isTableEmpty() && !hide) {
     rows = SdpOrderDetailDBWrapper.getVendorRequestHistoryBySdpOrderId(this.sdpOrderId);
   } else if (isTableEmpty() && hide) {
     rows = new ArrayList<VendorRequestHistoryBean>(0);
   }
   logger.log(Level.DEBUG, "Provisioning records found >> " + rows.size());
   return rows;
 }
 private static void close(Closeable resource) {
   if (resource != null) {
     try {
       resource.close();
     } catch (IOException e) {
       logger.log(
           Level.ERROR, "Failed to close BufferedInputStream/BufferedOutputString resources.");
     }
   }
 }
 public static Boolean mapOnOffParameterToBool(String value) {
   switch (value.toLowerCase()) {
     case MESSAGE_PARAMETER_ON:
       return true;
     case MESSAGE_PARAMETER_OFF:
       return false;
     default:
       LOGGER.log(Level.ERROR, "unexpected (0,1) parameter value: " + value);
       return false;
   }
 }
Exemple #24
0
 @Override
 public void span(
     long traceId,
     long spanId,
     long parentId,
     long start,
     long stop,
     String description,
     Map<String, String> data) {
   log.log(SPAN, format(traceId, spanId, parentId, start, stop, description, data));
 }
  @Override
  public void error(String message) {

    if (isErrorEnabled()) {

      try {
        wrappedLogger.log(CALLING_CLASS_FQCN, Level.ERROR, message, null);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  @Override
  public void debug(String message) {

    if (isDebugEnabled()) {

      try {
        wrappedLogger.log(CALLING_CLASS_FQCN, Level.DEBUG, message, null);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Exemple #27
0
 @Override
 protected void log(int level, Object message, Throwable tx) {
   switch (level) {
     case LEVEL_FATAL:
       logger.log(SUPER_FQCN, Level.FATAL, message, tx);
       break;
     case LEVEL_ERROR:
       logger.log(SUPER_FQCN, Level.ERROR, message, tx);
       break;
     case LEVEL_WARN:
       logger.log(SUPER_FQCN, Level.WARN, message, tx);
       break;
     case LEVEL_INFO:
       logger.log(SUPER_FQCN, Level.INFO, message, tx);
       break;
     case LEVEL_DEBUG:
       logger.log(SUPER_FQCN, Level.DEBUG, message, tx);
       break;
     case LEVEL_TRACE:
       if (hasTrace) logger.log(SUPER_FQCN, Level.TRACE, message, tx);
       break;
     default:
       break;
   }
 }
  private final String getFileAsString(String filename) throws IOException {
    File file = new File(filename);

    if (!file.exists()) {
      logger.log(Level.ERROR, "template file " + filename + " does not exist");
      System.exit(1);
    }
    final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    final byte[] bytes = new byte[(int) file.length()];
    bis.read(bytes);
    bis.close();
    return new String(bytes);
  }
  @Override
  public void error(Throwable throwable) {

    if (isErrorEnabled()) {

      try {
        String message = throwable.getMessage();
        wrappedLogger.log(CALLING_CLASS_FQCN, Level.ERROR, message, throwable);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  public void parseAndValidateConnectionDocument(String connectionDocument)
      throws Exception, SAXException, IOException, ParserConfigurationException {
    try {
      // validate the connections document against the xsd
      validateConnectionsXML(connectionDocument);
      // create document builder
      Element docEle = createDocumentBuilder(connectionDocument);

      // parse validate the connection_specification tag in connections
      // document
      parseConnectionSpecifications(docEle);
    } catch (Exception e) {

      TRACE.log(
          TraceLevel.ERROR,
          Messages.getString("Error_ConnectionDocumentHelper.1"),
          e); //$NON-NLS-1$
      LOG.log(
          LogLevel.ERROR, Messages.getString("Error_ConnectionDocumentHelper.1"), e); // $NON-NLS-1$
      throw e;
    }
  }