Esempio n. 1
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;
  }
  /**
   * WhiteboardObjectTextJabberImpl constructor.
   *
   * @param xml the XML string object to parse.
   */
  public WhiteboardObjectTextJabberImpl(String xml) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
      builder = factory.newDocumentBuilder();
      InputStream in = new ByteArrayInputStream(xml.getBytes());
      Document doc = builder.parse(in);

      Element e = doc.getDocumentElement();
      String elementName = e.getNodeName();
      if (elementName.equals("text")) {
        // we have a text
        String id = e.getAttribute("id");
        double x = Double.parseDouble(e.getAttribute("x"));
        double y = Double.parseDouble(e.getAttribute("y"));
        String fill = e.getAttribute("fill");
        String fontFamily = e.getAttribute("font-family");
        int fontSize = Integer.parseInt(e.getAttribute("font-size"));
        String text = e.getTextContent();

        this.setID(id);
        this.setWhiteboardPoint(new WhiteboardPoint(x, y));
        this.setFontName(fontFamily);
        this.setFontSize(fontSize);
        this.setText(text);
        this.setColor(Color.decode(fill).getRGB());
      }
    } catch (ParserConfigurationException ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    } catch (IOException ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    } catch (Exception ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    }
  }
Esempio n. 3
0
  /** @javadoc */
  public void handleChanged(String buildername, int number) {
    // method checks if this really something valid
    // and we should signal a new version

    boolean dirty = false;
    for (VersionCacheWhenNode whennode : whens) {
      List<String> types = whennode.getTypes();

      // check if im known in the types part
      if (types.contains(buildername)) {
        // is there only 1 builder type ?
        if (log.isDebugEnabled()) log.debug("types=" + types.toString());
        if (types.size() == 1) {
          dirty = true;
        } else {
          // so multiple prepare a multilevel !
          List<String> nodes = whennode.getNodes();

          List<String> fields = new Vector<String>();
          fields.add(buildername + ".number");
          List<String> ordervec = new Vector<String>();
          List<String> dirvec = new Vector<String>();

          List<MMObjectNode> vec =
              mmb.getClusterBuilder()
                  .searchMultiLevelVector(
                      nodes,
                      fields,
                      "YES",
                      types,
                      buildername + ".number==" + number,
                      ordervec,
                      dirvec);
          if (log.isDebugEnabled()) log.debug("VEC=" + vec);
          if (vec != null && vec.size() > 0) {
            dirty = true;
          }
        }
      }
    }

    if (dirty) {
      // add one to the version of this counter
      int version = versionnode.getIntValue("version");
      versionnode.setValue("version", version + 1);
      versionnode.commit();
      if (log.isDebugEnabled()) log.debug("Changed = " + (version + 1));
    }
  }
  /**
   * Subscribes this provider as interested in receiving notifications for new mail messages from
   * Google mail services such as Gmail or Google Apps.
   */
  private void subscribeForGmailNotifications() {
    // first check support for the notification service
    String accountIDService = jabberProvider.getAccountID().getService();
    boolean notificationsAreSupported =
        jabberProvider.isFeatureSupported(accountIDService, NewMailNotificationIQ.NAMESPACE);

    if (!notificationsAreSupported) {
      if (logger.isDebugEnabled())
        logger.debug(
            accountIDService
                + " does not seem to provide a Gmail notification "
                + " service so we won't be trying to subscribe for it");
      return;
    }

    if (logger.isDebugEnabled())
      logger.debug(
          accountIDService
              + " seems to provide a Gmail notification "
              + " service so we will try to subscribe for it");

    ProviderManager providerManager = ProviderManager.getInstance();

    providerManager.addIQProvider(
        MailboxIQ.ELEMENT_NAME, MailboxIQ.NAMESPACE, new MailboxIQProvider());
    providerManager.addIQProvider(
        NewMailNotificationIQ.ELEMENT_NAME,
        NewMailNotificationIQ.NAMESPACE,
        new NewMailNotificationProvider());

    Connection connection = jabberProvider.getConnection();

    connection.addPacketListener(new MailboxIQListener(), new PacketTypeFilter(MailboxIQ.class));
    connection.addPacketListener(
        new NewMailNotificationListener(), new PacketTypeFilter(NewMailNotificationIQ.class));

    if (opSetPersPresence.getCurrentStatusMessage().equals(JabberStatusEnum.OFFLINE)) return;

    // create a query with -1 values for newer-than-tid and
    // newer-than-time attributes
    MailboxQueryIQ mailboxQuery = new MailboxQueryIQ();

    if (logger.isTraceEnabled())
      logger.trace(
          "sending mailNotification for acc: "
              + jabberProvider.getAccountID().getAccountUniqueID());
    jabberProvider.getConnection().sendPacket(mailboxQuery);
  }
  /** 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;
    }
  }
  /**
   * 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;
  }
  /**
   * Makes an <tt>RTCPREMBPacket</tt> that provides receiver feedback to the endpoint from which we
   * receive.
   *
   * @return an <tt>RTCPREMBPacket</tt> that provides receiver feedback to the endpoint from which
   *     we receive.
   */
  private RTCPREMBPacket makeRTCPREMBPacket() {
    // TODO we should only make REMBs if REMB support has been advertised.
    // Destination
    RemoteBitrateEstimator remoteBitrateEstimator =
        ((VideoMediaStream) getStream()).getRemoteBitrateEstimator();

    Collection<Integer> ssrcs = remoteBitrateEstimator.getSsrcs();

    // TODO(gp) intersect with SSRCs from signaled simulcast layers
    // NOTE(gp) The Google Congestion Control algorithm (sender side)
    // doesn't seem to care about the SSRCs in the dest field.
    long[] dest = new long[ssrcs.size()];
    int i = 0;

    for (Integer ssrc : ssrcs) dest[i++] = ssrc & 0xFFFFFFFFL;

    // Exp & mantissa
    long bitrate = remoteBitrateEstimator.getLatestEstimate();

    if (bitrate == -1) return null;

    if (logger.isDebugEnabled()) logger.debug("Estimated bitrate: " + bitrate);

    // Create and return the packet.
    // We use the stream's local source ID (SSRC) as the SSRC of packet
    // sender.
    long streamSSRC = getLocalSSRC();

    return new RTCPREMBPacket(streamSSRC, /* mediaSSRC */ 0L, bitrate, dest);
  }
  /**
   * Sets the value of {@code lastN}, that is, the maximum number of endpoints whose video streams
   * will be forwarded to the endpoint. A value of {@code -1} means that there is no limit.
   *
   * @param lastN the value to set.
   */
  public void setLastN(int lastN) {
    if (logger.isDebugEnabled()) {
      logger.debug("Setting lastN=" + lastN);
    }

    List<String> endpointsToAskForKeyframe = null;
    synchronized (this) {
      // Since we have the lock anyway, call update() inside, so it
      // doesn't have to obtain it again. But keep the call to
      // askForKeyframes() outside.

      if (this.lastN != lastN) {
        // If we're just now enabling lastN, we don't need to ask for
        // keyframes as all streams were being forwarded already.
        boolean update = this.lastN != -1;

        this.lastN = lastN;

        if (lastN >= 0 && (currentLastN < 0 || currentLastN > lastN)) {
          currentLastN = lastN;
        }

        if (update) {
          endpointsToAskForKeyframe = update();
        }
      }
    }

    askForKeyframes(endpointsToAskForKeyframe);
  }
  @Override
  public void subscribe(Subscriber<? super Object> s) {
    if (log.isDebugEnabled()) {
      log.debug(
          "Subscribing inbound receiver [pending: "
              + ""
              + inboundEmitter.getPending()
              + ", done: "
              + inboundEmitter.done
              + "]");
    }
    if (inboundEmitter.actual == null) {
      if (inboundEmitter.done) {
        if (inboundEmitter.error != null) {
          Operators.error(s, inboundEmitter.error);
          return;
        } else if (inboundEmitter.getPending() == 0) {
          Operators.complete(s);
          return;
        }
      }

      inboundEmitter.init(s);
      s.onSubscribe(inboundEmitter);
    } else {
      Operators.error(
          s, new IllegalStateException("Only one connection receive subscriber allowed."));
    }
  }
Esempio n. 10
0
 /**
  * 采用批方式插入多条数据
  *
  * @param collection collection
  * @throws Exception
  */
 public void insertAll(Collection collection) throws Exception {
   StringBuffer buffer = new StringBuffer(200);
   buffer.append("INSERT INTO LineLoss (");
   buffer.append("LineCode,");
   buffer.append("R,");
   buffer.append("LineLong,");
   buffer.append("Volt,");
   buffer.append("T,");
   buffer.append("ValidStatus,");
   buffer.append("Flag,");
   buffer.append("Remark ");
   buffer.append(") ");
   buffer.append("VALUES(?,?,?,?,?,?,?,?)");
   if (logger.isDebugEnabled()) {
     logger.debug(buffer.toString());
   }
   dbManager.prepareStatement(buffer.toString());
   for (Iterator i = collection.iterator(); i.hasNext(); ) {
     LineLossDto lineLossDto = (LineLossDto) i.next();
     dbManager.setString(1, lineLossDto.getLineCode());
     dbManager.setDouble(2, lineLossDto.getR());
     dbManager.setDouble(3, lineLossDto.getLineLong());
     dbManager.setDouble(4, lineLossDto.getVolt());
     dbManager.setDouble(5, lineLossDto.getT());
     dbManager.setString(6, lineLossDto.getValidStatus());
     dbManager.setString(7, lineLossDto.getFlag());
     dbManager.setString(8, lineLossDto.getRemark());
     dbManager.addBatch();
   }
   dbManager.executePreparedUpdateBatch();
 }
Esempio n. 11
0
 /**
  * 采用批方式插入多条数据
  *
  * @param collection collection
  * @throws Exception
  */
 public void insertAll(Collection collection) throws Exception {
   StringBuffer buffer = new StringBuffer(200);
   buffer.append("INSERT INTO LwWholeSalePrice (");
   buffer.append("PowerClass,");
   buffer.append("SaleArea,");
   buffer.append("VoltageBegin,");
   buffer.append("VoltageEnd,");
   buffer.append("Price,");
   buffer.append("ValidStatus,");
   buffer.append("Flag,");
   buffer.append("Remark ");
   buffer.append(") ");
   buffer.append("VALUES(?,?,?,?,?,?,?,?)");
   if (logger.isDebugEnabled()) {
     logger.debug(buffer.toString());
   }
   dbManager.prepareStatement(buffer.toString());
   for (Iterator i = collection.iterator(); i.hasNext(); ) {
     LwWholeSalePriceDto lwWholeSalePriceDto = (LwWholeSalePriceDto) i.next();
     dbManager.setString(1, lwWholeSalePriceDto.getPowerClass());
     dbManager.setString(2, lwWholeSalePriceDto.getSaleArea());
     dbManager.setDouble(3, lwWholeSalePriceDto.getVoltageBegin());
     dbManager.setDouble(4, lwWholeSalePriceDto.getVoltageEnd());
     dbManager.setDouble(5, lwWholeSalePriceDto.getPrice());
     dbManager.setString(6, lwWholeSalePriceDto.getValidStatus());
     dbManager.setString(7, lwWholeSalePriceDto.getFlag());
     dbManager.setString(8, lwWholeSalePriceDto.getRemark());
     dbManager.addBatch();
   }
   dbManager.executePreparedUpdateBatch();
 }
Esempio n. 12
0
  public GLBootstrap() throws Exception {

    System.setProperty("jogamp.gluegen.UseTempJarCache", "false");

    log.info(
        "Initializing native JOGL jar dependencies for platform [{}]. Temp jar cache disabled.",
        PlatformPropsImpl.os_and_arch);

    String nativeJarName = String.format("%s-%s", NATIVES, PlatformPropsImpl.os_and_arch);
    String[] classpathEntries =
        System.getProperty(JAVA_CLASSPATH).split(System.getProperty(JAVA_SEPARATOR));

    for (String jarPath : classpathEntries) {

      if (jarPath.contains(nativeJarName)) {

        if (log.isDebugEnabled()) {
          log.debug("Applicable platform jar: [{}]", jarPath);
        }

        JarFile jf = new JarFile(jarPath);

        try {
          Enumeration<JarEntry> jarEntries = jf.entries();

          while (jarEntries.hasMoreElements()) {

            JarEntry je = jarEntries.nextElement();

            if (!je.isDirectory() && !je.getName().contains(JAVA_META_INF)) {
              if (log.isDebugEnabled()) {
                log.debug("Mapping jar entry [{}] -> [{}]", je.getName(), jarPath);
              }
              if (log.isDebugEnabled() && platformNativeIndex.containsKey(je.getName())) {
                log.debug("Duplicate jar entry: [{}]", je.getName());
                log.debug("Mapped at: [{}]", platformNativeIndex.get(je.getName()));
                log.debug("Also at: [{}]", jarPath);
              }
              platformNativeIndex.put(je.getName(), jarPath);
            }
          }
        } finally {
          closeJar(jf);
        }
      }
    }
  }
  /**
   * Initializes the local list of endpoints ({@link #speechActivityEndpointsChanged(List)}) with
   * the current endpoints from the conference.
   */
  public synchronized void initializeConferenceEndpoints() {
    speechActivityEndpointsChanged(channel.getConferenceSpeechActivity().getEndpoints());

    if (logger.isDebugEnabled()) {
      logger.debug(
          "Initialized the list of endpoints: " + conferenceSpeechActivityEndpoints.toString());
    }
  }
Esempio n. 14
0
  /**
   * Handles {@link EventFactory#FOCUS_JOINED_ROOM_TOPIC} and {@link
   * EventFactory#CONFERENCE_ROOM_TOPIC}.
   *
   * <p>{@inheritDoc}
   */
  @Override
  public void handleEvent(Event event) {
    String topic = event.getTopic();
    if (!topic.equals(EventFactory.FOCUS_JOINED_ROOM_TOPIC)
        && !topic.equals(EventFactory.CONFERENCE_ROOM_TOPIC)) {
      logger.error("Unexpected event topic: " + topic);
      return;
    }

    String roomJid = (String) event.getProperty(EventFactory.ROOM_JID_KEY);

    JitsiMeetConference conference = focusManager.getConference(roomJid);
    if (conference == null) {
      logger.error("Conference is null");
      return;
    }

    ChatRoom chatRoom = conference.getChatRoom();
    if (chatRoom == null) {
      logger.error("Chat room is null");
      return;
    }

    JitsiMeetServices meetServices = focusManager.getJitsiMeetServices();
    ComponentVersionsExtension versionsExtension = new ComponentVersionsExtension();

    // XMPP
    Version xmppServerVersion = meetServices.getXMPPServerVersion();
    if (xmppServerVersion != null) {
      versionsExtension.addComponentVersion(
          ComponentVersionsExtension.COMPONENT_XMPP_SERVER,
          xmppServerVersion.getNameVersionOsString());
    }

    // Conference focus
    org.jitsi.service.version.Version jicofoVersion = versionService.getCurrentVersion();
    versionsExtension.addComponentVersion(
        ComponentVersionsExtension.COMPONENT_FOCUS,
        jicofoVersion.getApplicationName()
            + "("
            + jicofoVersion.toString()
            + ","
            + System.getProperty("os.name")
            + ")");

    // Videobridge
    // It is not be reported for FOCUS_JOINED_ROOM_TOPIC
    String bridgeJid = (String) event.getProperty(EventFactory.BRIDGE_JID_KEY);
    Version jvbVersion = bridgeJid == null ? null : meetServices.getBridgeVersion(bridgeJid);
    if (jvbVersion != null) {
      versionsExtension.addComponentVersion(
          ComponentVersionsExtension.COMPONENT_VIDEOBRIDGE, jvbVersion.getNameVersionOsString());
    }

    meetTools.sendPresenceExtension(chatRoom, versionsExtension);

    if (logger.isDebugEnabled()) logger.debug("Sending versions: " + versionsExtension.toXML());
  }
 /**
  * 按条件删除数据
  *
  * @param conditions 查询条件
  * @return 删除的行数
  * @throws Exception
  */
 public int deleteByConditions(String conditions) throws Exception {
   StringBuffer buffer = new StringBuffer(100);
   buffer.append("DELETE FROM LwWholeSaleSummary WHERE ");
   buffer.append(conditions);
   if (logger.isDebugEnabled()) {
     logger.debug(buffer.toString());
   }
   int count = dbManager.executeUpdate(buffer.toString());
   return count;
 }
Esempio n. 16
0
  /**
   * Return true/false if logging is enabled at a given level.
   *
   * @param logLevel the level that we'd like to check loggability for.
   * @return always <tt>true</tt> regardless of <tt>logLevel</tt>'s value.
   */
  public boolean isLoggingEnabled(int logLevel) {
    // always enable trace messages so we can receive packets
    // and log them to packet logging service
    if (logLevel == TRACE_DEBUG) return logger.isDebugEnabled();
    if (logLevel == TRACE_MESSAGES) // same as TRACE_INFO
    return true;
    if (logLevel == TRACE_NONE) return false;

    return true;
  }
Esempio n. 17
0
  /**
   * Ends the call with for this <tt>CallPeer</tt>. Depending on the state of the peer the method
   * would send a CANCEL, BYE, or BUSY_HERE message and set the new state to DISCONNECTED.
   *
   * @param failed indicates if the hangup is following to a call failure or simply a disconnect
   * @param reasonText the text, if any, to be set on the <tt>ReasonPacketExtension</tt> as the
   *     value of its
   * @param reasonOtherExtension the <tt>PacketExtension</tt>, if any, to be set on the
   *     <tt>ReasonPacketExtension</tt> as the value of its <tt>otherExtension</tt> property
   */
  public void hangup(boolean failed, String reasonText, PacketExtension reasonOtherExtension) {
    // do nothing if the call is already ended
    if (CallPeerState.DISCONNECTED.equals(getState()) || CallPeerState.FAILED.equals(getState())) {
      if (logger.isDebugEnabled())
        logger.debug("Ignoring a request to hangup a call peer " + "that is already DISCONNECTED");
      return;
    }

    CallPeerState prevPeerState = getState();
    getMediaHandler().getTransportManager().close();

    if (failed) setState(CallPeerState.FAILED, reasonText);
    else setState(CallPeerState.DISCONNECTED, reasonText);

    SessionIQ responseIQ = null;

    if (prevPeerState.equals(CallPeerState.CONNECTED) || CallPeerState.isOnHold(prevPeerState)) {
      responseIQ =
          GTalkPacketFactory.createBye(getProtocolProvider().getOurJID(), peerJID, getSID());
      responseIQ.setInitiator(isInitiator() ? getAddress() : getProtocolProvider().getOurJID());
    } else if (CallPeerState.CONNECTING.equals(prevPeerState)
        || CallPeerState.CONNECTING_WITH_EARLY_MEDIA.equals(prevPeerState)
        || CallPeerState.ALERTING_REMOTE_SIDE.equals(prevPeerState)) {
      responseIQ =
          GTalkPacketFactory.createCancel(getProtocolProvider().getOurJID(), peerJID, getSID());
      responseIQ.setInitiator(isInitiator() ? getAddress() : getProtocolProvider().getOurJID());
    } else if (prevPeerState.equals(CallPeerState.INCOMING_CALL)) {
      responseIQ =
          GTalkPacketFactory.createBusy(getProtocolProvider().getOurJID(), peerJID, getSID());
      responseIQ.setInitiator(isInitiator() ? getAddress() : getProtocolProvider().getOurJID());
    } else if (prevPeerState.equals(CallPeerState.BUSY)
        || prevPeerState.equals(CallPeerState.FAILED)) {
      // For FAILED and BUSY we only need to update CALL_STATUS
      // as everything else has been done already.
    } else {
      logger.info("Could not determine call peer state!");
    }

    if (responseIQ != null) {
      if (reasonOtherExtension != null) {
        ReasonPacketExtension reason =
            (ReasonPacketExtension)
                responseIQ.getExtension(
                    ReasonPacketExtension.ELEMENT_NAME, ReasonPacketExtension.NAMESPACE);

        if (reason == null) {
          if (reasonOtherExtension instanceof ReasonPacketExtension) {
            responseIQ.setReason((ReasonPacketExtension) reasonOtherExtension);
          }
        } else reason.setOtherExtension(reasonOtherExtension);
      }

      getProtocolProvider().getConnection().sendPacket(responseIQ);
    }
  }
Esempio n. 18
0
  /**
   * Returns the SSRC paired with <tt>ssrc</tt> in an FID source-group, if any. If none is found,
   * returns -1.
   *
   * @return the SSRC paired with <tt>ssrc</tt> in an FID source-group, if any. If none is found,
   *     returns -1.
   */
  private long getPrimarySsrc(RawPacket pkt) {
    MediaStreamTrackReceiver receiver = channel.getStream().getMediaStreamTrackReceiver();

    if (receiver == null) {
      if (logger.isDebugEnabled()) {
        logger.debug("Dropping an incoming RTX packet from an unknown source.");
      }
      return -1;
    }

    RTPEncoding encoding = receiver.resolveRTPEncoding(pkt);
    if (encoding == null) {
      if (logger.isDebugEnabled()) {
        logger.debug("Dropping an incoming RTX packet from an unknown source.");
      }
      return -1;
    }

    return encoding.getPrimarySSRC();
  }
  /**
   * Initializes this network address manager service implementation and starts all
   * processes/threads associated with this address manager, such as a stun firewall/nat detector,
   * keep alive threads, binding lifetime discovery threads and etc. The method may also be used
   * after a call to stop() as a reinitialization technique.
   */
  public void start() {
    // init stun
    String stunAddressStr = null;
    int port = -1;
    stunAddressStr = NetaddrActivator.getConfigurationService().getString(PROP_STUN_SERVER_ADDRESS);
    String portStr = NetaddrActivator.getConfigurationService().getString(PROP_STUN_SERVER_PORT);

    this.localHostFinderSocket = initRandomPortSocket();

    if (stunAddressStr == null || portStr == null) {
      useStun = false;
      // we use the default stun server address only for chosing a public
      // route and not for stun queries.
      stunServerAddress = new StunAddress(DEFAULT_STUN_SERVER_ADDRESS, DEFAULT_STUN_SERVER_PORT);
      logger.info(
          "Stun server address("
              + stunAddressStr
              + ")/port("
              + portStr
              + ") not set (or invalid). Disabling STUN.");

    } else {
      try {
        port = Integer.valueOf(portStr).intValue();
      } catch (NumberFormatException ex) {
        logger.error(portStr + " is not a valid port number. " + "Defaulting to 3478", ex);
        port = 3478;
      }

      stunServerAddress = new StunAddress(stunAddressStr, port);
      detector = new SimpleAddressDetector(stunServerAddress);

      if (logger.isDebugEnabled()) {
        logger.debug(
            "Created a STUN Address detector for the following "
                + "STUN server: "
                + stunAddressStr
                + ":"
                + port);
      }
      detector.start();
      logger.debug("STUN server detector started;");

      // make sure that someone doesn't set invalid stun address and port
      NetaddrActivator.getConfigurationService()
          .addVetoableChangeListener(PROP_STUN_SERVER_ADDRESS, this);
      NetaddrActivator.getConfigurationService()
          .addVetoableChangeListener(PROP_STUN_SERVER_PORT, this);

      // now start a thread query to the stun server and only set the
      // useStun flag to true if it succeeds.
      launchStunServerTest();
    }
  }
Esempio n. 20
0
 @Override
 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
   if (inboundEmitter.requested != 0L) {
     ctx.read();
   } else {
     if (log.isDebugEnabled()) {
       log.debug("Pausing read due to lack of request");
     }
   }
   ctx.fireChannelReadComplete();
 }
Esempio n. 21
0
    @Override
    public void onError(Throwable t) {
      if (t instanceof IOException && t.getMessage().contains("Broken pipe")) {
        if (log.isDebugEnabled()) {
          log.debug("Connection closed remotely", t);
        }
        return;
      }

      log.error("Error processing connection. Closing the channel.", t);

      ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
Esempio n. 22
0
  /**
   * Dispatches the event received from a JAIN-SIP <tt>SipProvider</tt> to one of our "candidate
   * recipient" listeners.
   *
   * @param event the event received for a <tt>SipProvider</tt>.
   */
  public void processIOException(IOExceptionEvent event) {
    try {
      if (logger.isTraceEnabled()) logger.trace(event);

      // impossible to dispatch, log here
      if (logger.isDebugEnabled()) logger.debug("@todo implement processIOException()");
    } catch (Throwable exc) {
      // any exception thrown within our code should be caught here
      // so that we could log it rather than interrupt stack activity with
      // it.
      this.logApplicationException(DialogTerminatedEvent.class, exc);
    }
  }
 /**
  * The method queries a Stun server for a binding for the specified port.
  *
  * @param port the port to resolve (the stun message gets sent trhough that port)
  * @return StunAddress the address returned by the stun server or null if an error occurred or no
  *     address was returned
  * @throws IOException if an error occurs while stun4j is using sockets.
  * @throws BindException if the port is already in use.
  */
 private StunAddress queryStunServer(int port) throws IOException, BindException {
   StunAddress mappedAddress = null;
   if (detector != null && useStun) {
     mappedAddress = detector.getMappingFor(port);
     if (logger.isDebugEnabled())
       logger.debug(
           "For port:"
               + port
               + "a Stun server returned the "
               + "following mapping ["
               + mappedAddress);
   }
   return mappedAddress;
 }
 /**
  * 查询满足模糊查询条件的记录数
  *
  * @param conditions conditions
  * @return 满足模糊查询条件的记录数
  * @throws Exception
  */
 public int getCount(String conditions) throws Exception {
   int count = -1;
   StringBuffer buffer = new StringBuffer(100);
   buffer.append("SELECT count(*) FROM LwWholeSaleSummary WHERE ");
   buffer.append(conditions);
   if (logger.isDebugEnabled()) {
     logger.debug(buffer.toString());
   }
   ResultSet resultSet = dbManager.executeQuery(buffer.toString());
   resultSet.next();
   count = dbManager.getInt(resultSet, 1);
   resultSet.close();
   return count;
 }
Esempio n. 25
0
  /**
   * 按主键更新一条数据(主键本身无法变更)
   *
   * @param lwWholeSalePriceDto lwWholeSalePriceDto
   * @throws Exception
   */
  public void update(LwWholeSalePriceDto lwWholeSalePriceDto) throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    buffer.append("UPDATE LwWholeSalePrice SET ");
    buffer.append("PowerClass = ?, ");
    buffer.append("VoltageEnd = ?, ");
    buffer.append("Price = ?, ");
    buffer.append("ValidStatus = ?, ");
    buffer.append("Flag = ?, ");
    buffer.append("Remark = ? ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append("UPDATE LwWholeSalePrice SET ");
      debugBuffer.append("PowerClass = '" + lwWholeSalePriceDto.getPowerClass() + "', ");
      debugBuffer.append("VoltageEnd = " + lwWholeSalePriceDto.getVoltageEnd() + ", ");
      debugBuffer.append("Price = " + lwWholeSalePriceDto.getPrice() + ", ");
      debugBuffer.append("ValidStatus = '" + lwWholeSalePriceDto.getValidStatus() + "', ");
      debugBuffer.append("Flag = '" + lwWholeSalePriceDto.getFlag() + "', ");
      debugBuffer.append("Remark = '" + lwWholeSalePriceDto.getRemark() + "' ");
      debugBuffer.append("WHERE ");
      debugBuffer
          .append("SaleArea=")
          .append("'")
          .append(lwWholeSalePriceDto.getSaleArea())
          .append("' AND ");
      debugBuffer
          .append("VoltageBegin=")
          .append("")
          .append(lwWholeSalePriceDto.getVoltageBegin())
          .append("");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("WHERE ");
    buffer.append("SaleArea = ? And ");
    buffer.append("VoltageBegin = ?");

    dbManager.prepareStatement(buffer.toString());
    // 设置更新字段;
    dbManager.setString(1, lwWholeSalePriceDto.getPowerClass());
    dbManager.setDouble(2, lwWholeSalePriceDto.getVoltageEnd());
    dbManager.setDouble(3, lwWholeSalePriceDto.getPrice());
    dbManager.setString(4, lwWholeSalePriceDto.getValidStatus());
    dbManager.setString(5, lwWholeSalePriceDto.getFlag());
    dbManager.setString(6, lwWholeSalePriceDto.getRemark());
    // 设置条件字段;
    dbManager.setString(7, lwWholeSalePriceDto.getSaleArea());
    dbManager.setDouble(8, lwWholeSalePriceDto.getVoltageBegin());
    dbManager.executePreparedUpdate();
  }
  /**
   * Notifies this instance that the ordered list of endpoints (specified as a list of endpoint IDs)
   * in the conference has changed.
   *
   * @param endpointIds the new ordered list of endpoints (specified as a list of endpoint IDs) in
   *     the conference.
   * @return the list of IDs of endpoints which were added to the list of forwarded endpoints as a
   *     result of the call.
   */
  private synchronized List<String> speechActivityEndpointIdsChanged(List<String> endpointIds) {
    if (conferenceSpeechActivityEndpoints.equals(endpointIds)) {
      if (logger.isDebugEnabled()) {
        logger.debug("Conference endpoints have not changed.");
      }
      return null;
    } else {
      List<String> newEndpoints = new LinkedList<>(endpointIds);
      newEndpoints.removeAll(conferenceSpeechActivityEndpoints);

      conferenceSpeechActivityEndpoints = endpointIds;

      return update(newEndpoints);
    }
  }
  /**
   * Creates and sends a SUBSCRIBE request to a specific subscription <tt>Address</tt>/Request URI
   * if it matches a <tt>Subscription</tt> with an id tag of its Event header of a specific value in
   * the list of subscriptions managed by this instance with an Expires header value of zero in
   * order to terminate receiving event notifications and removes the specified
   * <tt>Subscription</tt> from the list of subscriptions managed by this instance. The removed
   * <tt>Subscription</tt> may receive notifications to process the <tt>Request</tt>s and/or
   * <tt>Response</tt>s which constitute the signaling session associated with it. If the attempt to
   * create the SUBSCRIBE request fails, the associated <tt>Subscription</tt> is not removed from
   * the list of subscriptions managed by this instance. If the specified <tt>Address</tt> does not
   * identify an existing <tt>Subscription</tt> in the list of subscriptions managed by this
   * instance, an assertion may optionally be performed or no reaction can be taken.
   *
   * @param toAddress a subscription <tt>Address</tt>/Request URI which identifies a
   *     <tt>Subscription</tt> to be removed from the list of subscriptions managed by this instance
   * @param eventId the id tag placed in the Event header of the <tt>Subscription</tt> to be matched
   *     if there is one or <tt>null</tt> if the <tt>Subscription</tt> should have no id tag in its
   *     Event header
   * @param assertSubscribed <tt>true</tt> to assert if the specified subscription
   *     <tt>Address</tt>/Request URI does not identify an existing <tt>Subscription</tt> in the
   *     list of subscriptions managed by this instance; <tt>false</tt> to not assert if the
   *     mentioned condition is met
   * @throws IllegalArgumentException if <tt>assertSubscribed</tt> is <tt>true</tt> and
   *     <tt>toAddress</tt> and <tt>eventId</tt> do not identify an existing <tt>Subscription</tt>
   *     in the list of subscriptions managed by this instance
   * @throws OperationFailedException if we fail constructing or sending the unSUBSCRIBE request.
   */
  public void unsubscribe(Address toAddress, String eventId, boolean assertSubscribed)
      throws IllegalArgumentException, OperationFailedException {
    Subscription subscription = getSubscription(toAddress, eventId);
    if (subscription == null)
      if (assertSubscribed)
        throw new IllegalArgumentException("trying to unregister a not registered contact");
      else return;

    Dialog dialog = subscription.getDialog();

    // we stop the subscription if we're subscribed to this contact
    if (dialog != null) {
      String callId = dialog.getCallId().getCallId();

      ClientTransaction subscribeTransaction;
      try {
        subscribeTransaction = createSubscription(subscription, dialog, 0);
      } catch (OperationFailedException e) {
        if (logger.isDebugEnabled()) logger.debug("failed to create the unsubscription", e);
        throw e;
      }

      // we are not anymore subscribed to this contact
      // this ensure that the response of this request will be
      // handled as an unsubscription response
      removeSubscription(callId, subscription);

      try {
        dialog.sendRequest(subscribeTransaction);
      } catch (SipException e) {
        if (logger.isDebugEnabled()) logger.debug("Can't send the request", e);
        throw new OperationFailedException(
            "Failed to send the subscription message", OperationFailedException.NETWORK_FAILURE, e);
      }
    }
  }
Esempio n. 28
0
  @Test
  public void delegatesLevelIsEnabledToSlf4j() {
    logging.setLevel(LogLevel.WARN);

    Logger logger = Logging.getLogger(LoggingTest.class);
    assertTrue(logger.isErrorEnabled());
    assertTrue(logger.isQuietEnabled());
    assertTrue(logger.isWarnEnabled());
    assertFalse(logger.isLifecycleEnabled());
    assertFalse(logger.isInfoEnabled());
    assertFalse(logger.isDebugEnabled());
    assertFalse(logger.isTraceEnabled());

    assertTrue(logger.isEnabled(LogLevel.ERROR));
    assertFalse(logger.isEnabled(LogLevel.INFO));
  }
Esempio n. 29
0
  /**
   * 按主键查找一条数据
   *
   * @param saleArea 趸售区域
   * @param voltageBegin 起始电压
   * @return LwWholeSalePriceDto
   * @throws Exception
   */
  public LwWholeSalePriceDto findByPrimaryKey(String saleArea, double voltageBegin)
      throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    // 拼SQL语句
    buffer.append("SELECT ");
    buffer.append("PowerClass,");
    buffer.append("SaleArea,");
    buffer.append("VoltageBegin,");
    buffer.append("VoltageEnd,");
    buffer.append("Price,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark ");
    buffer.append("FROM LwWholeSalePrice ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append(buffer.toString());
      debugBuffer.append("WHERE ");
      debugBuffer.append("SaleArea=").append("'").append(saleArea).append("' AND ");
      debugBuffer.append("VoltageBegin=").append("").append(voltageBegin).append("");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("WHERE ");
    buffer.append("SaleArea = ? And ");
    buffer.append("VoltageBegin = ?");

    dbManager.prepareStatement(buffer.toString());
    // 设置条件字段;
    dbManager.setString(1, saleArea);
    dbManager.setDouble(2, voltageBegin);
    ResultSet resultSet = dbManager.executePreparedQuery();
    LwWholeSalePriceDto lwWholeSalePriceDto = null;
    if (resultSet.next()) {
      lwWholeSalePriceDto = new LwWholeSalePriceDto();
      lwWholeSalePriceDto.setPowerClass(dbManager.getString(resultSet, 1));
      lwWholeSalePriceDto.setSaleArea(dbManager.getString(resultSet, 2));
      lwWholeSalePriceDto.setVoltageBegin(dbManager.getDouble(resultSet, 3));
      lwWholeSalePriceDto.setVoltageEnd(dbManager.getDouble(resultSet, 4));
      lwWholeSalePriceDto.setPrice(dbManager.getDouble(resultSet, 5));
      lwWholeSalePriceDto.setValidStatus(dbManager.getString(resultSet, 6));
      lwWholeSalePriceDto.setFlag(dbManager.getString(resultSet, 7));
      lwWholeSalePriceDto.setRemark(dbManager.getString(resultSet, 8));
    }
    resultSet.close();
    return lwWholeSalePriceDto;
  }
Esempio n. 30
0
  @Override
  public org.mmbase.bridge.Node getNode(final Cloud userCloud, final Document doc) {
    String docId = doc.get("number");
    if (docId == null) {
      throw new IllegalArgumentException("No number found in " + doc);
    }
    LazyMap m = nodeCache.get(docId); //
    if (m == null) {
      Map<String, String> keys = new HashMap<String, String>();
      for (String keyWord : keyWords) {
        keys.put(keyWord, doc.get(keyWord));
      }
      m = new LazyMap(docId, keys);
      nodeCache.put(docId, m);
    }
    org.mmbase.bridge.Node node =
        new MapNode<String>(
            m,
            new MapNodeManager(userCloud, m) {
              @Override
              public boolean hasField(String name) {
                if (JdbcIndexDefinition.this.key.equals(name)) return true;
                return super.hasField(name);
              }

              @Override
              public org.mmbase.bridge.Field getField(String name) {
                if (map == null && JdbcIndexDefinition.this.key.equals(name)) {
                  org.mmbase.core.CoreField fd =
                      org.mmbase.core.util.Fields.createField(
                          name,
                          org.mmbase.core.util.Fields.classToType(Object.class),
                          org.mmbase.bridge.Field.TYPE_UNKNOWN,
                          org.mmbase.bridge.Field.STATE_VIRTUAL,
                          null);
                  return new org.mmbase.bridge.implementation.BasicField(fd, this);
                } else {
                  return super.getField(name);
                }
              }
            });
    if (log.isDebugEnabled()) {
      log.debug("Returning node for " + node);
    }
    return node;
  }