Beispiel #1
1
  /**
   * Load a system library from a stream. Copies the library to a temp file and loads from there.
   *
   * @param libname name of the library (just used in constructing the library name)
   * @param is InputStream pointing to the library
   */
  private void loadLibraryFromStream(String libname, InputStream is) {
    try {
      File tempfile = createTempFile(libname);
      OutputStream os = new FileOutputStream(tempfile);

      logger.debug("tempfile.getPath() = " + tempfile.getPath());

      long savedTime = System.currentTimeMillis();

      // Leo says 8k block size is STANDARD ;)
      byte buf[] = new byte[8192];
      int len;
      while ((len = is.read(buf)) > 0) {
        os.write(buf, 0, len);
      }

      os.flush();
      InputStream lock = new FileInputStream(tempfile);
      os.close();

      double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3;
      logger.debug("Copying took " + seconds + " seconds.");

      logger.debug("Loading library from " + tempfile.getPath() + ".");
      System.load(tempfile.getPath());

      lock.close();
    } catch (IOException io) {
      logger.error("Could not create the temp file: " + io.toString() + ".\n");
    } catch (UnsatisfiedLinkError ule) {
      logger.error("Couldn't load copied link file: " + ule.toString() + ".\n");
      throw ule;
    }
  }
  /**
   * Return an instance of a logger
   *
   * @param the class name of the load to load
   * @param messageCatalog the resource bundle containing messages
   * @param loggerID an identifier for the logger
   * @param resourceName a name or context to associate with this logger instance.
   * @return a ready for use logger
   */
  private static Logger getLogger(
      String loggerClassName,
      ResourceBundle messageCatalog,
      String loggerID,
      String resourceName) { // , FFDC ffdc) {
    Logger logger = null;
    Class logClass = null;

    try {
      logClass = Class.forName(loggerClassName);
    } catch (NoClassDefFoundError ncdfe) {
      return null;
    } catch (ClassNotFoundException cnfe) {
      return null;
    }
    if (null != logClass) {
      // Now instantiate the log
      try {
        logger = (Logger) logClass.newInstance();
      } catch (IllegalAccessException e) {
        return null;
      } catch (InstantiationException e) {
        return null;
      } catch (ExceptionInInitializerError e) {
        return null;
      } catch (SecurityException e) {
        return null;
      }
      logger.initialise(messageCatalog, loggerID, resourceName);
    }

    return logger;
  }
  @Test
  public void testDiffRatios() {
    logger.info("\ntesting diffRatios()");
    double[] input = null;
    double[] result = null;
    assertEquals(0, MathUtil.diffRatios(input).length);
    input = new double[] {};
    assertEquals(0, MathUtil.diffRatios(input).length);
    input = new double[] {1};
    assertEquals(0, MathUtil.diffRatios(input).length);

    input = new double[] {1, 2};
    result = MathUtil.diffRatios(input);
    assertEquals(1, result.length);
    assertEquals(2.0, result[0], 0.0);

    input = new double[] {1, 2, 1, 5};
    result = MathUtil.diffRatios(input);
    assertEquals(3, result.length);
    assertEquals(2.0, result[0], 0.0);
    assertEquals(0.5, result[1], 0.0);
    assertEquals(5.0, result[2], 0.0);

    input = new double[] {1, 2, 0, 5, 8};
    result = MathUtil.diffRatios(input);
    logger.debug(ListArrayUtil.arrayToString(result));
    assertEquals(true, Double.isInfinite(result[2]));
    assertEquals(false, Double.isNaN(result[2]));
  }
  public boolean equals(SyncLogEntry entry) {

    Logger.e(
        "entry: "
            + entry.m_file_name
            + " tags: "
            + entry.m_tags
            + " hash: "
            + entry.m_hash_sum
            + " timestamp:"
            + entry.m_time_stamp);
    Logger.e(
        "this: "
            + this.m_file_name
            + " tags: "
            + this.m_tags
            + " hash: "
            + this.m_hash_sum
            + " timestamp:"
            + this.m_time_stamp);
    return this.m_file_name.equals(entry.m_file_name)
        && this.m_tags.equals(entry.m_tags)
        && this.m_hash_sum.equals(entry.m_hash_sum)
        && this.m_time_stamp.equals(entry.m_time_stamp);
  }
  /**
   * Removes the group created in the server stored contact list by the create group test, makes
   * sure that the corresponding event has been generated and verifies that the group is not in the
   * list any more.
   */
  public void postTestRemoveGroup() {
    logger.trace("testing removal of server stored groups");

    // first add a listener
    GroupChangeCollector groupChangeCollector = new GroupChangeCollector();
    opSetPersPresence1.addServerStoredGroupChangeListener(groupChangeCollector);

    try {
      // remove the group
      opSetPersPresence1.removeServerStoredContactGroup(
          opSetPersPresence1.getServerStoredContactListRoot().getGroup(testGroupName2));
    } catch (OperationFailedException ex) {
      logger.error("error removing group", ex);
    }

    groupChangeCollector.waitForEvent(10000);

    opSetPersPresence1.removeServerStoredGroupChangeListener(groupChangeCollector);

    // check whether we got group created event
    assertEquals("Collected Group Change event", 1, groupChangeCollector.collectedEvents.size());

    assertEquals(
        "Group name.",
        testGroupName2,
        ((ServerStoredGroupEvent) groupChangeCollector.collectedEvents.get(0))
            .getSourceGroup()
            .getGroupName());

    // check whether the group is still on the contact list
    ContactGroup group =
        opSetPersPresence1.getServerStoredContactListRoot().getGroup(testGroupName2);

    assertNull("A freshly removed group was still on the contact list.", group);
  }
Beispiel #6
0
  public int update(int oid, String quantity, String memo) { // 更新揀貨單的揀貨數量
    logger.debug(
        "OrderPlaceDDAO.update: "
            + "pickId: "
            + oid
            + ", quantity: "
            + quantity
            + ", memo: "
            + memo);

    EntityManager em = XPersistence.getManager();
    OrderPlaceD bean = em.find(OrderPlaceD.class, oid);
    logger.debug("OrderPlaceD.update: orderPlaceD: " + bean);
    if (bean != null) {
      //			bean.setQuantity(quantity);
      bean.setRemark(memo);
      try {
        em.merge(bean);
        XPersistence.commit();
      } catch (Exception e) {
        logger.error("OrderPlaceD.update: " + e);
      }
      return 1; // 1:成功
    }
    return 0; // 0:失敗
  }
  /**
   * Retransmits a packet to {@link #channel}. If the destination supports the RTX format, the
   * packet will be encapsulated in RTX, otherwise, the packet will be retransmitted as-is.
   *
   * @param pkt the packet to retransmit.
   * @param after the {@code TransformEngine} in the chain of {@code TransformEngine}s of the
   *     associated {@code MediaStream} after which the injection of {@code pkt} is to begin
   * @return {@code true} if the packet was successfully retransmitted, {@code false} otherwise.
   */
  public boolean retransmit(RawPacket pkt, TransformEngine after) {
    boolean destinationSupportsRtx = channel.getRtxPayloadType() != -1;
    boolean retransmitPlain;

    if (destinationSupportsRtx) {
      long rtxSsrc = getPairedSsrc(pkt.getSSRC());

      if (rtxSsrc == -1) {
        logger.warn("Cannot find SSRC for RTX, retransmitting plain.");
        retransmitPlain = true;
      } else {
        retransmitPlain = !encapsulateInRtxAndTransmit(pkt, rtxSsrc);
      }
    } else {
      retransmitPlain = true;
    }

    if (retransmitPlain) {
      MediaStream mediaStream = channel.getStream();

      if (mediaStream != null) {
        try {
          mediaStream.injectPacket(pkt, /* data */ true, after);
        } catch (TransmissionFailedException tfe) {
          logger.warn("Failed to retransmit a packet.");
          return false;
        }
      }
    }

    return true;
  }
Beispiel #8
0
  /** 基类实现消息监听接口,加上打印metaq监控日志的方法 */
  @Override
  public ConsumeConcurrentlyStatus consumeMessage(
      List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
    long startTime = System.currentTimeMillis();
    logger.info("receive_message:{}", msgs.toString());
    if (msgs == null || msgs.size() < 1) {
      logger.error("receive empty msg!");
      return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    List<Serializable> msgList = new ArrayList<>();
    for (MessageExt message : msgs) {
      msgList.add(decodeMsg(message));
    }

    final int reconsumeTimes = msgs.get(0).getReconsumeTimes();
    MsgObj msgObj = new MsgObj();
    msgObj.setReconsumeTimes(reconsumeTimes);
    msgObj.setMsgList(msgList);
    msgObj.setContext(context);
    context.setDelayLevelWhenNextConsume(getDelayLevelWhenNextConsume(reconsumeTimes));

    ConsumeConcurrentlyStatus status = doConsumeMessage(msgObj);
    logger.info(
        "ConsumeConcurrentlyStatus:{}|cost:{}", status, System.currentTimeMillis() - startTime);
    return status;
  }
  @Test
  public void testFileRecreated() throws Exception {

    // don't use the mock FileLogger in this test
    LogPersister.setContext(activity);
    LogPersister.setLogLevel(LEVEL.DEBUG);
    File file = new File(activity.getFilesDir(), FILE_NAME0);

    Logger logger = Logger.getLogger("package");
    LogPersister.storeLogs(true);

    logger.info("a message");

    waitForNotify(logger);
    assertTrue(file.exists());

    // If I deleted it instead of letting java.util.logger manage the files, will
    // java.util.logger recreate it?  Let's make sure it does.
    file.delete();
    assertFalse(file.exists());

    logger.info("another message");

    waitForNotify(logger);

    assertTrue(file.exists());
  }
  public void test() throws Exception {
    try {
      Logger logger = LoggerFactory.getLogger(this.getClass());
      String msg = "hello world " + diff;
      logger.info(msg);
      fail("NoSuchMethodError expected");
    } catch (NoSuchMethodError e) {
    }

    int lineCount = sps.stringList.size();
    assertTrue("number of lines should be 3 but was " + lineCount, lineCount == 3);

    // expected output:
    // SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding.
    // SLF4J: Your binding is version 1.4.x or earlier.
    // SLF4J: Upgrade your binding to version 1.6.x. or 2.0.x

    {
      String s = (String) sps.stringList.get(0);
      assertTrue(
          s.contains("SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding."));
    }
    {
      String s = (String) sps.stringList.get(1);
      assertTrue(s.contains("SLF4J: Your binding is version 1.5.5 or earlier."));
    }
    {
      String s = (String) sps.stringList.get(2);
      assertTrue(s.contains("SLF4J: Upgrade your binding to version 1.6.x. or 2.0.x"));
    }
  }
  /**
   * Handles registration of a new configuration form.
   *
   * @param event the <tt>ServiceEvent</tt> that notified us
   */
  public void serviceChanged(ServiceEvent event) {
    Object sService = AdvancedConfigActivator.bundleContext.getService(event.getServiceReference());

    // we don't care if the source service is not a configuration form
    if (!(sService instanceof ConfigurationForm)) return;

    ConfigurationForm configForm = (ConfigurationForm) sService;

    /*
     * This AdvancedConfigurationPanel is an advanced ConfigurationForm so
     * don't try to add it to itself.
     */
    if ((configForm == this) || !configForm.isAdvanced()) return;

    switch (event.getType()) {
      case ServiceEvent.REGISTERED:
        if (logger.isInfoEnabled())
          logger.info("Handling registration of a new Configuration Form.");

        this.addConfigForm(configForm);
        break;

      case ServiceEvent.UNREGISTERING:
        this.removeConfigForm(configForm);
        break;
    }
  }
Beispiel #12
0
  /** @invisible */
  public void start() {
    _myThread = null;
    _myDatagramSocket = null;
    _myThread = new Thread(this);
    try {
      Thread.sleep(1000);
    } catch (InterruptedException iex) {
      Logger.printError("UdpServer.start()", "oscServer sleep interruption " + iex);
    }
    try {
      _myDatagramSocket = new DatagramSocket(_myPort);
      _myInetAddress = InetAddress.getByName(_myAddress);
      Logger.printProcess(
          "UdpServer.start()", "new Unicast DatagramSocket created @ port " + _myPort);
    } catch (IOException ioex) {
      Logger.printError(
          "UdpServer.start()",
          " IOException, couldnt create new DatagramSocket @ port " + _myPort + " " + ioex);
    }

    if (_myDatagramSocket != null) {
      _myThread.start();
      isRunning = _myThread.isAlive();
      isSocket = true;
    } else {
      isRunning = false;
    }
  }
Beispiel #13
0
  /** @invisible */
  public void run() {
    if (_myDatagramSocket != null) {
      if (isRunning) {
        Logger.printProcess("UdpServer.run()", "UdpServer is running @ " + _myPort);
      }
    } else {
      Logger.printError("UdpServer.run()", "Socket is null. closing UdpServer.");
      return;
    }

    while (isRunning) {
      try {
        byte[] myBuffer = new byte[_myDatagramSize];
        DatagramPacket myPacket = new DatagramPacket(myBuffer, _myDatagramSize);
        _myDatagramSocket.receive(myPacket);
        _myListener.process(myPacket, _myPort);
      } catch (IOException ioex) {
        Logger.printProcess("UdpServer.run()", " socket closed.");
        break;
      } catch (ArrayIndexOutOfBoundsException ex) {
        Logger.printError("UdpServer.run()", "ArrayIndexOutOfBoundsException:  " + ex);
      }
    }
    dispose();
  }
  public static void main(String[] args) {
    Logger logger = null;
    List<Logger> loggerList = new ArrayList<Logger>();
    /*
     * here SystemLogger and error logger are implementation of an internal interface so the method remains same
     */
    logger = new SystemLogger();
    loggerList.add(logger);

    Logger logger1 = null;
    logger1 = new ErrorLogger();
    loggerList.add(logger1);

    /*
     * TraceLogger is a 3rd party implementation which does not implement our internal interface and it also doesn't
     * have the same logging method as the other implementations. so Here we make an adapter which implements the
     * internal interface and the adapter class internally uses the 3rd party class now this can be done via
     * composition as well as inheritance , this example uses composition
     */
    Logger logger2 = null;
    logger2 = new TraceLoggerAdapter();
    loggerList.add(logger2);

    // this example uses inheritance
    Logger logger3 = null;
    logger3 = new TraceLoggerInheritanceAdapter();
    loggerList.add(logger3);

    for (Logger genericLogger : loggerList) {
      genericLogger.log("test");
    }
  }
Beispiel #15
0
  /**
   * @param host
   * @param notify
   * @return
   */
  private boolean remove(SiteHost host, boolean notify) {
    Logger.info("WorkPool.remove, work site %s", host);

    boolean success = false;
    this.lockSingle();
    try {
      mapTime.remove(host);
      WorkSite site = mapSite.remove(host);
      if (site != null) {
        for (Naming naming : site.list()) {
          SiteSet set = mapNaming.get(naming);
          if (set != null) {
            set.remove(host);
          }
          if (set == null || set.isEmpty()) {
            mapNaming.remove(naming);
          }
        }
        success = true;

        if (notify) {
          CallPool.getInstance().refreshWorkSite();
        }
      }
    } catch (Throwable exp) {
      Logger.error(exp);
    } finally {
      this.unlockSingle();
    }
    return success;
  }
  private synchronized void checkTimeUpdate(long localTime, long utcTime) throws Exception {
    // broadcast
    _props.setProperty("utc", String.valueOf(utcTime));
    _props.setProperty("local", String.valueOf(localTime));

    TimeUpdateNotification notification =
        new TimeUpdateNotification(TimeUpdateNotification.UPDATE_UTC_TIME, _props);

    Notifier.getInstance().broadcast(notification);

    // wait
    try {
      wait(30000L); // 30 seconds
    } catch (Exception ex) {
    }

    // refreshTimeServer();
    // checkSuccess(_event, _sessions[0], _sm[0], IErrorCode.NO_ERROR);

    long offset = utcTime - localTime;
    Logger.debug("Input UTC Time = " + new Timestamp(utcTime));
    Logger.debug("Input Local Time = " + new Timestamp(localTime));
    Logger.debug("Expected offset: " + offset);

    // check local to utc
    Timestamp ts = TimeUtil.localToUtcTimestamp(_testDate);
    Logger.debug("Converted local to UTc timestamp: " + ts);
    assertEquals("LocalToUtc conversion fail", offset, ts.getTime() - _testDate.getTime());

    // check utc to local
    ts = TimeUtil.utcToLocalTimestamp(_testDate);
    Logger.debug("Converted utc to local timestamp: " + ts);
    assertEquals("UtcToLocal conversion fail", offset, _testDate.getTime() - ts.getTime());
  }
  protected void prepareTestData() throws java.lang.Exception {
    long currentTime = TimeUtil.getCurrentLocalTimeMillis();
    long oneHour = 3600000;
    long positive = 8 * oneHour + currentTime;
    long negative = -5 * oneHour + currentTime;

    _times =
        new long[][] {
          {positive, currentTime},
          {currentTime, currentTime},
          {negative, currentTime},
        };

    Calendar cal = GregorianCalendar.getInstance();
    cal.set(2002, 9, 19, 5, 5, 29);
    _testDate = new Timestamp(cal.getTime().getTime());

    Logger.debug("Test date (ts)= " + _testDate);
    Logger.debug("Test date (ms)= " + _testDate.getTime());

    _timeServer = UtcTimeServer.getInstance();

    TimeUtil.setTimeServer(_timeServer);

    _event = new GetUtcTimeEvent();

    //    createSessions(1);
    //    createStateMachines(1);

  }
  @Test
  public void testThreadQueueOrderSetters() throws Exception {
    FileLoggerMock mockFileLogger = setFileLoggerInstanceField(activity);
    // order in the file should reflect the order of the calls even though multi-threaded:
    LogPersister.setContext(activity);
    Logger logger = Logger.getLogger("pkg");
    final int limit = 100;
    for (int i = 0; i < limit; i++) {
      if (i % 2 == 0) {
        LogPersister.storeLogs(true);
      } else {
        LogPersister.storeLogs(false);
      }
      if (i % 2 == 0) {
        LogPersister.setLogLevel(LEVEL.DEBUG);
      } else {
        LogPersister.setLogLevel(LEVEL.WARN);
      }
      logger.debug(String.valueOf(i));
    }

    Thread.sleep(limit * 5); // hope that's long enough for all the threads to complete

    JSONArray jsonArray = mockFileLogger.getAccumulatedLogCalls();

    assertEquals(50, jsonArray.length());

    // check the order.  If you were to change the LogThreadPoolWorkQueue
    // size to something other than 1, this should fail
    for (int i = 0; i < 50; i++) {
      assertEquals(String.valueOf(i * 2), jsonArray.getJSONObject(i).getString("msg"));
    }
  }
  public void handleIncomingUpdate(Request msg) throws DialogStateException {
    assert TransactionUtils.isTransactionExecutionThread()
        : "Code run in wrong thread. Must be run in TransactionThread. Now in "
            + Thread.currentThread();
    assert !done.get();

    if (!done.get()) {
      Logger.log("Remote party has sent update");

      final Dialog dialog = getStackContext().getDialogStorage().findDialogForMessage(msg);
      assert dialog != null;

      checkUpdatePreconditions(dialog, msg);

      Logger.log(TAG, "mark dialog as update in progress");
      dialog.markUpdateInProgress(InitiateParty.REMOTE);

      // TransactionType<InviteSrvTransaction, ? extends ServerCommonInviteTransaction>
      // transactionType = SIP_REINVITE_SERVER;
      TransactionType<UpdateSrvTransaction, UpdateServerTransaction> transactionType =
          SIP_UPDATE_SERVER;

      doHandleIncomingUpdate(msg, dialog, transactionType);
    }
  }
  @Test
  public void testAString() throws Exception {
    FileLoggerMock mockFileLogger = setFileLoggerInstanceField(activity);
    LogPersister.setContext(activity);
    LogPersister.setLogLevel(LEVEL.DEBUG);
    Logger logger = Logger.getLogger("package");
    LogPersister.setAnalyticsCapture(true);

    logger.analytics("message", null);

    waitForNotify(logger);

    JSONArray jsonArray = mockFileLogger.getAccumulatedLogCalls();
    JSONObject jsonObject = jsonArray.getJSONObject(0);

    // jsonObject should have a fixed number of key/value pairs
    assertEquals(
        "resulting jsonobject in file has wrong number of key/value pairs", 6, jsonObject.length());
    // verify the key/value pairs
    assertTrue(
        jsonObject.has(TIMESTAMP_KEY)); // don't test the value, as it may differ from current
    assertEquals("package", jsonObject.get(PACKAGE_KEY));
    // WARN
    assertEquals("ANALYTICS", jsonObject.get(LEVEL_KEY));
    assertEquals("message", jsonObject.get(MESSAGE_KEY));
    // ensure no exception is thrown by parsing the threadid value:
    assertFalse(jsonObject.getLong(THREADID_KEY) == 0);
  }
Beispiel #21
0
  public boolean intersects(int x, int y, Rectangle rectangle) {
    try {
      Rectangle up = new Rectangle(rectangle.getX(), rectangle.getY() - 2, rectangle.getWidth(), 1);
      Rectangle right =
          new Rectangle(
              rectangle.getX() + rectangle.getWidth() + 1,
              rectangle.getY(),
              1,
              rectangle.getHeight());
      Rectangle down =
          new Rectangle(
              rectangle.getX(),
              rectangle.getY() + rectangle.getHeight() + 1,
              rectangle.getWidth(),
              1);
      Rectangle left =
          new Rectangle(rectangle.getX() - 2, rectangle.getY(), 1, rectangle.getHeight());
      Rectangle rect = blocks[x][y].getRect();

      return (rect.intersects(up)
          || rect.intersects(right)
          || rect.intersects(down)
          || rect.intersects(left));
    } catch (NullPointerException e) {
      logger.log("NullPointerException in World.intersects(int, int, Rectangle)", Level.DEBUG);
      logger.log("Stack:", Level.DEBUG);
      logger.log(e.getMessage(), Level.DEBUG);
    }
    return false;
  }
Beispiel #22
0
  @Override
  public boolean loadLibrary(String libname, boolean ignoreError, ClassLoader cl) {
    try {
      for (Entry<String, String> nativeEntry : platformNativeIndex.entrySet()) {
        if (nativeEntry.getKey().contains(libname)) {
          if (log.isDebugEnabled()) {
            log.debug(
                "Loading mapped entry: [{}] [{}] [{}]",
                libname,
                nativeEntry.getKey(),
                nativeEntry.getValue());
          }
          File nativeLibCopy =
              extractJarEntry(
                  nativeEntry.getValue(),
                  nativeEntry.getKey(),
                  System.getProperty(JAVA_TMP_DIR),
                  String.format("%s.jni", libname));
          System.load(nativeLibCopy.getAbsolutePath());
          return true;
        }
      }
    } catch (Exception e) {
      log.error("Unable to load native library [{}] - {}", libname, e);
    }

    if (log.isDebugEnabled()) {
      log.debug("No mapped library match for [{}]", libname);
    }
    return false;
  }
Beispiel #23
0
  /**
   * Jirecon packets processing logic.
   *
   * <p>{@inheritDoc}
   */
  @Override
  public void processPacket(Packet packet) {
    JireconIq recording = (JireconIq) packet;

    if (JireconIq.Action.INFO != recording.getAction() && IQ.Type.RESULT == recording.getType()
        || StringUtils.isNullOrEmpty(recording.getRid())) {
      logger.warn("Discarded: " + recording.toXML());
      return;
    }

    if (!recording.getRid().equals(recordingId)) {
      logger.warn("Received IQ for unknown session: " + recording.toXML());
      return;
    }

    if (status != recording.getStatus()) {
      status = recording.getStatus();

      logger.info("Recording " + recordingId + " status: " + status);

      if (status == JireconIq.Status.STOPPED) {
        logger.info("Recording STOPPED: " + recordingId);
        recordingId = null;
      }
    } else {
      logger.info("Ignored status change: " + recording.toXML());
    }
  }
  /**
   * Returns existing chat rooms for the given <tt>chatRoomProvider</tt>.
   *
   * @param chatRoomProvider the <tt>ChatRoomProviderWrapper</tt>, which chat rooms we're looking
   *     for
   * @return existing chat rooms for the given <tt>chatRoomProvider</tt>
   */
  public List<String> getExistingChatRooms(ChatRoomProviderWrapper chatRoomProvider) {
    if (chatRoomProvider == null) return null;

    ProtocolProviderService protocolProvider = chatRoomProvider.getProtocolProvider();

    if (protocolProvider == null) return null;

    OperationSetMultiUserChat groupChatOpSet =
        protocolProvider.getOperationSet(OperationSetMultiUserChat.class);

    if (groupChatOpSet == null) return null;

    List<String> chatRooms = null;
    try {
      chatRooms = groupChatOpSet.getExistingChatRooms();
    } catch (OperationFailedException e) {
      if (logger.isTraceEnabled())
        logger.trace(
            "Failed to obtain existing chat rooms for server: "
                + protocolProvider.getAccountID().getService(),
            e);
    } catch (OperationNotSupportedException e) {
      if (logger.isTraceEnabled())
        logger.trace(
            "Failed to obtain existing chat rooms for server: "
                + protocolProvider.getAccountID().getService(),
            e);
    }

    return chatRooms;
  }
  /**
   * Tries to obtain a mapped/public address for the specified port (possibly by executing a STUN
   * query).
   *
   * @param dst the destination that we'd like to use this address with.
   * @param port the port whose mapping we are interested in.
   * @return a public address corresponding to the specified port or null if all attempts to
   *     retrieve such an address have failed.
   * @throws IOException if an error occurs while stun4j is using sockets.
   * @throws BindException if the port is already in use.
   */
  public InetSocketAddress getPublicAddressFor(InetAddress dst, int port)
      throws IOException, BindException {
    if (!useStun || (dst instanceof Inet6Address)) {
      logger.debug(
          "Stun is disabled for destination "
              + dst
              + ", skipping mapped address recovery (useStun="
              + useStun
              + ", IPv6@="
              + (dst instanceof Inet6Address)
              + ").");
      // we'll still try to bind though so that we could notify the caller
      // if the port has been taken already.
      DatagramSocket bindTestSocket = new DatagramSocket(port);
      bindTestSocket.close();

      // if we're here then the port was free.
      return new InetSocketAddress(getLocalHost(dst), port);
    }
    StunAddress mappedAddress = queryStunServer(port);
    InetSocketAddress result = null;
    if (mappedAddress != null) result = mappedAddress.getSocketAddress();
    else {
      // Apparently STUN failed. Let's try to temporarily disble it
      // and use algorithms in getLocalHost(). ... We should probably
      // eveng think about completely disabling stun, and not only
      // temporarily.
      // Bug report - John J. Barton - IBM
      InetAddress localHost = getLocalHost(dst);
      result = new InetSocketAddress(localHost, port);
    }
    if (logger.isDebugEnabled())
      logger.debug("Returning mapping for port:" + port + " as follows: " + result);
    return result;
  }
  /** Implements notification in order to track socket state. */
  @Override
  public synchronized void onSctpNotification(SctpSocket socket, SctpNotification notification) {
    if (logger.isDebugEnabled()) {
      logger.debug("socket=" + socket + "; notification=" + notification);
    }
    switch (notification.sn_type) {
      case SctpNotification.SCTP_ASSOC_CHANGE:
        SctpNotification.AssociationChange assocChange =
            (SctpNotification.AssociationChange) notification;

        switch (assocChange.state) {
          case SctpNotification.AssociationChange.SCTP_COMM_UP:
            if (!assocIsUp) {
              boolean wasReady = isReady();

              assocIsUp = true;
              if (isReady() && !wasReady) notifySctpConnectionReady();
            }
            break;

          case SctpNotification.AssociationChange.SCTP_COMM_LOST:
          case SctpNotification.AssociationChange.SCTP_SHUTDOWN_COMP:
          case SctpNotification.AssociationChange.SCTP_CANT_STR_ASSOC:
            try {
              closeStream();
            } catch (IOException e) {
              logger.error("Error closing SCTP socket", e);
            }
            break;
        }
        break;
    }
  }
  @Test
  public void testSum_double_array() {
    logger.info("\ntesting sum(double[] input, int...endPoints)");
    double[] input = null;
    assertEquals(0.0, MathUtil.sum(input), 0.0);
    assertEquals(0.0, MathUtil.sum(input, 0), 0.0);
    assertEquals(0.0, MathUtil.sum(input, 0, 57, 3), 0.0);

    input = new double[] {1.0, 2.0, 3.0, 4.0};
    assertEquals(10.0, MathUtil.sum(input), 0.0);
    assertEquals(3.0, MathUtil.sum(input, 0, 1), 0.0);
    assertEquals(6.0, MathUtil.sum(input, 0, 2), 0.0);
    assertEquals(10.0, MathUtil.sum(input, 0, 3), 0.0);
    assertEquals(10.0, MathUtil.sum(input, 0, 4), 0.0);

    assertEquals(2.0, MathUtil.sum(input, 1, 1), 0.0);
    assertEquals(5.0, MathUtil.sum(input, 1, 2), 0.0);
    assertEquals(9.0, MathUtil.sum(input, 1, 3), 0.0);

    // with indeces out of bounds
    assertEquals(9.0, MathUtil.sum(input, 1, 4), 0.0);
    assertEquals(9.0, MathUtil.sum(input, 4, 1), 0.0);

    input =
        new double[] {
          1.3310000000000004, 1.3310000000000004, 1.3310000000000004, 1.3310000000000004
        };
    double[] cumBins = MathUtil.cumProd(input, true);
    logger.debug(ListArrayUtil.arrayToString(cumBins));
    int regularContribution = 1;
    logger.debug(cumBins[0] + regularContribution * MathUtil.sum(cumBins, 1, cumBins.length - 1));
  }
Beispiel #28
0
  protected boolean navigationClick(final int status, int time) {
    System.out.println("***** navigationClick *****");
    System.out.println("status=" + Integer.toHexString(status));
    if ((status & (KeypadListener.STATUS_FOUR_WAY | KeypadListener.STATUS_TRACKWHEEL)) == 0) {
      if (status != 0) Logger.log("navClick ignored status " + Integer.toHexString(status));
      return true;
    }

    boolean used = false;

    try {
      if (c_on_navigation_click == 0)
        c_on_navigation_click = CibylCallTable.getAddressByName("rim_on_navigation_click");
    } catch (Throwable t) {
      Logger.log("Exception in navigationClick: " + t);
      t.printStackTrace();

      System.exit(0);
    }

    if (c_on_navigation_click != 0) {
      UIWorker.addUIEvent(c_on_navigation_click, status, time, 0, 0, true);
    }

    return true;
  }
Beispiel #29
0
 private void initTestPolls() throws Exception {
   testV1polls = new V1Poll[testV1msg.length];
   for (int i = 0; i < testV1polls.length; i++) {
     log.debug3("initTestPolls: V1 " + i);
     BasePoll p = pollmanager.makePoll(testV1msg[i]);
     assertNotNull(p);
     assertNotNull(p.getMessage());
     log.debug("initTestPolls: V1 " + i + " returns " + p);
     assertTrue(p instanceof V1Poll);
     switch (i) {
       case 0:
         assertTrue(p instanceof V1NamePoll);
         break;
       case 1:
         assertTrue(p instanceof V1ContentPoll);
         break;
       case 2:
         assertTrue(p instanceof V1VerifyPoll);
         break;
     }
     testV1polls[i] = (V1Poll) p;
     assertNotNull(testV1polls[i]);
     log.debug3("initTestPolls: " + i + " " + p.toString());
   }
 }
  private synchronized void cleanUp() {
    Logger.d("Service cleanUp called");
    this.taskQueue.clear();

    if (this.currentTask != null) {
      this.currentTask.stop();
    }
    // remove all future tasks
    this.measurementExecutor.shutdown();
    // remove and stop all active tasks
    this.measurementExecutor.shutdownNow();
    this.checkin.shutDown();

    this.unregisterReceiver(broadcastReceiver);
    Logger.d("canceling pending intents");

    if (checkinIntentSender != null) {
      checkinIntentSender.cancel();
      alarmManager.cancel(checkinIntentSender);
    }
    if (checkinRetryIntentSender != null) {
      checkinRetryIntentSender.cancel();
      alarmManager.cancel(checkinRetryIntentSender);
    }
    if (measurementIntentSender != null) {
      measurementIntentSender.cancel();
      alarmManager.cancel(measurementIntentSender);
    }
    persistState();
    this.notifyAll();
    phoneUtils.shutDown();
    Logger.i("Shut down all executors and stopping service");
  }