Esempio n. 1
0
  /**
   * Receives options requests and replies with an OK response containing methods that we support.
   *
   * @param requestEvent the incoming options request.
   * @return <tt>true</tt> if request has been successfully processed, <tt>false</tt> otherwise
   */
  @Override
  public boolean processRequest(RequestEvent requestEvent) {
    Response optionsOK = null;
    try {
      optionsOK =
          provider.getMessageFactory().createResponse(Response.OK, requestEvent.getRequest());

      // add to the allows header all methods that we support
      for (String method : provider.getSupportedMethods()) {
        // don't support REGISTERs
        if (!method.equals(Request.REGISTER))
          optionsOK.addHeader(provider.getHeaderFactory().createAllowHeader(method));
      }

      Iterable<String> knownEventsList = provider.getKnownEventsList();

      synchronized (knownEventsList) {
        for (String event : knownEventsList)
          optionsOK.addHeader(provider.getHeaderFactory().createAllowEventsHeader(event));
      }
    } catch (ParseException ex) {
      // What else could we do apart from logging?
      logger.warn("Failed to create an incoming OPTIONS request", ex);
      return false;
    }

    try {
      SipStackSharing.getOrCreateServerTransaction(requestEvent).sendResponse(optionsOK);
    } catch (TransactionUnavailableException ex) {
      // this means that we received an OPTIONS request outside the scope
      // of a transaction which could mean that someone is simply sending
      // us b****hit to keep a NAT connection alive, so let's not get too
      // excited.
      if (logger.isInfoEnabled())
        logger.info("Failed to respond to an incoming " + "transactionless OPTIONS request");
      if (logger.isTraceEnabled()) logger.trace("Exception was:", ex);
      return false;
    } catch (InvalidArgumentException ex) {
      // What else could we do apart from logging?
      logger.warn("Failed to send an incoming OPTIONS request", ex);
      return false;
    } catch (SipException ex) {
      // What else could we do apart from logging?
      logger.warn("Failed to send an incoming OPTIONS request", ex);
      return false;
    }

    return true;
  }
  /**
   * Returns the <tt>URL</tt> of the sound corresponding to the given property key.
   *
   * @return the <tt>URL</tt> of the sound corresponding to the given property key.
   */
  public URL getSoundURL(String urlKey) {
    String path = getSoundPath(urlKey);

    if (path == null || path.length() == 0) {
      logger.warn("Missing resource for key: " + urlKey);
      return null;
    }
    return getSoundURLForPath(path);
  }
  /**
   * Returns the <tt>InputStream</tt> of the image corresponding to the given key.
   *
   * @param streamKey The identifier of the image in the resource properties file.
   * @return the <tt>InputStream</tt> of the image corresponding to the given key.
   */
  public InputStream getImageInputStream(String streamKey) {
    String path = getImagePath(streamKey);

    if (path == null || path.length() == 0) {
      logger.warn("Missing resource for key: " + streamKey);
      return null;
    }

    return getImageInputStreamForPath(path);
  }
Esempio n. 4
0
  public ClientThread(Socket socket, History history, Users users) throws IOException {

    logger.warn("New client is trying to connect to the chat...");
    logger.info("Assigning a socket to a new client...");
    this.s = socket;

    logger.info("Getting the input stream...");
    in = new DataInputStream(s.getInputStream());

    logger.info("Getting the output stream...");
    out = new DataOutputStream(s.getOutputStream());

    this.users = users;
    users.addObserver(this);

    this.history = history;

    start();
    logger.warn("Connection with new user is established.");
  }
Esempio n. 5
0
 public void run() {
   try {
     prepareClient();
     logger.info("Starting normal session with " + getClientName());
     while (true) {
       this.receive();
     }
   } catch (IOException ioe) {
     logger.warn("Client " + this + " has been disconnected.");
     this.setDisabled(true);
     users.remove(this);
   } finally {
     try {
       if (s != null && !s.isClosed()) {
         s.close();
         logger.warn("Socket with " + this + " has been closed.");
       }
     } catch (IOException ioe) {
       logger.error("Socket has not been closed.", ioe);
     }
   }
 }
Esempio n. 6
0
  /**
   * Retrieves default values from xml.
   *
   * @param list the configuration list
   */
  private static void parseDefaults(NodeList list) {
    for (int i = 0; i < list.getLength(); ++i) {
      NamedNodeMap mapping = list.item(i).getAttributes();
      String attribute = mapping.getNamedItem("attribute").getNodeValue();
      String value = mapping.getNamedItem("value").getNodeValue();

      try {
        Default field = Default.fromString(attribute);
        DEFAULTS.put(field, value);
      } catch (IllegalArgumentException exc) {
        logger.warn("Unrecognized default attribute: " + attribute);
      }
    }
  }
Esempio n. 7
0
 /**
  * Populates LOCALES list with contents of xml.
  *
  * @param list the configuration list
  */
 private static void parseLocales(NodeList list) {
   for (int i = 0; i < list.getLength(); ++i) {
     Node node = list.item(i);
     NamedNodeMap attributes = node.getAttributes();
     String label = ((Attr) attributes.getNamedItem("label")).getValue();
     String code = ((Attr) attributes.getNamedItem("isoCode")).getValue();
     String dictLocation = ((Attr) attributes.getNamedItem("dictionaryUrl")).getValue();
     try {
       LOCALES.add(new Locale(label, code, new URL(dictLocation)));
     } catch (MalformedURLException exc) {
       logger.warn(
           "Unable to parse dictionary location of " + label + " (" + dictLocation + ")", exc);
     }
   }
 }
Esempio n. 8
0
  static {
    try {
      URL url = SpellCheckActivator.bundleContext.getBundle().getResource(RESOURCE_LOC);

      InputStream stream = url.openStream();

      if (stream == null) throw new IOException();

      // strict parsing options
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

      factory.setValidating(false);
      factory.setIgnoringComments(true);
      factory.setIgnoringElementContentWhitespace(true);

      // parses configuration xml
      /*-
       * Warning: Felix is unable to import the com.sun.rowset.internal
       * package, meaning this can't use the XmlErrorHandler. This causes
       * a warning and a default handler to be attached. Otherwise this
       * should have: builder.setErrorHandler(new XmlErrorHandler());
       */
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse(stream);

      // iterates over nodes, parsing contents
      Node root = doc.getChildNodes().item(1);

      NodeList categories = root.getChildNodes();

      for (int i = 0; i < categories.getLength(); ++i) {
        Node node = categories.item(i);
        if (node.getNodeName().equals(NODE_DEFAULTS)) {
          parseDefaults(node.getChildNodes());
        } else if (node.getNodeName().equals(NODE_LOCALES)) {
          parseLocales(node.getChildNodes());
        } else {
          logger.warn("Unrecognized category: " + node.getNodeName());
        }
      }
    } catch (IOException exc) {
      logger.error("Unable to load spell checker parameters", exc);
    } catch (SAXException exc) {
      logger.error("Unable to parse spell checker parameters", exc);
    } catch (ParserConfigurationException exc) {
      logger.error("Unable to parse spell checker parameters", exc);
    }
  }
  /**
   * Returns an InetAddress instance that represents the localhost, and that a socket can bind upon
   * or distribute to peers as a contact address.
   *
   * @param intendedDestination the destination that we'd like to use the localhost address with.
   * @return an InetAddress instance representing the local host, and that a socket can bind upon or
   *     distribute to peers as a contact address.
   */
  public synchronized InetAddress getLocalHost(InetAddress intendedDestination) {
    // no point in making sure that the localHostFinderSocket is initialized.
    // better let it through a NullPointerException.
    InetAddress localHost = null;
    localHostFinderSocket.connect(intendedDestination, this.RANDOM_ADDR_DISC_PORT);
    localHost = localHostFinderSocket.getLocalAddress();
    localHostFinderSocket.disconnect();
    // windows socket implementations return the any address so we need to
    // find something else here ... InetAddress.getLocalHost seems to work
    // better on windows so lets hope it'll do the trick.
    if (localHost.isAnyLocalAddress()) {
      try {
        // all that's inside the if is an ugly IPv6 hack
        // (good ol' IPv6 - always causing more problems than it solves.)
        if (intendedDestination instanceof Inet6Address) {
          // return the first globally routable ipv6 address we find
          // on the machine (and hope it's a good one)
          Enumeration interfaces = NetworkInterface.getNetworkInterfaces();

          while (interfaces.hasMoreElements()) {
            NetworkInterface iface = (NetworkInterface) interfaces.nextElement();
            Enumeration addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
              InetAddress address = (InetAddress) addresses.nextElement();
              if (address instanceof Inet6Address) {
                if (!address.isAnyLocalAddress()
                    && !address.isLinkLocalAddress()
                    && !address.isSiteLocalAddress()
                    && !address.isLoopbackAddress()) {
                  return address;
                }
              }
            }
          }
        } else localHost = InetAddress.getLocalHost();
        /** @todo test on windows for ipv6 cases */
      } catch (Exception ex) {
        // sigh ... ok return 0.0.0.0
        logger.warn("Failed to get localhost ", ex);
      }
    }

    return localHost;
  }
  /**
   * {@inheritDoc}
   *
   * <p>SCTP input data callback.
   */
  @Override
  public void onSctpPacket(
      byte[] data, int sid, int ssn, int tsn, long ppid, int context, int flags) {
    if (ppid == WEB_RTC_PPID_CTRL) {
      // Channel control PPID
      try {
        onCtrlPacket(data, sid);
      } catch (IOException e) {
        logger.error("IOException when processing ctrl packet", e);
      }
    } else if (ppid == WEB_RTC_PPID_STRING || ppid == WEB_RTC_PPID_BIN) {
      WebRtcDataStream channel;

      synchronized (this) {
        channel = channels.get(sid);
      }

      if (channel == null) {
        logger.error("No channel found for sid: " + sid);
        return;
      }
      if (ppid == WEB_RTC_PPID_STRING) {
        // WebRTC String
        String str;
        String charsetName = "UTF-8";

        try {
          str = new String(data, charsetName);
        } catch (UnsupportedEncodingException uee) {
          logger.error("Unsupported charset encoding/name " + charsetName, uee);
          str = null;
        }
        channel.onStringMsg(str);
      } else {
        // WebRTC Binary
        channel.onBinaryMsg(data);
      }
    } else {
      logger.warn("Got message on unsupported PPID: " + ppid);
    }
  }
Esempio n. 11
0
  public void init() throws MQClientException {
    nameServer = PropertyFileUtil.get("rocketmq.namesrv.domain");

    if (StringUtils.isBlank(nameServer)) {

      logger.warn("【MQ init】property rocketmq.namesrv.domain not found");

      return;
    }

    if ("localTest".equals(nameServer)) {

      logger.warn("【MQ init】localTest");

      return;
    }

    if (StringUtils.isBlank(System.getProperty("rocketmq.namesrv.domain"))) {
      System.setProperty("rocketmq.namesrv.domain", nameServer);
    }
    topicType = getTopic();
    topic = RocketMqUtils.getTopic(topicType);

    if (StringUtils.isBlank(group)) {
      group = "S_" + topic.getTopic() + "_" + topic.getTags();
    }
    consumer = new DefaultMQPushConsumer(group);
    consumer.setNamesrvAddr(nameServer);
    consumer.setMessageModel(getMessageModel());
    consumer.setConsumeThreadMin(minConsumeThread);
    consumer.setConsumeThreadMax(maxConsumeThread);
    // 可以不设置 设置后可以起多个 消费端
    try {
      consumer.setInstanceName("DEFAULT_CONSUMER-" + InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
      logger.error("getHostName error", e);
    }
    // 设置订阅的topic 设置订阅过滤表达式
    if (StringUtils.isBlank(subExpression)) {
      subExpression = topic.getTags();
      consumer.subscribe(topic.getTopic(), subExpression);
    } else {
      consumer.subscribe(topic.getTopic(), subExpression);
    }
    try {
      consumer.registerMessageListener(this);
      consumer.start();
    } catch (MQClientException e) {
      logger.error(
          "consumer start error!topic={},subExpression={},group={}",
          topic.getTopic(),
          subExpression,
          group,
          e);
    }
    logger.info(
        "consumer start! topic={},subExpression={},group={}",
        topic.getTopic(),
        subExpression,
        group);
  }
  /**
   * Handles control packet.
   *
   * @param data raw packet data that arrived on control PPID.
   * @param sid SCTP stream id on which the data has arrived.
   */
  private synchronized void onCtrlPacket(byte[] data, int sid) throws IOException {
    ByteBuffer buffer = ByteBuffer.wrap(data);
    int messageType = /* 1 byte unsigned integer */ 0xFF & buffer.get();

    if (messageType == MSG_CHANNEL_ACK) {
      if (logger.isDebugEnabled()) {
        logger.debug(getEndpoint().getID() + " ACK received SID: " + sid);
      }
      // Open channel ACK
      WebRtcDataStream channel = channels.get(sid);
      if (channel != null) {
        // Ack check prevents from firing multiple notifications
        // if we get more than one ACKs (by mistake/bug).
        if (!channel.isAcknowledged()) {
          channel.ackReceived();
          notifyChannelOpened(channel);
        } else {
          logger.warn("Redundant ACK received for SID: " + sid);
        }
      } else {
        logger.error("No channel exists on sid: " + sid);
      }
    } else if (messageType == MSG_OPEN_CHANNEL) {
      int channelType = /* 1 byte unsigned integer */ 0xFF & buffer.get();
      int priority = /* 2 bytes unsigned integer */ 0xFFFF & buffer.getShort();
      long reliability = /* 4 bytes unsigned integer */ 0xFFFFFFFFL & buffer.getInt();
      int labelLength = /* 2 bytes unsigned integer */ 0xFFFF & buffer.getShort();
      int protocolLength = /* 2 bytes unsigned integer */ 0xFFFF & buffer.getShort();
      String label;
      String protocol;

      if (labelLength == 0) {
        label = "";
      } else {
        byte[] labelBytes = new byte[labelLength];

        buffer.get(labelBytes);
        label = new String(labelBytes, "UTF-8");
      }
      if (protocolLength == 0) {
        protocol = "";
      } else {
        byte[] protocolBytes = new byte[protocolLength];

        buffer.get(protocolBytes);
        protocol = new String(protocolBytes, "UTF-8");
      }

      if (logger.isDebugEnabled()) {
        logger.debug(
            "!!! "
                + getEndpoint().getID()
                + " data channel open request on SID: "
                + sid
                + " type: "
                + channelType
                + " prio: "
                + priority
                + " reliab: "
                + reliability
                + " label: "
                + label
                + " proto: "
                + protocol);
      }

      if (channels.containsKey(sid)) {
        logger.error("Channel on sid: " + sid + " already exists");
      }

      WebRtcDataStream newChannel = new WebRtcDataStream(sctpSocket, sid, label, true);
      channels.put(sid, newChannel);

      sendOpenChannelAck(sid);

      notifyChannelOpened(newChannel);
    } else {
      logger.error("Unexpected ctrl msg type: " + messageType);
    }
  }
Esempio n. 13
0
 /**
  * Log an exception.
  *
  * @param ex the exception that we are to log.
  */
 public void logException(Throwable ex) {
   logger.warn("Exception in the JAIN-SIP stack: " + ex.getMessage());
   if (logger.isInfoEnabled()) logger.info("JAIN-SIP exception stack trace is", ex);
 }
Esempio n. 14
0
 /**
  * Prints the specified <tt>exception</tt> as a warning.
  *
  * @param exception the <tt>Exception</tt> we are passed from jain-sip.
  */
 public void logException(Exception exception) {
   logger.warn("the following exception occured in JAIN-SIP: " + exception, exception);
 }
Esempio n. 15
0
 /**
  * Log a warning message.
  *
  * @param string the warning that we'd like to log
  */
 public void logWarning(String string) {
   logger.warn("Warning from the JAIN-SIP stack" + string);
 }
Esempio n. 16
0
  /**
   * Listens for incoming datagrams, stores them for reading by the <tt>read</tt> method and
   * notifies the local <tt>transferHandler</tt> that there's data to be read.
   */
  public void run() {
    DatagramPacket p = new DatagramPacket(buffer, 0, PACKET_RECEIVE_BUFFER_LENGTH);

    while (!closed) {
      try {
        // http://code.google.com/p/android/issues/detail?id=24765
        if (OSUtils.IS_ANDROID) p.setLength(PACKET_RECEIVE_BUFFER_LENGTH);

        receivePacket(p);
      } catch (IOException e) {
        ioError = true;
        break;
      }

      /*
       * Do the DatagramPacketFilters accept the received DatagramPacket?
       */
      DatagramPacketFilter[] datagramPacketFilters = getDatagramPacketFilters();
      boolean accept;

      if (!enabled) accept = false;
      else if (datagramPacketFilters == null) accept = true;
      else {
        accept = true;
        for (int i = 0; i < datagramPacketFilters.length; i++) {
          try {
            if (!datagramPacketFilters[i].accept(p)) {
              accept = false;
              break;
            }
          } catch (Throwable t) {
            if (t instanceof ThreadDeath) throw (ThreadDeath) t;
          }
        }
      }

      if (accept) {
        RawPacket pkts[] = createRawPacket(p);

        for (int i = 0; i < pkts.length; i++) {
          RawPacket pkt = pkts[i];

          pkts[i] = null;

          if (pkt != null) {
            if (pkt.isInvalid()) {
              /*
               * Return pkt to the pool because it is invalid and,
               * consequently, will not be made available to
               * reading.
               */
              poolRawPacket(pkt);
            } else {
              RawPacket oldPkt;

              synchronized (pktSyncRoot) {
                oldPkt = this.pkt;
                this.pkt = pkt;
              }
              if (oldPkt != null) {
                /*
                 * Return oldPkt to the pool because it was made
                 * available to reading and it was not read.
                 */
                poolRawPacket(oldPkt);
              }

              if (videoRecorder != null) videoRecorder.recordData(pkt);

              if ((transferHandler != null) && !closed) {
                try {
                  transferHandler.transferData(this);
                } catch (Throwable t) {
                  /*
                   * XXX We cannot allow transferHandler to
                   * kill us.
                   */
                  if (t instanceof ThreadDeath) {
                    throw (ThreadDeath) t;
                  } else {
                    logger.warn("An RTP packet may have not been" + " fully handled.", t);
                  }
                }
              }
            }
          }
        }
        rawPacketArrayPool.offer(pkts);
      }
    }
  }