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

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

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

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

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

    return true;
  }
Beispiel #3
0
  /**
   * Jirecon packets processing logic.
   *
   * <p>{@inheritDoc}
   */
  @Override
  public void processPacket(Packet packet) {
    JireconIq recording = (JireconIq) packet;

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

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

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

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

      if (status == JireconIq.Status.STOPPED) {
        logger.info("Recording STOPPED: " + recordingId);
        recordingId = null;
      }
    } else {
      logger.info("Ignored status change: " + recording.toXML());
    }
  }
  @Path("devices/{deviceLibraryIdentifier}/registrations/{passTypeIdentifier}/{serialNumber}")
  @DELETE
  public Response unregisterDevice(
      @PathParam("deviceLibraryIdentifier") String deviceLibraryIdentifier,
      @PathParam("passTypeIdentifier") String passTypeIdentifier,
      @PathParam("serialNumber") String serialNumber,
      @HeaderParam("Authorization") @DefaultValue("") String authorization) {

    PassDAO pass = new PassDAO(passTypeIdentifier, serialNumber);
    if (!pass.retrieve()) {
      // pass not found
      // response is UNAUTHORIZED in order to prevent trial/error/guessing for passes
      log.warn("pass does not exist: {}", serialNumber);
      return Response.status(Response.Status.UNAUTHORIZED).build();
    }

    if (!AuthUtil.isAuthorized(authorization, pass.getAuthenticationToken())) {
      log.warn("invalid authorization: {}", authorization);
      return Response.status(Response.Status.UNAUTHORIZED).build();
    }

    DeviceDAO device = new DeviceDAO(deviceLibraryIdentifier);
    if (device.retrieve()) {
      device.removeRegistration(passTypeIdentifier, serialNumber);
      if (device.store()) {
        return Response.status(Response.Status.OK).build();
      } else {
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
      }
    }
    return Response.status(Response.Status.NOT_FOUND).build();
  }
Beispiel #5
0
 public static int parseInt(Object obj)
 {
     if(obj == null)
     {
         Logger.warn(jp/co/cyberagent/adteck/lib/MathUtil, "parseInt", "object is null.", new Object[0]);
         return 0;
     }
     if(obj instanceof Integer)
         return ((Integer)obj).intValue();
     if(obj instanceof String)
     {
         int i;
         try
         {
             i = Integer.valueOf((String)obj).intValue();
         }
         // Misplaced declaration of an exception variable
         catch(Object obj)
         {
             return 0;
         }
         return i;
     } else
     {
         Logger.warn(jp/co/cyberagent/adteck/lib/MathUtil, "parseInt", "object is neither Integer nor String.", new Object[0]);
         return parseInt((String)obj);
     }
 }
  /**
   * 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());
  }
  /**
   * 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;
  }
Beispiel #8
0
 @Test
 // TODO can we add assertions here?
 public void t03_TestStandardLogger() throws FileSystemException, ReadWriteException {
   Logger logger = new Logger(System.out);
   logger.info("this is a trace message");
   logger.warn("this is a warning");
   logger.warn("this is a warning", getException(1));
   logger.error("this is an error", getException(1));
   logger.error(getException(1));
 }
  /**
   * 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;
  }
Beispiel #10
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;
  }
Beispiel #11
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);
    }
  }
Beispiel #12
0
  /**
   * Take a JSON object corresponding to the 'engines' field for the provided engine name, updating
   * {@link #syncIDs} and {@link #versions} accordingly.
   *
   * <p>If the record is malformed, an entry is added to {@link #exceptions}, to be rethrown during
   * validation.
   */
  protected void recordEngineState(String engineName, ExtendedJSONObject engineEntry) {
    if (engineEntry == null) {
      throw new IllegalArgumentException("engineEntry cannot be null.");
    }

    // Record syncID first, so that engines with bad versions are recorded.
    try {
      String syncID = engineEntry.getString("syncID");
      if (syncID == null) {
        Logger.warn(LOG_TAG, "No syncID for " + engineName + ". Recording exception.");
        exceptions.put(engineName, new MetaGlobalMalformedSyncIDException());
      }
      syncIDs.put(engineName, syncID);
    } catch (ClassCastException e) {
      // Malformed syncID on the server. Wipe the server.
      Logger.warn(
          LOG_TAG,
          "Malformed syncID "
              + engineEntry.get("syncID")
              + " for "
              + engineName
              + ". Recording exception.");
      exceptions.put(engineName, new MetaGlobalMalformedSyncIDException());
    }

    try {
      Integer version = engineEntry.getIntegerSafely("version");
      Logger.trace(LOG_TAG, "Engine " + engineName + " has server version " + version);
      if (version == null || version.intValue() == 0) {
        // Invalid version. Wipe the server.
        Logger.warn(
            LOG_TAG,
            "Malformed version " + version + " for " + engineName + ". Recording exception.");
        exceptions.put(engineName, new MetaGlobalMalformedVersionException());
        return;
      }
      versions.put(engineName, version);
    } catch (NumberFormatException e) {
      // Invalid version. Wipe the server.
      Logger.warn(
          LOG_TAG,
          "Malformed version "
              + engineEntry.get("version")
              + " for "
              + engineName
              + ". Recording exception.");
      exceptions.put(engineName, new MetaGlobalMalformedVersionException());
      return;
    }
  }
Beispiel #13
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;
  }
        /** {@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;
        }
Beispiel #15
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);
    }
  }
Beispiel #16
0
    /**
     * if initialtoken was specified, use that (split on comma).
     * otherwise, if num_tokens == 1, pick a token to assume half the load of the most-loaded node.
     * else choose num_tokens tokens at random
     */
    public static Collection<Token> getBootstrapTokens(final TokenMetadata metadata) throws ConfigurationException
    {
        Collection<String> initialTokens = DatabaseDescriptor.getInitialTokens();
        // if user specified tokens, use those
        if (initialTokens.size() > 0)
        {
            logger.debug("tokens manually specified as {}",  initialTokens);
            List<Token> tokens = new ArrayList<Token>(initialTokens.size());
            for (String tokenString : initialTokens)
            {
                Token token = StorageService.getPartitioner().getTokenFactory().fromString(tokenString);
                if (metadata.getEndpoint(token) != null)
                    throw new ConfigurationException("Bootstrapping to existing token " + tokenString + " is not allowed (decommission/removenode the old node first).");
                tokens.add(token);
            }
            return tokens;
        }

        int numTokens = DatabaseDescriptor.getNumTokens();
        if (numTokens < 1)
            throw new ConfigurationException("num_tokens must be >= 1");

        if (numTokens == 1)
            logger.warn("Picking random token for a single vnode.  You should probably add more vnodes; failing that, you should probably specify the token manually");

        return getRandomTokens(metadata, numTokens);
    }
Beispiel #17
0
  @Test
  public void routesLogMessagesViaSlf4j() {
    Logger logger = Logging.getLogger(LoggingTest.class);

    expectLogMessage(LogLevel.DEBUG, "debug");
    logger.debug("debug");

    expectLogMessage(LogLevel.INFO, "info");
    logger.info("info");

    expectLogMessage(LogLevel.WARN, "warn");
    logger.warn("warn");

    expectLogMessage(LogLevel.LIFECYCLE, "lifecycle");
    logger.lifecycle("lifecycle");

    expectLogMessage(LogLevel.ERROR, "error");
    logger.error("error");

    expectLogMessage(LogLevel.QUIET, "quiet");
    logger.quiet("quiet");

    expectLogMessage(LogLevel.LIFECYCLE, "lifecycle via level");
    logger.log(LogLevel.LIFECYCLE, "lifecycle via level");
  }
Beispiel #18
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);
 }
  /**
   * 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();
  }
  @Test
  public void testLevels() throws Exception {
    FileLoggerMock mockFileLogger = setFileLoggerInstanceField(activity);
    LogPersister.setContext(activity);
    Logger logger = Logger.getLogger("package");
    LogPersister.storeLogs(true);

    final String hi = "hi";

    // no calls should create a file:

    LogPersister.setLogLevel(LEVEL.ERROR);
    logger.warn(hi);
    waitForNotify(logger);
    logger.info(hi);
    waitForNotify(logger);
    logger.debug(hi);
    waitForNotify(logger);

    LogPersister.setLogLevel(LEVEL.WARN);
    logger.info(hi);
    waitForNotify(logger);
    logger.debug(hi);
    waitForNotify(logger);

    LogPersister.setLogLevel(LEVEL.INFO);
    logger.debug(hi);
    waitForNotify(logger);

    // "hi" should not appear in the file

    assertEquals(0, mockFileLogger.getAccumulatedLogCalls().length());
  }
Beispiel #21
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;
  }
  @Test
  public void testWStringThrowable() throws Exception {
    FileLoggerMock mockFileLogger = setFileLoggerInstanceField(activity);
    LogPersister.setContext(activity);
    LogPersister.setLogLevel(LEVEL.DEBUG);
    Logger logger = Logger.getLogger("package");
    LogPersister.storeLogs(true);

    logger.warn("message", new Exception());

    waitForNotify(logger);

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

    // jsonObject should have a fixed number of key/value pairs
    assertEquals(
        "resulting jsonobject in file has wrong number of key/value pairs", 6, jsonObject.length());
    // verify the key/value pairs
    assertTrue(
        jsonObject.has(TIMESTAMP_KEY)); // don't test the value, as it may differ from current
    assertEquals("package", jsonObject.get(PACKAGE_KEY));
    // ERROR
    assertEquals("WARN", jsonObject.get(LEVEL_KEY));
    assertEquals("message", jsonObject.get(MESSAGE_KEY));
    // ensure no exception is thrown by parsing the threadid value:
    assertFalse(jsonObject.getLong(THREADID_KEY) == 0);
  }
Beispiel #23
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;
 }
Beispiel #24
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;
 }
  protected void error(Throwable error) {
    LOG.warn("Got exception: " + error.toString(), error);

    if (error.toString().contains("Rescan")) {
      new ErrorDialog(activity, error.toString(), false);
    } else {
      new ErrorDialog(activity, error.toString(), true);
    }
  }
  /**
   * 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;
    }
  }
Beispiel #27
0
  /**
   * decode palette from the input stream
   *
   * @param pic SubPicture object containing info about the current caption
   * @return
   * @throws CoreException
   */
  private Palette decodePalette(SubPictureBD pic) throws CoreException {
    boolean fadeOut = false;
    int paletteIndex;
    List<PaletteInfo> paletteInfos = pic.getPalettes().get(pic.getImageObject().getPaletteID());
    if (paletteInfos == null) {
      throw new CoreException("Palette ID out of bounds.");
    }

    Palette palette = new Palette(256, Core.usesBT601());
    // by definition, index 0xff is always completely transparent
    // also all entries must be fully transparent after initialization

    try {
      for (PaletteInfo paletteInfo : paletteInfos) {
        int index = paletteInfo.getPaletteOffset();
        for (int i = 0; i < paletteInfo.getPaletteSize(); i++) {
          // each palette entry consists of 5 bytes
          paletteIndex = buffer.getByte(index);
          int y = buffer.getByte(++index);
          int cr, cb;
          if (configuration.isSwapCrCb()) {
            cb = buffer.getByte(++index);
            cr = buffer.getByte(++index);
          } else {
            cr = buffer.getByte(++index);
            cb = buffer.getByte(++index);
          }
          int alpha = buffer.getByte(++index);

          int alphaOld = palette.getAlpha(paletteIndex);
          // avoid fading out
          if (alpha >= alphaOld) {
            if (alpha
                < configuration
                    .getAlphaCrop()) { // to not mess with scaling algorithms, make transparent
                                       // color black
              y = 16;
              cr = 128;
              cb = 128;
            }
            palette.setAlpha(paletteIndex, alpha);
          } else {
            fadeOut = true;
          }

          palette.setYCbCr(paletteIndex, y, cb, cr);
          index++;
        }
      }
      if (fadeOut) {
        logger.warn("fade out detected -> patched palette\n");
      }
      return palette;
    } catch (FileBufferException ex) {
      throw new CoreException(ex.getMessage());
    }
  }
Beispiel #28
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;
 }
Beispiel #29
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;
 }
  /**
   * 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);
  }