/**
   * Retransmits a packet to {@link #channel}. If the destination supports the RTX format, the
   * packet will be encapsulated in RTX, otherwise, the packet will be retransmitted as-is.
   *
   * @param pkt the packet to retransmit.
   * @param after the {@code TransformEngine} in the chain of {@code TransformEngine}s of the
   *     associated {@code MediaStream} after which the injection of {@code pkt} is to begin
   * @return {@code true} if the packet was successfully retransmitted, {@code false} otherwise.
   */
  public boolean retransmit(RawPacket pkt, TransformEngine after) {
    boolean destinationSupportsRtx = channel.getRtxPayloadType() != -1;
    boolean retransmitPlain;

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

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

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

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

    return true;
  }
  /**
   * Checks whether RTP packets from {@code sourceChannel} should be forwarded to {@link #channel}.
   *
   * @param sourceChannel the channel.
   * @return {@code true} iff RTP packets from {@code sourceChannel} should be forwarded to {@link
   *     #channel}.
   */
  public boolean isForwarded(Channel sourceChannel) {
    if (lastN < 0 && currentLastN < 0) {
      // If Last-N is disabled, we forward everything.
      return true;
    }

    if (sourceChannel == null) {
      logger.warn("Invalid sourceChannel: null.");
      return false;
    }

    Endpoint channelEndpoint = sourceChannel.getEndpoint();
    if (channelEndpoint == null) {
      logger.warn("sourceChannel has no endpoint.");
      return false;
    }

    if (forwardedEndpoints == INITIAL_EMPTY_LIST) {
      // LastN is enabled, but we haven't yet initialized the list of
      // endpoints in the conference.
      initializeConferenceEndpoints();
    }

    // This may look like a place to optimize, because we query an unordered
    // list (in O(n)) and it executes on each video packet if lastN is
    // enabled. However, the size of  forwardedEndpoints is restricted to
    // lastN and so small enough that it is not worth optimizing.
    return forwardedEndpoints.contains(channelEndpoint.getID());
  }
Esempio n. 3
0
 public final boolean assertInstanceOf(String $label, Class<?> $klass, Object $obj) {
   if ($obj == null) {
     $unitFailures++;
     $log.warn(
         messageFail(
             $label, "null is never an instance of anything, and certainly not " + $klass + "."),
         new AssertionFailed());
     return false;
   }
   try {
     $klass.cast($obj);
     $log.debug(
         messagePass(
             $label,
             "\""
                 + $obj.getClass().getCanonicalName()
                 + "\" is an instance of \""
                 + $klass.getCanonicalName()
                 + "\""));
     return true;
   } catch (ClassCastException $e) {
     $unitFailures++;
     $log.warn(messageFail($label, $e.getMessage() + "."), new AssertionFailed());
     return false;
   }
 }
Esempio n. 4
0
  /**
   * Place to put some hacks if needed on incoming requests.
   *
   * @param event the incoming request event.
   * @return status <code>true</code> if we don't need to process this message, just discard it and
   *     <code>false</code> otherwise.
   */
  private boolean applyNonConformanceHacks(RequestEvent event) {
    Request request = event.getRequest();
    try {
      /*
       * Max-Forwards is required, yet there are UAs which do not
       * place it. SipProvider#getNewServerTransaction(Request)
       * will throw an exception in the case of a missing
       * Max-Forwards header and this method will eventually just
       * log it thus ignoring the whole event.
       */
      if (request.getHeader(MaxForwardsHeader.NAME) == null) {
        // it appears that some buggy providers do send requests
        // with no Max-Forwards headers, as we are at application level
        // and we know there will be no endless loops
        // there is no problem of adding headers and process normally
        // this messages
        MaxForwardsHeader maxForwards =
            SipFactory.getInstance().createHeaderFactory().createMaxForwardsHeader(70);
        request.setHeader(maxForwards);
      }
    } catch (Throwable ex) {
      logger.warn("Cannot apply incoming request modification!", ex);
    }

    try {
      // using asterisk voice mail initial notify for messages
      // is ok, but on the fly received messages their notify comes
      // without subscription-state, so we add it in order to be able to
      // process message.
      if (request.getMethod().equals(Request.NOTIFY)
          && request.getHeader(EventHeader.NAME) != null
          && ((EventHeader) request.getHeader(EventHeader.NAME))
              .getEventType()
              .equals(OperationSetMessageWaitingSipImpl.EVENT_PACKAGE)
          && request.getHeader(SubscriptionStateHeader.NAME) == null) {
        request.addHeader(
            new HeaderFactoryImpl().createSubscriptionStateHeader(SubscriptionStateHeader.ACTIVE));
      }
    } catch (Throwable ex) {
      logger.warn("Cannot apply incoming request modification!", ex);
    }

    try {
      // receiving notify message without subscription state
      // used for keep-alive pings, they have done their job
      // and are no more need. Skip processing them to avoid
      // filling logs with unneeded exceptions.
      if (request.getMethod().equals(Request.NOTIFY)
          && request.getHeader(SubscriptionStateHeader.NAME) == null) {
        return true;
      }
    } catch (Throwable ex) {
      logger.warn("Cannot apply incoming request modification!", ex);
    }

    return false;
  }
  /**
   * Downloads a Bundle file for a given bundle id.
   *
   * @param request HttpRequest
   * @param response HttpResponse
   * @throws IOException If fails sending back to the user response information
   */
  public void downloadBundle(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    try {
      if (!APILocator.getLayoutAPI()
          .doesUserHaveAccessToPortlet("EXT_CONTENT_PUBLISHING_TOOL", getUser())) {
        response.sendError(401);
        return;
      }
    } catch (DotDataException e1) {
      Logger.error(RemotePublishAjaxAction.class, e1.getMessage(), e1);
      response.sendError(401);
      return;
    }
    Map<String, String> map = getURIParams();
    response.setContentType("application/x-tgz");

    String bid = map.get("bid");

    PublisherConfig config = new PublisherConfig();
    config.setId(bid);
    File bundleRoot = BundlerUtil.getBundleRoot(config);

    ArrayList<File> list = new ArrayList<File>(1);
    list.add(bundleRoot);
    File bundle =
        new File(bundleRoot + File.separator + ".." + File.separator + config.getId() + ".tar.gz");
    if (!bundle.exists()) {
      response.sendError(500, "No Bundle Found");
      return;
    }

    response.setHeader("Content-Disposition", "attachment; filename=" + config.getId() + ".tar.gz");
    BufferedInputStream in = null;
    try {
      in = new BufferedInputStream(new FileInputStream(bundle));
      byte[] buf = new byte[4096];
      int len;

      while ((len = in.read(buf, 0, buf.length)) != -1) {
        response.getOutputStream().write(buf, 0, len);
      }
    } catch (Exception e) {
      Logger.warn(this.getClass(), "Error Downloading Bundle.", e);
    } finally {
      try {
        in.close();
      } catch (Exception ex) {
        Logger.warn(this.getClass(), "Error Closing Stream.", ex);
      }
    }
    return;
  }
Esempio n. 6
0
  /**
   * Returns {@code true} if a specific RED packet contains multiple blocks;
   * {@code false}, otherwise.
   *
   * @param buffer the byte buffer that contains the RED payload.
   * @param offset the offset in the buffer where the RED payload begins.
   * @param length the length of the RED payload.
   * @return {@code true if {@pkt} contains multiple RED blocks; otherwise,
   * {@code false}
   */
  public static boolean isMultiBlock(byte[] buffer, int offset, int length) {
    if (buffer == null || buffer.length == 0) {
      logger.warn("The buffer appears to be empty.");
      return false;
    }

    if (offset < 0 || buffer.length <= offset) {
      logger.warn("Prevented array out of bounds exception.");
      return false;
    }

    return (buffer[offset] & 0x80) != 0;
  }
Esempio n. 7
0
  /**
   * Restarts the recording for a specific SSRC.
   *
   * @param ssrc the SSRC for which to restart recording. RTP packet of the new recording).
   */
  private void resetRecording(long ssrc, long timestamp) {
    ReceiveStreamDesc receiveStream = findReceiveStream(ssrc);

    // we only restart audio recordings
    if (receiveStream != null && receiveStream.format instanceof AudioFormat) {
      String newFilename = getNextFilename(path + "/" + ssrc, AUDIO_FILENAME_SUFFIX);

      // flush the buffer contained in the MP3 encoder
      String s = "trying to flush ssrc=" + ssrc;
      Processor p = receiveStream.processor;
      if (p != null) {
        s += " p!=null";
        for (TrackControl tc : p.getTrackControls()) {
          Object o = tc.getControl(FlushableControl.class.getName());
          if (o != null) ((FlushableControl) o).flush();
        }
      }

      if (logger.isInfoEnabled()) {
        logger.info("Restarting recording for SSRC=" + ssrc + ". New filename: " + newFilename);
      }

      receiveStream.dataSink.close();
      receiveStream.dataSink = null;

      // flush the FMJ jitter buffer
      // DataSource ds = receiveStream.receiveStream.getDataSource();
      // if (ds instanceof net.sf.fmj.media.protocol.rtp.DataSource)
      //    ((net.sf.fmj.media.protocol.rtp.DataSource)ds).flush();

      receiveStream.filename = newFilename;
      try {
        receiveStream.dataSink =
            Manager.createDataSink(
                receiveStream.dataSource, new MediaLocator("file:" + newFilename));
      } catch (NoDataSinkException ndse) {
        logger.warn("Could not reset recording for SSRC=" + ssrc + ": " + ndse);
        removeReceiveStream(receiveStream, false);
      }

      try {
        receiveStream.dataSink.open();
        receiveStream.dataSink.start();
      } catch (IOException ioe) {
        logger.warn("Could not reset recording for SSRC=" + ssrc + ": " + ioe);
        removeReceiveStream(receiveStream, false);
      }

      audioRecordingStarted(ssrc, timestamp);
    }
  }
Esempio n. 8
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;
  }
  /**
   * Tries to find an SSRC paired with {@code ssrc} in an FID group in one of the channels from
   * {@link #channel}'s {@code Content}. Returns -1 on failure.
   *
   * @param pkt the {@code RawPacket} that holds the RTP packet for which to find a paired SSRC.
   * @return An SSRC paired with {@code ssrc} in an FID group, or -1.
   */
  private long getRtxSsrc(RawPacket pkt) {
    StreamRTPManager receiveRTPManager =
        channel.getStream().getRTPTranslator().findStreamRTPManagerByReceiveSSRC(pkt.getSSRC());

    MediaStreamTrackReceiver receiver = null;
    if (receiveRTPManager != null) {
      MediaStream receiveStream = receiveRTPManager.getMediaStream();
      if (receiveStream != null) {
        receiver = receiveStream.getMediaStreamTrackReceiver();
      }
    }

    if (receiver == null) {
      return -1;
    }

    RTPEncoding encoding = receiver.resolveRTPEncoding(pkt);
    if (encoding == null) {
      logger.warn(
          "encoding_not_found"
              + ",stream_hash="
              + channel.getStream().hashCode()
              + " ssrc="
              + pkt.getSSRCAsLong());
      return -1;
    }

    return encoding.getRTXSSRC();
  }
        /** {@inheritDoc} */
        @Override
        public RawPacket transform(RawPacket pkt) {
          if (pkt == null) {
            return pkt;
          }

          RTCPCompoundPacket inPacket;
          try {
            inPacket =
                (RTCPCompoundPacket)
                    parser.parse(pkt.getBuffer(), pkt.getOffset(), pkt.getLength());
          } catch (BadFormatException e) {
            logger.warn("Failed to terminate an RTCP packet. " + "Dropping packet.");
            return null;
          }

          // Update our RTCP stats map (timestamps). This operation is
          // read-only.
          remoteClockEstimator.apply(inPacket);

          cnameRegistry.update(inPacket);

          // Remove SRs and RRs from the RTCP packet.
          pkt = feedbackGateway.gateway(inPacket);

          return pkt;
        }
Esempio n. 11
0
 /** Allow some code to run very early in Play - Use with caution ! */
 public static void initStaticStuff() {
   // Play! plugings
   Enumeration<URL> urls = null;
   try {
     urls = Play.class.getClassLoader().getResources("play.static");
   } catch (Exception e) {
   }
   while (urls != null && urls.hasMoreElements()) {
     URL url = urls.nextElement();
     try {
       BufferedReader reader =
           new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
       String line = null;
       while ((line = reader.readLine()) != null) {
         try {
           Class.forName(line);
         } catch (Exception e) {
           Logger.warn("! Cannot init static: " + line);
         }
       }
     } catch (Exception ex) {
       Logger.error(ex, "Cannot load %s", url);
     }
   }
 }
Esempio n. 12
0
 public static void save(Project project) {
   System.out.println("---> " + project.isPersistent());
   Logger.warn("Next warning is intended!");
   project.save();
   validation.keep();
   show(project.id);
 }
Esempio n. 13
0
 protected List<MappingWithDirection> findApplicable(MappingKey key) {
   ArrayList<MappingWithDirection> result = new ArrayList<MappingWithDirection>();
   for (ParsedMapping pm : mappings) {
     if ((pm.mappingCase == null && key.mappingCase == null)
         ^ (pm.mappingCase != null && pm.mappingCase.equals(key.mappingCase))) {
       if (pm.sideA.isAssignableFrom(key.source) && pm.sideB.isAssignableFrom(key.target))
         result.add(new MappingWithDirection(pm, true));
       else if (pm.sideB.isAssignableFrom(key.source) && pm.sideA.isAssignableFrom(key.target))
         result.add(new MappingWithDirection(pm, false));
     }
   }
   if (!result.isEmpty()) {
     Collections.sort(result, new MappingComparator(key.target));
   } else if (automappingEnabled) {
     logger.info(
         "Could not find applicable mappings between {} and {}. A mapping will be created using automapping facility",
         key.source.getName(),
         key.target.getName());
     ParsedMapping pm = new Mapping(key.source, key.target, this).automap().parse();
     logger.debug("Automatically created {}", pm);
     mappings.add(pm);
     result.add(new MappingWithDirection(pm, true));
   } else
     logger.warn(
         "Could not find applicable mappings between {} and {}!",
         key.source.getName(),
         key.target.getName());
   return result;
 }
Esempio n. 14
0
  private void removeReceiveStream(ReceiveStreamDesc receiveStream, boolean emptyJB) {
    if (receiveStream.format instanceof VideoFormat) {
      rtpConnector.packetBuffer.disable(receiveStream.ssrc);
      emptyPacketBuffer(receiveStream.ssrc);
    }

    if (receiveStream.dataSink != null) {
      try {
        receiveStream.dataSink.stop();
      } catch (IOException e) {
        logger.error("Failed to stop DataSink " + e);
      }

      receiveStream.dataSink.close();
    }

    if (receiveStream.processor != null) {
      receiveStream.processor.stop();
      receiveStream.processor.close();
    }

    DataSource dataSource = receiveStream.receiveStream.getDataSource();
    if (dataSource != null) {
      try {
        dataSource.stop();
      } catch (IOException ioe) {
        logger.warn("Failed to stop DataSource");
      }
      dataSource.disconnect();
    }

    synchronized (receiveStreams) {
      receiveStreams.remove(receiveStream);
    }
  }
Esempio n. 15
0
  /**
   * 返回响应结果
   *
   * @param response
   * @return
   */
  public static RestResponse returnResponse(
      BaseRestRequest request,
      RestResponse response,
      RestServiceMapping serviceMapping,
      RestServiceConfiguration configuration) {

    String cmd = request.getRestRequest().getCmd();

    // 调用后置拦截器
    List<RestRequestAfterInterceptor> requestAfterInterceptors =
        configuration.getRequestAfterInterceptors();
    for (RestRequestAfterInterceptor requestInterceptor : requestAfterInterceptors) {
      String requestInterceptorName = requestInterceptor.getName();
      logger.debug(
          "REST_AFTER_INTERCEPTOR_START, cmd: {}, name: {}",
          cmd,
          requestInterceptorName + "|" + requestInterceptor.getClass().getName());
      try {
        requestInterceptor.setConfiguration(configuration);
        requestInterceptor.execute(serviceMapping, request, response);
      } catch (Exception e) {
        response.setException(e);
        logger.warn("执行拦截器 {} 失败", requestInterceptorName, e);
      }
      logger.debug(
          "REST_AFTER_INTERCEPTOR_COMPLETE, cmd: {}, name: {}",
          cmd,
          requestInterceptorName + "|" + requestInterceptor.getClass().getName());
    }
    return response;
  }
Esempio n. 16
0
  /**
   * Process candidates received.
   *
   * @param sessionInitIQ The {@link SessionIQ} that created the session we are handling here
   */
  public void processCandidates(SessionIQ sessionInitIQ) {
    Collection<PacketExtension> extensions = sessionInitIQ.getExtensions();
    List<GTalkCandidatePacketExtension> candidates = new ArrayList<GTalkCandidatePacketExtension>();

    for (PacketExtension ext : extensions) {
      if (ext.getElementName().equalsIgnoreCase(GTalkCandidatePacketExtension.ELEMENT_NAME)) {
        GTalkCandidatePacketExtension cand = (GTalkCandidatePacketExtension) ext;
        candidates.add(cand);
      }
    }

    try {
      getMediaHandler().processCandidates(candidates);
    } catch (OperationFailedException ofe) {
      logger.warn("Failed to process an incoming candidates", ofe);

      // send an error response
      String reasonText = "Error: " + ofe.getMessage();
      SessionIQ errResp =
          GTalkPacketFactory.createSessionTerminate(
              sessionInitIQ.getTo(),
              sessionInitIQ.getFrom(),
              sessionInitIQ.getID(),
              Reason.GENERAL_ERROR,
              reasonText);

      getMediaHandler().getTransportManager().close();
      setState(CallPeerState.FAILED, reasonText);
      getProtocolProvider().getConnection().sendPacket(errResp);
      return;
    }

    // HACK for FreeSwitch that send accept message before sending
    // candidates
    if (sessAcceptedWithNoCands != null) {
      if (isInitiator()) {
        try {
          answer();
        } catch (OperationFailedException e) {
          logger.info("Failed to answer call (FreeSwitch hack)");
        }
      } else {
        final SessionIQ sess = sessAcceptedWithNoCands;
        sessAcceptedWithNoCands = null;

        // run in another thread to not block smack receive thread and
        // possibly delay others candidates messages.
        new Thread() {
          @Override
          public void run() {
            processSessionAccept(sess);
          }
        }.start();
      }
      sessAcceptedWithNoCands = null;
    }
  }
Esempio n. 17
0
 public final boolean assertEquals(String $label, float $expected, float $actual) {
   if ($expected != $actual) {
     $unitFailures++;
     $log.warn(messageFail($label, $expected, $actual), new AssertionFailed());
     return false;
   }
   $log.debug(messagePass($label, $expected, $actual));
   return true;
 }
Esempio n. 18
0
 public final boolean assertNotSame(String $label, Object $expected, Object $actual) {
   if ($expected == $actual) {
     $unitFailures++;
     $log.warn(messageFailNot($label, $expected, $actual), new AssertionFailed());
     return false;
   }
   $log.debug(messagePassNot($label, $expected, $actual));
   return true;
 }
Esempio n. 19
0
 public final boolean assertEquals(String $label, long $expected, long $actual, long $margin) {
   if (Math.abs($expected - $actual) <= $margin) {
     $unitFailures++;
     $log.warn(messageFail($label, $expected, $actual, $margin), new AssertionFailed());
     return false;
   }
   $log.debug(messagePass($label, $expected, $actual, $margin));
   return true;
 }
  /**
   * Iterate through all the <tt>ReceiveStream</tt>s that this <tt>MediaStream</tt> has and make
   * <tt>RTCPReportBlock</tt>s for all of them.
   *
   * @param time
   * @return
   */
  private RTCPReportBlock[] makeRTCPReportBlocks(long time) {
    MediaStream stream = getStream();
    // State validation.
    if (stream == null) {
      logger.warn("stream is null.");
      return MIN_RTCP_REPORTS_BLOCKS_ARRAY;
    }

    StreamRTPManager streamRTPManager = stream.getStreamRTPManager();
    if (streamRTPManager == null) {
      logger.warn("streamRTPManager is null.");
      return MIN_RTCP_REPORTS_BLOCKS_ARRAY;
    }

    Collection<ReceiveStream> receiveStreams = streamRTPManager.getReceiveStreams();

    if (receiveStreams == null || receiveStreams.size() == 0) {
      logger.info("There are no receive streams to build report " + "blocks for.");
      return MIN_RTCP_REPORTS_BLOCKS_ARRAY;
    }

    SSRCCache cache = streamRTPManager.getSSRCCache();
    if (cache == null) {
      logger.info("cache is null.");
      return MIN_RTCP_REPORTS_BLOCKS_ARRAY;
    }

    // Create the return object.
    Collection<RTCPReportBlock> rtcpReportBlocks = new ArrayList<RTCPReportBlock>();

    // Populate the return object.
    for (ReceiveStream receiveStream : receiveStreams) {
      // Dig into the guts of FMJ and get the stats for the current
      // receiveStream.
      SSRCInfo info = cache.cache.get((int) receiveStream.getSSRC());

      if (!info.ours && info.sender) {
        RTCPReportBlock rtcpReportBlock = info.makeReceiverReport(time);
        rtcpReportBlocks.add(rtcpReportBlock);
      }
    }

    return rtcpReportBlocks.toArray(new RTCPReportBlock[rtcpReportBlocks.size()]);
  }
Esempio n. 21
0
  @Override
  public REDBlock next() {
    if (!hasNext()) {
      throw new NoSuchElementException();
    }

    cntRemainingBlocks--;

    if (buffer == null || buffer.length <= offNextBlockHeader) {
      logger.warn("Prevented an array out of bounds exception.");
      return null;
    }

    byte blockPT = (byte) (buffer[offNextBlockHeader] & 0x7f);

    int blockLen;
    if (hasNext()) {
      if (buffer.length < offNextBlockHeader + 4) {
        logger.warn("Prevented an array out of bounds exception.");
        return null;
      }

      // 0                   1                   2                   3
      // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      // |F|   block PT  |  timestamp offset         |   block length    |
      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      blockLen =
          (buffer[offNextBlockHeader + 2] & 0x03) << 8 | (buffer[offNextBlockHeader + 3] & 0xFF);
      offNextBlockHeader += 4; // next RED header
      offNextBlockPayload += blockLen;
    } else {
      // 0 1 2 3 4 5 6 7
      // +-+-+-+-+-+-+-+-+
      // |0|   Block PT  |
      // +-+-+-+-+-+-+-+-+
      blockLen = length - (offNextBlockPayload + 1);
      offNextBlockHeader = -1;
      offNextBlockPayload = -1;
    }

    return new REDBlock(buffer, offNextBlockPayload, blockLen, blockPT);
  }
Esempio n. 22
0
  /**
   * Gets the first RED block in the RED payload.
   *
   * @param buffer the byte buffer that contains the RED payload.
   * @param offset the offset in the buffer where the RED payload begins.
   * @param length the length of the RED payload.
   * @return the primary RED block if it exists, null otherwise.
   */
  public static REDBlock getPrimaryBlock(byte[] buffer, int offset, int length) {
    // Chrome is typically sending RED packets with a single block carrying
    // either VP8 or FEC. This is unusual, and probably wrong as it messes
    // up the sequence numbers and packet loss computations but it's just
    // the way it is. Here we detect this situation and avoid looping
    // through the blocks if there is a single block.
    if (isMultiBlock(buffer, offset, length)) {
      REDBlock block = null;
      REDBlockIterator redBlockIterator = new REDBlockIterator(buffer, offset, length);
      while (redBlockIterator.hasNext()) {
        block = redBlockIterator.next();
      }

      if (block == null) {
        logger.warn("No primary block found.");
      }

      return block;
    } else {
      if (buffer == null || offset < 0 || length < 0 || buffer.length < offset + length) {
        logger.warn(
            "Prevented an array out of bounds exception: "
                + "buffer length: "
                + buffer.length
                + ", offset: "
                + offset
                + ", len: "
                + length);
        return null;
      }

      byte blockPT = (byte) (buffer[offset] & 0x7f);
      int blockOff = offset + 1; // + 1 for the primary block header.
      int blockLen = length - blockOff;

      if (buffer.length < blockOff + blockLen) {
        logger.warn("Primary block doesn't fit in RED packet.");
        return null;
      }

      return new REDBlock(buffer, blockOff, blockLen, blockPT);
    }
  }
  /**
   * Updates the configuration from the filter config.
   *
   * @param filterConfig
   */
  @SuppressWarnings("unchecked")
  public void updateConfigration(FilterConfig filterConfig) {
    Enumeration<String> paramEnum = filterConfig.getInitParameterNames();
    while (paramEnum.hasMoreElements()) {
      String paramName = paramEnum.nextElement();
      if (paramName.startsWith("r")) {
        try {
          if (!runOptions.containsKey(paramName)) throw new Exception("Invalid Parameter Name");
          runOptions.put(paramName, Boolean.parseBoolean(filterConfig.getInitParameter(paramName)));
        } catch (Exception e) {
          log.warn("Init Parameter [" + paramName + "] is invalid or could not be set.", e);
        }
      } else if (paramName.startsWith("b")) {
        try {
          if (!batchOptions.containsKey(paramName)) throw new Exception("Invalid Parameter Name");
          batchOptions.put(paramName, Integer.parseInt(filterConfig.getInitParameter(paramName)));
        } catch (Exception e) {
          log.warn("Init Parameter [" + paramName + "] is invalid or could not be set.", e);
        }
      } else if (paramName.startsWith("p")) {
        try {
          if (!parameterNames.containsKey(paramName)) throw new Exception("Invalid Parameter Name");
          parameterNames.put(paramName, filterConfig.getInitParameter(paramName));
        } catch (Exception e) {
          log.warn("Init Parameter [" + paramName + "] is invalid or could not be set.", e);
        }
      } else if ("listenerClassName".equals(paramName)) {
        listenerClassName = filterConfig.getInitParameter(paramName);
      } else if ("agentLogLevel".equals(paramName)) {
        try {
          agentLogLevel = Integer.parseInt(filterConfig.getInitParameter(paramName));
        } catch (Exception e) {
          log.warn("Agent Log Level Could Not Be Set. Defaulting to [" + agentLogLevel + "].", e);
        }

      } else {
        log.warn("Init Parameter [" + paramName + "] was not recognized.");
      }
    }
    log.info("Completed AjaxMetrics Filter Configuration. Config is:\n" + toString());
    inited = true;
  }
 /**
  * Checks whether the carbon is supported by the server or not.
  *
  * @return <tt>true</tt> if carbon is supported by the server and <tt>false</tt> if not.
  */
 private boolean isCarbonSupported() {
   try {
     return jabberProvider
         .getDiscoveryManager()
         .discoverInfo(jabberProvider.getAccountID().getService())
         .containsFeature(CarbonPacketExtension.NAMESPACE);
   } catch (XMPPException e) {
     logger.warn("Failed to retrieve carbon support." + e.getMessage());
   }
   return false;
 }
Esempio n. 25
0
 @Override
 public boolean inIndex(String identifier) {
   CloseableIterator<JdbcEntry> i = getSqlCursor(getFindSql(identifier));
   boolean result = i.hasNext();
   try {
     i.close();
   } catch (IOException ex) {
     log.warn(ex);
   }
   return result;
 }
Esempio n. 26
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. 27
0
 protected void addOrReplace(ParsedMapping parsedMapping) {
   MappingKey key = new MappingKey(parsedMapping);
   for (int i = 0; i < mappings.size(); i++) {
     if (key.equals(new MappingKey(mappings.get(i)))) {
       logger.warn("{}\nis replaced with\n{}", mappings.get(i), parsedMapping);
       mappings.set(i, parsedMapping);
       return;
     }
   }
   logger.debug("Parsed {}", parsedMapping);
   mappings.add(parsedMapping);
 }
Esempio n. 28
0
  protected static void recordToErrorCounter(String cmd) {

    String today = DateUtil.format(new Date(), "yyyyMMdd");
    try {

      RedisUtil.incr(ERROR_COUNT_KEY + today);

    } catch (Exception e) {

      logger.warn("记录api返回错误请求的次数失败, today: {}", today, e);
    }

    try {

      RedisUtil.incr(ERROR_COUNT_KEY + today + ":cmd:" + cmd);

    } catch (Exception e) {

      logger.warn("记录cmd: {}, today: {} 返回错误请求的次数失败", cmd, today, e);
    }
  }
Esempio n. 29
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);
     }
   }
 }
  /**
   * Creates an account for the given user and password.
   *
   * @param providerFactory the ProtocolProviderFactory which will create the account
   * @param user the user identifier
   * @return the <tt>ProtocolProviderService</tt> for the new account.
   */
  public ProtocolProviderService installAccount(
      ProtocolProviderFactory providerFactory, String user) throws OperationFailedException {
    Hashtable<String, String> accountProperties = new Hashtable<String, String>();

    accountProperties.put(
        ProtocolProviderFactory.ACCOUNT_ICON_PATH,
        "resources/images/protocol/gibberish/gibberish32x32.png");

    if (registration.isRememberPassword()) {
      accountProperties.put(ProtocolProviderFactory.PASSWORD, registration.getPassword());
    }

    if (isModification()) {
      providerFactory.uninstallAccount(protocolProvider.getAccountID());
      this.protocolProvider = null;
      setModification(false);
    }

    try {
      AccountID accountID = providerFactory.installAccount(user, accountProperties);

      ServiceReference serRef = providerFactory.getProviderForAccount(accountID);

      protocolProvider =
          (ProtocolProviderService) GibberishAccRegWizzActivator.bundleContext.getService(serRef);
    } catch (IllegalStateException exc) {
      logger.warn(exc.getMessage());

      throw new OperationFailedException(
          "Account already exists.", OperationFailedException.IDENTIFICATION_CONFLICT);
    } catch (Exception exc) {
      logger.warn(exc.getMessage());

      throw new OperationFailedException(
          "Failed to add account", OperationFailedException.GENERAL_ERROR);
    }

    return protocolProvider;
  }