Example #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;
  }
Example #2
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;
    }
  }
  /**
   * 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);
  }
  /**
   * 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);
  }
Example #7
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();
 }
  /**
   * 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;
  }
 /**
  * 采用批方式插入多条数据
  *
  * @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();
 }
Example #10
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());
    }
  }
 /**
  * 按条件删除数据
  *
  * @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;
 }
Example #13
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;
  }
  /**
   * 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);
    }
  }
  /**
   * 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();
    }
  }
  /**
   * 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();
  }
Example #17
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);
    }
  }
 /**
  * 查询满足模糊查询条件的记录数
  *
  * @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;
 }
 /**
  * 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 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);
      }
    }
  }
  /**
   * 按主键查找一条数据
   *
   * @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;
  }
Example #24
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;
  }
  /**
   * Sets the list of "pinned" endpoints (i.e. endpoints for which video should always be forwarded,
   * regardless of {@code lastN}).
   *
   * @param newPinnedEndpointIds the list of endpoint IDs to set.
   */
  public void setPinnedEndpointIds(List<String> newPinnedEndpointIds) {
    if (logger.isDebugEnabled()) {
      logger.debug("Setting pinned endpoints: " + newPinnedEndpointIds.toString());
    }
    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 (!pinnedEndpoints.equals(newPinnedEndpointIds)) {
        pinnedEndpoints = Collections.unmodifiableList(newPinnedEndpointIds);

        endpointsToAskForKeyframe = update();
      }
    }

    askForKeyframes(endpointsToAskForKeyframe);
  }
  /**
   * Sends the <tt>message</tt> to the destination indicated by the <tt>to</tt> contact.
   *
   * @param to the <tt>Contact</tt> to send <tt>message</tt> to
   * @param message the <tt>Message</tt> to send.
   * @throws java.lang.IllegalStateException if the underlying stack is not registered and
   *     initialized.
   * @throws java.lang.IllegalArgumentException if <tt>to</tt> is not an instance of ContactImpl.
   */
  public void sendInstantMessage(Contact to, Message message)
      throws IllegalStateException, IllegalArgumentException {
    if (!(to instanceof ContactSipImpl))
      throw new IllegalArgumentException("The specified contact is not a Sip contact." + to);

    assertConnected();

    // offline message
    if (to.getPresenceStatus().equals(sipStatusEnum.getStatus(SipStatusEnum.OFFLINE))
        && !offlineMessageSupported) {
      if (logger.isDebugEnabled()) logger.debug("trying to send a message to an offline contact");
      fireMessageDeliveryFailed(
          message, to, MessageDeliveryFailedEvent.OFFLINE_MESSAGES_NOT_SUPPORTED);
      return;
    }

    // create the message
    Request mes;
    try {
      mes = createMessageRequest(to, message);
    } catch (OperationFailedException ex) {
      logger.error("Failed to create the message.", ex);

      fireMessageDeliveryFailed(message, to, MessageDeliveryFailedEvent.INTERNAL_ERROR);
      return;
    }

    try {
      sendMessageRequest(mes, to, message);
    } catch (TransactionUnavailableException ex) {
      logger.error(
          "Failed to create messageTransaction.\n"
              + "This is most probably a network connection error.",
          ex);

      fireMessageDeliveryFailed(message, to, MessageDeliveryFailedEvent.NETWORK_FAILURE);
      return;
    } catch (SipException ex) {
      logger.error("Failed to send the message.", ex);

      fireMessageDeliveryFailed(message, to, MessageDeliveryFailedEvent.INTERNAL_ERROR);
      return;
    }
  }
  /**
   * Sends a file transfer request to the given <tt>toContact</tt> by specifying the local and
   * remote file path and the <tt>fromContact</tt>, sending the file.
   *
   * @param toContact the contact that should receive the file
   * @param file the file to send
   * @return the transfer object
   * @throws IllegalStateException if the protocol provider is not registered or connected
   * @throws IllegalArgumentException if some of the arguments doesn't fit the protocol requirements
   */
  public FileTransfer sendFile(Contact toContact, File file)
      throws IllegalStateException, IllegalArgumentException {
    assertConnected();

    if (file.length() > getMaximumFileLength())
      throw new IllegalArgumentException("File length exceeds the allowed one for this protocol");

    // Get the aim connection
    AimConnection aimConnection = icqProvider.getAimConnection();

    // Create an outgoing file transfer instance
    OutgoingFileTransfer outgoingFileTransfer =
        aimConnection
            .getIcbmService()
            .getRvConnectionManager()
            .createOutgoingFileTransfer(new Screenname(toContact.getAddress()));

    String id =
        String.valueOf(outgoingFileTransfer.getRvSessionInfo().getRvSession().getRvSessionId());

    FileTransferImpl outFileTransfer =
        new FileTransferImpl(outgoingFileTransfer, id, toContact, file, FileTransfer.OUT);

    // Adding the file to the outgoing file transfer
    try {
      outgoingFileTransfer.setSingleFile(new File(file.getPath()));
    } catch (IOException e) {
      if (logger.isDebugEnabled()) logger.debug("Error sending file", e);
      return null;
    }

    // Notify all interested listeners that a file transfer has been
    // created.
    FileTransferCreatedEvent event = new FileTransferCreatedEvent(outFileTransfer, new Date());

    fireFileTransferCreated(event);

    // Sending the file
    outgoingFileTransfer.sendRequest(new InvitationMessage(""));

    outFileTransfer.fireStatusChangeEvent(FileTransferStatusChangeEvent.PREPARING);

    return outFileTransfer;
  }
Example #28
0
  /**
   * 按主键查找一条数据
   *
   * @param lineCode 线路名称
   * @return LineLossDto
   * @throws Exception
   */
  public LineLossDto findByPrimaryKey(String lineCode) throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    // 拼SQL语句
    buffer.append("SELECT ");
    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("FROM LineLoss ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append(buffer.toString());
      debugBuffer.append("WHERE ");
      debugBuffer.append("LineCode=").append("'").append(lineCode).append("'");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("WHERE ");
    buffer.append("LineCode = ?");

    dbManager.prepareStatement(buffer.toString());
    // 设置条件字段;
    dbManager.setString(1, lineCode);
    ResultSet resultSet = dbManager.executePreparedQuery();
    LineLossDto lineLossDto = null;
    if (resultSet.next()) {
      lineLossDto = new LineLossDto();
      lineLossDto.setLineCode(dbManager.getString(resultSet, 1));
      lineLossDto.setR(dbManager.getDouble(resultSet, 2));
      lineLossDto.setLineLong(dbManager.getDouble(resultSet, 3));
      lineLossDto.setVolt(dbManager.getDouble(resultSet, 4));
      lineLossDto.setT(dbManager.getDouble(resultSet, 5));
      lineLossDto.setValidStatus(dbManager.getString(resultSet, 6));
      lineLossDto.setFlag(dbManager.getString(resultSet, 7));
      lineLossDto.setRemark(dbManager.getString(resultSet, 8));
    }
    resultSet.close();
    return lineLossDto;
  }
Example #29
0
  /**
   * 按主键删除一条数据
   *
   * @param lineCode 线路名称
   * @throws Exception
   */
  public void delete(String lineCode) throws Exception {
    StringBuffer buffer = new StringBuffer(100);
    buffer.append("DELETE FROM LineLoss ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append(buffer.toString());
      debugBuffer.append("WHERE ");
      debugBuffer.append("LineCode=").append("'").append(lineCode).append("'");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("WHERE ");
    buffer.append("LineCode = ?");

    dbManager.prepareStatement(buffer.toString());
    // 设置条件字段;
    dbManager.setString(1, lineCode);
    dbManager.executePreparedUpdate();
  }
  /**
   * Removes the RTX encapsulation from a packet.
   *
   * @param pkt the packet to remove the RTX encapsulation from.
   * @return the original media packet represented by {@code pkt}, or null if we couldn't
   *     reconstruct the original packet.
   */
  private RawPacket deRtx(RawPacket pkt) {
    boolean success = false;

    if (pkt.getPayloadLength() - pkt.getPaddingSize() < 2) {
      // We need at least 2 bytes to read the OSN field.
      if (logger.isDebugEnabled()) {
        logger.debug("Dropping an incoming RTX packet with padding only: " + pkt);
      }
      return null;
    }

    long mediaSsrc = getPrimarySsrc(pkt);
    if (mediaSsrc != -1) {
      if (rtxAssociatedPayloadType != -1) {
        int osn = pkt.getOriginalSequenceNumber();
        // Remove the RTX header by moving the RTP header two bytes
        // right.
        byte[] buf = pkt.getBuffer();
        int off = pkt.getOffset();
        System.arraycopy(buf, off, buf, off + 2, pkt.getHeaderLength());

        pkt.setOffset(off + 2);
        pkt.setLength(pkt.getLength() - 2);

        pkt.setSSRC((int) mediaSsrc);
        pkt.setSequenceNumber(osn);
        pkt.setPayloadType(rtxAssociatedPayloadType);
        success = true;
      } else {
        logger.warn(
            "RTX packet received, but no APT is defined. Packet "
                + "SSRC "
                + pkt.getSSRCAsLong()
                + ", associated media"
                + " SSRC "
                + mediaSsrc);
      }
    }

    // If we failed to handle the RTX packet, drop it.
    return success ? pkt : null;
  }