/**
   * This method reads the contents of a file, and then populates an array with integers inside of
   * it
   *
   * @param inputFile The file being read
   * @param outputArray The array that the numbers will be output to
   */
  public static void readArray(String inputFile, int[] outputArray) {
    boolean flag = false;
    Scanner keyboard = new Scanner(System.in);
    String checkFile = inputFile;
    while (!flag) {

      try {
        DataInputStream inFile = new DataInputStream(new FileInputStream(checkFile));
        for (int i = 0; i < outputArray.length; i++) {
          outputArray[i] = inFile.readInt();
        }
        inFile.close();
        flag = true;
      } catch (EOFException e) {
        System.out.println(e.getMessage());
      } catch (FileNotFoundException e) {
        System.out.println("File not found.");
        System.out.println("Please input the name of the file you'd like to read from: ");
        Scanner checkKeyboard = new Scanner(System.in);
        checkFile = (checkKeyboard.next() + ".dat");
      } catch (IOException e) {
        System.out.println(e.getMessage());
      }
    }
  }
예제 #2
1
  @Override
  protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
      throws ServletException, IOException {
    response.setHeader("Access-Control-Allow-Origin", "*");
    try {
      if (server == null) {
        LOG.error("server in servlet not configured");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentLength(0);
        return;
      }

      ResponderAndRelativeUri r = server.getResponderAndRelativeUri(request);
      if (r == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      }

      if (StringUtil.isNotBlank(r.getRelativeUri())) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      }

      Responder responder = r.getResponder();

      HealthCheckResult healthResult = server.healthCheck(responder);
      if (healthResult.isHealthy()) {
        response.setStatus(HttpServletResponse.SC_OK);
      } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }

      response.setContentType(HealthCheckServlet.CT_RESPONSE);
      byte[] respBytes = healthResult.toJsonMessage(true).getBytes();
      response.setContentLength(respBytes.length);
      response.getOutputStream().write(respBytes);
    } catch (EOFException e) {
      final String message = "connection reset by peer";
      if (LOG.isErrorEnabled()) {
        LOG.warn(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
      }
      LOG.debug(message, e);

      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      response.setContentLength(0);
    } catch (Throwable t) {
      final String message = "Throwable thrown, this should not happen";
      if (LOG.isErrorEnabled()) {
        LOG.error(LogUtil.buildExceptionLogFormat(message), t.getClass().getName(), t.getMessage());
      }
      LOG.debug(message, t);
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      response.setContentLength(0);
    }

    response.flushBuffer();
  } // method doGet
예제 #3
0
  /**
   * This method is Safe replica version of org.apache.http.util.EntityUtils.toByteArray. The try
   * block embedding 'instream.read' has a corresponding catch block for 'EOFException' (that's
   * Ignored) and all other IOExceptions are let pass.
   *
   * @param entity
   * @return byte array containing the entity content. May be empty/null.
   * @throws IOException if an error occurs reading the input stream
   */
  public byte[] toByteArraySafe(final HttpEntity entity) throws IOException {
    if (entity == null) {
      return null;
    }

    InputStream instream = entity.getContent();
    if (instream == null) {
      return new byte[] {};
    }
    Preconditions.checkArgument(
        entity.getContentLength() < Integer.MAX_VALUE,
        "HTTP entity too large to be buffered in memory");

    // The raw data stream (inside JDK) is read in a buffer of size '512'. The original code
    // org.apache.http.util.EntityUtils.toByteArray reads the unzipped data in a buffer of
    // 4096 byte. For any data stream that has a compression ratio lesser than 1/8, this may
    // result in the buffer/array overflow. Increasing the buffer size to '16384'. It's highly
    // unlikely to get data compression ratios lesser than 1/32 (3%).
    final int bufferLength = 16384;
    int i = (int) entity.getContentLength();
    if (i < 0) {
      i = bufferLength;
    }
    ByteArrayBuffer buffer = new ByteArrayBuffer(i);
    try {
      byte[] tmp = new byte[bufferLength];
      int l;
      while ((l = instream.read(tmp)) != -1) {
        buffer.append(tmp, 0, l);
      }
    } catch (EOFException eofe) {
      /**
       * Ref: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4040920 Due to a bug in JDK ZLIB
       * (InflaterInputStream), unexpected EOF error can occur. In such cases, even if the input
       * stream is finished reading, the 'Inflater.finished()' call erroneously returns 'false' and
       * 'java.util.zip.InflaterInputStream.fill' throws the 'EOFException'. So for such case,
       * ignore the Exception in case Exception Cause is 'Unexpected end of ZLIB input stream'.
       *
       * <p>Also, ignore this exception in case the exception has no message body as this is the
       * case where {@link GZIPInputStream#readUByte} throws EOFException with empty message. A bug
       * has been filed with Sun and will be mentioned here once it is accepted.
       */
      if (instream.available() == 0
          && (eofe.getMessage() == null
              || eofe.getMessage().equals("Unexpected end of ZLIB input stream"))) {
        LOG.log(Level.FINE, "EOFException: ", eofe);
      } else {
        throw eofe;
      }
    } finally {
      instream.close();
    }
    return buffer.toByteArray();
  }
 /** Start the thread. Exits when the client has been completely handled. */
 @Override
 public void run() {
   try {
     GELFClientHandlerIF client = null;
     if (GELF.isChunkedMessage(this.receivedGelfSentence)) {
       LOG.info("Received message is chunked. Handling now.");
       client = new ChunkedGELFClientHandler(this.receivedGelfSentence);
     } else {
       LOG.info("Received message is not chunked. Handling now.");
       client = new SimpleGELFClientHandler(this.receivedGelfSentence);
     }
     client.handle();
   } catch (InvalidGELFTypeException e) {
     LOG.error("Invalid GELF type in message: " + e.getMessage(), e);
   } catch (InvalidGELFHeaderException e) {
     LOG.error("Invalid GELF header in message: " + e.getMessage(), e);
   } catch (InvalidGELFCompressionMethodException e) {
     LOG.error("Invalid compression method of GELF message: " + e.getMessage(), e);
   } catch (java.util.zip.DataFormatException e) {
     LOG.error("Invalid compression data format in GELF message: " + e.getMessage(), e);
   } catch (java.io.UnsupportedEncodingException e) {
     LOG.error("Invalid enconding of GELF message: " + e.getMessage(), e);
   } catch (java.io.EOFException e) {
     LOG.error("EOF Exception while handling GELF message: " + e.getMessage(), e);
   } catch (java.net.SocketException e) {
     LOG.error("SocketException while handling GELF message: " + e.getMessage(), e);
   } catch (java.io.IOException e) {
     LOG.error("IO Error while handling GELF message: " + e.getMessage(), e);
   } catch (Exception e) {
     LOG.error("Exception caught while handling GELF message: " + e.getMessage(), e);
   }
 }
 @Override
 public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
     throws IOException, HttpMessageNotReadableException {
   try {
     TumblrResponse tumblrResponse =
         objectMapper.readValue(inputMessage.getBody(), TumblrResponse.class);
     checkResponse(tumblrResponse);
     Object result;
     if (TumblrResponse.class.equals(type)) {
       // don't parse the response json, callee is going to process is manually
       result = tumblrResponse;
     } else {
       // parse the response json into an instance of the given class
       JavaType javaType = getJavaType(type, contextClass);
       String response = tumblrResponse.getResponseJson();
       result = objectMapper.readValue(response, javaType);
     }
     return result;
   } catch (JsonParseException ex) {
     throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
   } catch (EOFException ex) {
     throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
   } catch (Exception e) {
     e.printStackTrace();
     throw new IOException(e);
   }
 }
예제 #6
0
 public static void main(String args[]) {
   int numMsg = Integer.parseInt(args[2]);
   // arguments supply message and hostname of destination
   Socket s = null;
   try {
     int serverPort = 7896;
     s = new Socket(args[1], serverPort);
     PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
     for (int i = 0; i < numMsg; i++) {
       out.println(Integer.toString(i) + " " + args[0]);
       out.flush();
     }
   } catch (UnknownHostException e) {
     System.out.println("Sock:" + e.getMessage());
   } catch (EOFException e) {
     System.out.println("EOF:" + e.getMessage());
   } catch (IOException e) {
     System.out.println("IO:" + e.getMessage());
   } finally {
     if (s != null)
       try {
         s.close();
       } catch (IOException e) {
         System.out.println("close:" + e.getMessage());
       }
   }
 }
  /**
   * Lee un caracter del archivo indicado y lo trasnforma a entero en formato ASCII.
   *
   * @return int entrada
   */
  public int readChar() {
    int entrada = -1;
    try {
      entrada = in.read();
    } catch (EOFException e) {
      System.err.println(e.getMessage());
    } catch (IOException e) {
      System.err.println(e.getMessage());
    }

    return entrada;
  }
    /** @review runSafe OK */
    @Override
    public void run() {
      log.debug(prefix() + "ReceiverThread started.");
      try {
        while (!isInterrupted()) {
          /*
           * TODO: if we implement network view it should return a
           * ProgressMonitor with Util#getRunnableContext(), that we
           * can use here.
           */
          progress = SubMonitor.convert(new NullProgressMonitor());
          progress.beginTask("receive", 100);

          try {
            IncomingTransferObject transferObject =
                channel.receiveIncomingTransferObject(progress.newChild(1));

            listener.addIncomingTransferObject(transferObject);

          } catch (LocalCancellationException e) {
            log.info("Connection was closed by me. ");
            if (progress != null && !progress.isCanceled()) progress.setCanceled(true);
            close();
            return;
          } catch (SocketException e) {
            log.debug(prefix() + "Connection was closed by me. " + e.getMessage());
            close();
            return;
          } catch (EOFException e) {
            e.printStackTrace();

            log.debug(prefix() + "Connection was closed by peer. " + e.getMessage());
            close();
            return;
          } catch (IOException e) {
            log.error(prefix() + "Network IO Exception: " + e.getMessage(), e);

            if (e.getMessage().contains("Socket already disposed")) return;

            close();
            return;
          } catch (ClassNotFoundException e) {
            log.error(prefix() + "Received unexpected object in ReceiveThread", e);
            continue;
          }
        }
      } catch (RuntimeException e) {
        log.error(prefix() + "Internal Error in Receive Thread: ", e);
        // If there is programming problem, close the socket
        close();
      }
    }
예제 #9
0
 @Test
 public void testReadMoreThanInputThrowsEOFException() throws Throwable {
   byte[] bytes = new byte[2];
   FSDMsg fSDMsg = new FSDMsg("testFSDMsgBasePath", "testFSDMsgBaseSchema");
   InputStream is = new ByteArrayInputStream(bytes);
   try {
     fSDMsg.read(is, 100, null, null);
     fail("Expected EOFException to be thrown");
   } catch (EOFException ex) {
     assertNull("ex.getMessage()", ex.getMessage());
     assertEquals("(ByteArrayInputStream) is.available()", 0, is.available());
   }
 }
예제 #10
0
  private MemberModel() {
    // init memberMap
    memberMap = new HashMap<>();
    // init entitledMap (1 to many relation between memberID and BookNumber)
    entitledMap = new HashMap<>();
    boolean readFlag = false;
    ObjectInputStream oin = null;
    Member tm;
    String[] sa = new String[3];
    try {
      oin = new ObjectInputStream(new FileInputStream("members1.dat"));
      readFlag = true;
    } catch (Exception e) {
      e.printStackTrace();
    }
    // read in from file
    while (readFlag) {
      try {
        // Read a member data from inputstream
        // Structure for reading
        // __________________________________________________________
        // |String|String|String|Boolean or Double|ArrayList<String>|
        // ----------------------------------------------------------

        sa[ID_INDEX] = oin.readUTF();
        sa[TITLE_INDEX] = oin.readUTF();
        sa[PHONENO_INDEX] = oin.readUTF();
        if (sa[ID_INDEX].indexOf("STA") != -1) {
          tm = new Staff(sa[ID_INDEX], sa[TITLE_INDEX], sa[PHONENO_INDEX]);
          ((Staff) tm).setBookOverdue(oin.readBoolean());
        } else {
          tm = new Student(sa[ID_INDEX], sa[TITLE_INDEX], sa[PHONENO_INDEX]);
          ((Student) tm).setFinesOwing(oin.readDouble());
        }
        // Raw data map without relationship to book
        memberMap.put(tm.getMemberID(), tm);
        // Map for storing relation
        entitledMap.put(tm.getMemberID(), (ArrayList<String>) oin.readObject());
      } catch (EOFException e) {
        Log.e(e.getMessage());
        readFlag = false;
      } catch (Exception e) {
        Log.e(e.getMessage());
      }
    }
    try {
      oin.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #11
0
 @Test
 public void testReadFieldTypeNullLengthToMuchThrowsEOFException1() throws Throwable {
   FSDMsg fSDMsg = new FSDMsg("testFSDMsgBasePath");
   byte[] bytes = new byte[1];
   InputStream is = new ByteArrayInputStream(bytes);
   try {
     fSDMsg.readField(is, "testFSDMsgFieldName", 100, null, null);
     fail("Expected EOFException to be thrown");
   } catch (EOFException ex) {
     assertNull("ex.getMessage()", ex.getMessage());
     assertEquals("fSDMsg.fields.size()", 0, fSDMsg.fields.size());
     assertEquals("(ByteArrayInputStream) is.available()", 0, is.available());
   }
 }
예제 #12
0
  @Override
  public void process(
      final OperationList ops, final ImageInfo imageInfo, final OutputStream outputStream)
      throws ProcessorException {
    if (!getAvailableOutputFormats().contains(ops.getOutputFormat())) {
      throw new UnsupportedOutputFormatException();
    }

    // will receive stderr output from kdu_expand
    final ByteArrayOutputStream errorBucket = new ByteArrayOutputStream();
    try {
      final ReductionFactor reductionFactor = new ReductionFactor();
      final ProcessBuilder pb = getProcessBuilder(ops, imageInfo.getSize(), reductionFactor);
      logger.info("Invoking {}", StringUtils.join(pb.command(), " "));
      final Process process = pb.start();

      try (final InputStream processInputStream = process.getInputStream();
          final InputStream processErrorStream = process.getErrorStream()) {
        executorService.submit(new StreamCopier(processErrorStream, errorBucket));

        final ImageReader reader =
            new ImageReader(new InputStreamStreamSource(processInputStream), Format.TIF);
        try {
          postProcessUsingJava2d(reader, ops, imageInfo, reductionFactor, outputStream);
          final int code = process.waitFor();
          if (code != 0) {
            logger.warn("kdu_expand returned with code {}", code);
            final String errorStr = errorBucket.toString();
            if (errorStr != null && errorStr.length() > 0) {
              throw new ProcessorException(errorStr);
            }
          }
        } finally {
          reader.dispose();
        }
      } finally {
        process.destroy();
      }
    } catch (EOFException e) {
      // This will generally not have a message.
      logger.error("process(): EOFException ({})", e.getMessage(), ops);
    } catch (IOException | InterruptedException e) {
      String msg = e.getMessage();
      final String errorStr = errorBucket.toString();
      if (errorStr != null && errorStr.length() > 0) {
        msg += " (command output: " + errorStr + ")";
      }
      throw new ProcessorException(msg, e);
    }
  }
예제 #13
0
 public Tuple getNext() throws NoSuchElementException, TransactionAbortedException {
   try {
     Tuple tuple = new Tuple(td);
     for (int i = 0; i < td.numFields(); i++) {
       IntField intf = IntField.createIntField(in.readInt());
       tuple.setField(i, intf);
     }
     return tuple;
   } catch (EOFException eof) {
     throw new NoSuchElementException(eof.getMessage());
   } catch (Exception e) {
     e.printStackTrace();
     BufferPool.Instance().abortTransaction(tid);
     closeConnection();
     throw new TransactionAbortedException(e);
   }
 }
예제 #14
0
  @Override
  public void run() {
    try {
      Object object = input.readObject();
      System.out.println(
          "Enviando " + object + " para " + clientSocket.getInetAddress().getCanonicalHostName());
      output.writeObject(object);
    } catch (EOFException e) {
      System.out.println("EOF:" + e.getMessage());
    } catch (IOException e) {
      System.out.println("IO:" + e.getMessage());
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {
        clientSocket.close();
      } catch (IOException e) {

      }
    }
  }
  @Test
  public void shouldThrowEOFExceptionWhenReadingSingleTab() {
    // given
    JsonReader reader = new JsonReader(new StringReader("\t"));
    CoverageJsonReader coverageReader = new CoverageJsonReader(reader);

    // when
    try {
      coverageReader.endReading();
    } catch (EOFException e) {
      // then
      assertThat(e.getMessage(), equalTo("End of input at line 1 column 2"));
      return;
    } catch (IOException e) {
      // or, then
      e.printStackTrace();
      fail("Did not expect IOException");
      return;
    }

    // or, then
    fail("Expected an EOFException to be thrown");
  }
      @Override
      public void run() {
        try {
          if (connectionCallback != null) {
            connectionCallback.onPublisherBoltConnect();
          }
          BufferedInputStream in = new BufferedInputStream(connectionSocket.getInputStream());
          while (true) {

            byte[] streamNameByteSize = loadData(in, new byte[4]);
            ByteBuffer sizeBuf = ByteBuffer.wrap(streamNameByteSize);
            int streamNameSize = sizeBuf.getInt();
            if (streamNameSize == TCPEventPublisher.PING_HEADER_VALUE) {
              continue;
            }
            byte[] streamNameData = loadData(in, new byte[streamNameSize]);
            String streamId = new String(streamNameData, 0, streamNameData.length);
            StreamRuntimeInfo streamRuntimeInfo = streamRuntimeInfoMap.get(streamId);
            while (streamRuntimeInfo == null) {
              Thread.sleep(1000);
              log.warn(
                  "TCP server on port :'"
                      + tcpEventServerConfig.getPort()
                      + "' waiting for streamId:'"
                      + streamId
                      + "' to process incoming events");
              streamRuntimeInfo = streamRuntimeInfoMap.get(streamId);
            }
            Object[] eventData = new Object[streamRuntimeInfo.getNoOfAttributes()];
            byte[] fixedMessageData =
                loadData(in, new byte[8 + streamRuntimeInfo.getFixedMessageSize()]);

            ByteBuffer bbuf = ByteBuffer.wrap(fixedMessageData, 0, fixedMessageData.length);
            long timestamp = bbuf.getLong();

            List<Integer> stringValueSizes = new ArrayList<>();
            Attribute.Type[] attributeTypes = streamRuntimeInfo.getAttributeTypes();
            for (int i = 0; i < attributeTypes.length; i++) {
              Attribute.Type type = attributeTypes[i];
              switch (type) {
                case INT:
                  eventData[i] = bbuf.getInt();
                  continue;
                case LONG:
                  eventData[i] = bbuf.getLong();
                  continue;
                case BOOL:
                  eventData[i] = bbuf.get() == 1;
                  continue;
                case FLOAT:
                  eventData[i] = bbuf.getFloat();
                  continue;
                case DOUBLE:
                  eventData[i] = bbuf.getDouble();
                  continue;
                case STRING:
                  int size = bbuf.getInt();
                  stringValueSizes.add(size);
              }
            }

            int stringSizePosition = 0;
            for (int i = 0; i < attributeTypes.length; i++) {
              Attribute.Type type = attributeTypes[i];
              if (Attribute.Type.STRING == type) {
                byte[] stringData =
                    loadData(in, new byte[stringValueSizes.get(stringSizePosition)]);
                stringSizePosition++;
                eventData[i] = new String(stringData, 0, stringData.length);
              }
            }
            streamCallback.receive(streamId, timestamp, eventData);
          }
        } catch (EOFException e) {
          log.info("Closing listener socket. " + e.getMessage());
        } catch (IOException e) {
          log.error("Error reading data from receiver socket:" + e.getMessage(), e);
        } catch (Throwable t) {
          log.error("Error :" + t.getMessage(), t);
        } finally {
          if (connectionCallback != null) {
            connectionCallback.onPublisherBoltDisconnect();
          }
        }
      }
예제 #17
0
  private void processRequest(
      final HttpServletRequest request,
      final HttpServletResponse response,
      final ResponderAndRelativeUri r,
      final boolean getMethod)
      throws ServletException, IOException {
    Responder responder = r.getResponder();
    AuditEvent auditEvent = null;

    AuditLevel auditLevel = AuditLevel.INFO;
    AuditStatus auditStatus = AuditStatus.SUCCESSFUL;
    String auditMessage = null;

    long start = 0;

    AuditService auditService =
        (auditServiceRegister == null) ? null : auditServiceRegister.getAuditService();

    if (auditService != null && responder.getAuditOption() != null) {
      start = System.currentTimeMillis();
      auditEvent = new AuditEvent(new Date());
      auditEvent.setApplicationName("OCSP");
      auditEvent.setName("PERF");
    }

    try {
      if (server == null) {
        String message = "responder in servlet not configured";
        LOG.error(message);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentLength(0);

        auditLevel = AuditLevel.ERROR;
        auditStatus = AuditStatus.FAILED;
        auditMessage = message;
        return;
      }

      InputStream requestStream;
      if (getMethod) {
        String relativeUri = r.getRelativeUri();

        // RFC2560 A.1.1 specifies that request longer than 255 bytes SHOULD be sent by
        // POST, we support GET for longer requests anyway.
        if (relativeUri.length() > responder.getRequestOption().getMaxRequestSize()) {
          response.setContentLength(0);
          response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);

          auditStatus = AuditStatus.FAILED;
          auditMessage = "request too large";
          return;
        }

        requestStream = new ByteArrayInputStream(Base64.decode(relativeUri));
      } else {
        // accept only "application/ocsp-request" as content type
        if (!CT_REQUEST.equalsIgnoreCase(request.getContentType())) {
          response.setContentLength(0);
          response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);

          auditStatus = AuditStatus.FAILED;
          auditMessage = "unsupporte media type " + request.getContentType();
          return;
        }

        // request too long
        if (request.getContentLength() > responder.getRequestOption().getMaxRequestSize()) {
          response.setContentLength(0);
          response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);

          auditStatus = AuditStatus.FAILED;
          auditMessage = "request too large";
          return;
        } // if (CT_REQUEST)

        requestStream = request.getInputStream();
      } // end if (getMethod)

      OCSPRequest ocspRequest;
      try {
        ASN1StreamParser parser = new ASN1StreamParser(requestStream);
        ocspRequest = OCSPRequest.getInstance(parser.readObject());
      } catch (Exception e) {
        response.setContentLength(0);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

        auditStatus = AuditStatus.FAILED;
        auditMessage = "bad request";

        final String message = "could not parse the request (OCSPRequest)";
        if (LOG.isErrorEnabled()) {
          LOG.error(
              LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
        }
        LOG.debug(message, e);

        return;
      }

      OCSPReq ocspReq = new OCSPReq(ocspRequest);

      response.setContentType(HttpOcspServlet.CT_RESPONSE);

      OcspRespWithCacheInfo ocspRespWithCacheInfo =
          server.answer(responder, ocspReq, auditEvent, getMethod);
      if (ocspRespWithCacheInfo == null) {
        auditMessage = "processRequest returned null, this should not happen";
        LOG.error(auditMessage);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentLength(0);

        auditLevel = AuditLevel.ERROR;
        auditStatus = AuditStatus.FAILED;
      } else {
        OCSPResp resp = ocspRespWithCacheInfo.getResponse();
        byte[] encodedOcspResp = null;
        response.setStatus(HttpServletResponse.SC_OK);

        ResponseCacheInfo cacheInfo = ocspRespWithCacheInfo.getCacheInfo();
        if (getMethod && cacheInfo != null) {
          encodedOcspResp = resp.getEncoded();
          long now = System.currentTimeMillis();
          // RFC 5019 6.2: Date: The date and time at which the OCSP server generated
          // the HTTP response.
          response.setDateHeader("Date", now);
          // RFC 5019 6.2: Last-Modified: date and time at which the OCSP responder
          // last modified the response.
          response.setDateHeader("Last-Modified", cacheInfo.getThisUpdate());
          // RFC 5019 6.2: Expires: This date and time will be the same as the
          // nextUpdate time-stamp in the OCSP
          // response itself.
          // This is overridden by max-age on HTTP/1.1 compatible components
          if (cacheInfo.getNextUpdate() != null) {
            response.setDateHeader("Expires", cacheInfo.getNextUpdate());
          }
          // RFC 5019 6.2: This profile RECOMMENDS that the ETag value be the ASCII
          // HEX representation of the SHA1 hash of the OCSPResponse structure.
          response.setHeader(
              "ETag",
              new StringBuilder(42)
                  .append('\\')
                  .append(HashCalculator.hexSha1(encodedOcspResp))
                  .append('\\')
                  .toString());

          // Max age must be in seconds in the cache-control header
          long maxAge;
          if (responder.getResponseOption().getCacheMaxAge() != null) {
            maxAge = responder.getResponseOption().getCacheMaxAge().longValue();
          } else {
            maxAge = OcspServer.defaultCacheMaxAge;
          }

          if (cacheInfo.getNextUpdate() != null) {
            maxAge =
                Math.min(maxAge, (cacheInfo.getNextUpdate() - cacheInfo.getThisUpdate()) / 1000);
          }

          response.setHeader(
              "Cache-Control",
              new StringBuilder(55)
                  .append("max-age=")
                  .append(maxAge)
                  .append(",public,no-transform,must-revalidate")
                  .toString());
        } // end if (getMethod && cacheInfo != null)

        if (encodedOcspResp != null) {
          response.getOutputStream().write(encodedOcspResp);
        } else {
          ASN1OutputStream asn1Out = new ASN1OutputStream(response.getOutputStream());
          asn1Out.writeObject(resp.toASN1Structure());
          asn1Out.flush();
        }
      } // end if (ocspRespWithCacheInfo)
    } catch (EOFException e) {
      final String message = "Connection reset by peer";
      if (LOG.isErrorEnabled()) {
        LOG.warn(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
      }
      LOG.debug(message, e);

      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      response.setContentLength(0);
    } catch (Throwable t) {
      final String message = "Throwable thrown, this should not happen!";
      LOG.error(message, t);

      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      response.setContentLength(0);

      auditLevel = AuditLevel.ERROR;
      auditStatus = AuditStatus.FAILED;
      auditMessage = "internal error";
    } finally {
      try {
        response.flushBuffer();
      } finally {
        if (auditEvent != null) {
          if (auditLevel != null) {
            auditEvent.setLevel(auditLevel);
          }

          if (auditStatus != null) {
            auditEvent.setStatus(auditStatus);
          }

          if (auditMessage != null) {
            auditEvent.addEventData(new AuditEventData("message", auditMessage));
          }

          auditEvent.setDuration(System.currentTimeMillis() - start);

          if (!auditEvent.containsChildAuditEvents()) {
            auditService.logEvent(auditEvent);
          } else {
            List<AuditEvent> expandedAuditEvents = auditEvent.expandAuditEvents();
            for (AuditEvent event : expandedAuditEvents) {
              auditService.logEvent(event);
            }
          }
        } // end if (auditEvent != null)
      } // end inner try
    } // end external try
  } // method processRequest
예제 #18
0
 /**
  * Reads a MIDI track chunk
  *
  * @param DataInputStream dis - the input stream to read from
  * @exception IOException
  */
 private void readTrackChunk(DataInputStream dis) throws IOException {
   // local variables for Track class
   Track track = new Track();
   // Insert new Track into a list of tracks
   this.trackList.addElement(track);
   int deltaTime = 0;
   // Read track header
   if (dis.readInt() != 0x4D54726B) { // If MTrk read is wrong
     throw new IOException("Track started in wrong place!!!!  ABORTING");
   } else { // If MTrk read ok get bytesRemaining
     dis.readInt();
   }
   // loop variables
   int status, oldStatus = 0, eventLength = 0;
   // Start gathering event data
   Event event = null;
   while (true) {
     try {
       // get variable length timestamp
       deltaTime = MidiUtil.readVarLength(dis);
       // mark stream so we can return if we need running status
       dis.mark(2);
       status = dis.readUnsignedByte();
       // decide on running status
       if (status < 0x80) { // set running status
         status = oldStatus;
         // return stream to before status read
         dis.reset();
       }
       // create default event of correct type
       if (status >= 0xFF) { // Meta Event
         int type = dis.readUnsignedByte();
         eventLength = MidiUtil.readVarLength(dis);
         event = jm.midi.MidiUtil.createMetaEvent(type);
       } else if (status >= 0xF0) { // System Exclusive --- NOT
         // SUPPORTED
         eventLength = MidiUtil.readVarLength(dis);
       } else if (status >= 0x80) { // MIDI voice event
         short selection = (short) (status / 0x10);
         short midiChannel = (short) (status - (selection * 0x10));
         VoiceEvt evt = (VoiceEvt) MidiUtil.createVoiceEvent(selection);
         if (evt == null) {
           throw new IOException("MIDI file read error: invalid voice event type!");
         }
         evt.setMidiChannel(midiChannel);
         event = evt;
       }
       oldStatus = status;
     } catch (EOFException ex) {
       logger.warn("EOFException (" + ex.getMessage() + ") encountered in SMFTools");
     } catch (Exception e) {
       throw new IllegalStateException(e);
     }
     if (event != null) {
       // read data into the new event and
       // add the new event to the Track object
       event.setTime(deltaTime);
       event.read(dis);
       track.addEvent(event);
       // event.print();
       if (event instanceof EndTrack) break;
     } else {
       // skip the stream ahead to next valid event
       dis.skipBytes(eventLength);
     }
   }
 }
예제 #19
0
  public HTTPStatus request(
      String method,
      String path,
      HTTPHeader header,
      InputStream body,
      int ok1,
      int ok2,
      OutputStream dst,
      DefaultHandler handler,
      SVNErrorMessage context)
      throws SVNException {
    if ("".equals(path) || path == null) {
      path = "/";
    }

    // 1. prompt for ssl client cert if needed, if cancelled - throw cancellation exception.
    HTTPSSLKeyManager keyManager =
        myKeyManager == null && myRepository.getAuthenticationManager() != null
            ? createKeyManager()
            : myKeyManager;
    TrustManager trustManager =
        myTrustManager == null && myRepository.getAuthenticationManager() != null
            ? myRepository.getAuthenticationManager().getTrustManager(myRepository.getLocation())
            : myTrustManager;

    String sslRealm =
        "<" + myHost.getProtocol() + "://" + myHost.getHost() + ":" + myHost.getPort() + ">";
    SVNAuthentication httpAuth = myLastValidAuth;
    boolean isAuthForced =
        myRepository.getAuthenticationManager() != null
            ? myRepository.getAuthenticationManager().isAuthenticationForced()
            : false;
    if (httpAuth == null && isAuthForced) {
      httpAuth =
          myRepository
              .getAuthenticationManager()
              .getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, sslRealm, null);
      myChallengeCredentials =
          new HTTPBasicAuthentication((SVNPasswordAuthentication) httpAuth, myCharset);
    }
    String realm = null;

    // 2. create request instance.
    HTTPRequest request = new HTTPRequest(myCharset);
    request.setConnection(this);
    request.setKeepAlive(true);
    request.setRequestBody(body);
    request.setResponseHandler(handler);
    request.setResponseStream(dst);

    SVNErrorMessage err = null;
    boolean ntlmAuthIsRequired = false;
    boolean ntlmProxyAuthIsRequired = false;
    boolean negoAuthIsRequired = false;
    int authAttempts = 0;
    while (true) {
      HTTPStatus status = null;
      if (System.currentTimeMillis() >= myNextRequestTimeout) {
        SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "Keep-Alive timeout detected");
        close();
      }
      int retryCount = 1;
      try {
        err = null;
        String httpAuthResponse = null;
        String proxyAuthResponse = null;
        while (retryCount >= 0) {
          connect(keyManager, trustManager);
          request.reset();
          request.setProxied(myIsProxied);
          request.setSecured(myIsSecured);
          if (myProxyAuthentication != null
              && (ntlmProxyAuthIsRequired
                  || !"NTLM".equals(myProxyAuthentication.getAuthenticationScheme()))) {
            if (proxyAuthResponse == null) {
              request.initCredentials(myProxyAuthentication, method, path);
              proxyAuthResponse = myProxyAuthentication.authenticate();
            }
            request.setProxyAuthentication(proxyAuthResponse);
          }

          if (myChallengeCredentials != null
              && (ntlmAuthIsRequired
                  || negoAuthIsRequired
                  || ((!"NTLM".equals(myChallengeCredentials.getAuthenticationScheme()))
                          && !"Negotiate".equals(myChallengeCredentials.getAuthenticationScheme()))
                      && httpAuth != null)) {
            if (httpAuthResponse == null) {
              request.initCredentials(myChallengeCredentials, method, path);
              httpAuthResponse = myChallengeCredentials.authenticate();
            }
            request.setAuthentication(httpAuthResponse);
          }

          try {
            request.dispatch(method, path, header, ok1, ok2, context);
            break;
          } catch (EOFException pe) {
            // retry, EOF always means closed connection.
            if (retryCount > 0) {
              close();
              continue;
            }
            throw (IOException) new IOException(pe.getMessage()).initCause(pe);
          } finally {
            retryCount--;
          }
        }
        myNextRequestTimeout = request.getNextRequestTimeout();
        status = request.getStatus();
      } catch (SSLHandshakeException ssl) {
        myRepository.getDebugLog().logFine(SVNLogType.NETWORK, ssl);
        close();
        if (ssl.getCause() instanceof SVNSSLUtil.CertificateNotTrustedException) {
          SVNErrorManager.cancel(ssl.getCause().getMessage(), SVNLogType.NETWORK);
        }
        SVNErrorMessage sslErr =
            SVNErrorMessage.create(
                SVNErrorCode.RA_NOT_AUTHORIZED,
                "SSL handshake failed: ''{0}''",
                new Object[] {ssl.getMessage()},
                SVNErrorMessage.TYPE_ERROR,
                ssl);
        if (keyManager != null) {
          keyManager.acknowledgeAndClearAuthentication(sslErr);
        }
        err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, ssl);
        // continue; http://svnkit.com/tracker/view.php?id=301 - Kohsuke
      } catch (IOException e) {
        myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e);
        if (e instanceof SocketTimeoutException) {
          err =
              SVNErrorMessage.create(
                  SVNErrorCode.RA_DAV_REQUEST_FAILED,
                  "timed out waiting for server",
                  null,
                  SVNErrorMessage.TYPE_ERROR,
                  e);
        } else if (e instanceof UnknownHostException) {
          err =
              SVNErrorMessage.create(
                  SVNErrorCode.RA_DAV_REQUEST_FAILED,
                  "unknown host",
                  null,
                  SVNErrorMessage.TYPE_ERROR,
                  e);
        } else if (e instanceof ConnectException) {
          err =
              SVNErrorMessage.create(
                  SVNErrorCode.RA_DAV_REQUEST_FAILED,
                  "connection refused by the server",
                  null,
                  SVNErrorMessage.TYPE_ERROR,
                  e);
        } else if (e instanceof SVNCancellableOutputStream.IOCancelException) {
          SVNErrorManager.cancel(e.getMessage(), SVNLogType.NETWORK);
        } else if (e instanceof SSLException) {
          err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e);
        } else {
          err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e);
        }
      } catch (SVNException e) {
        myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e);
        // force connection close on SVNException
        // (could be thrown by user's auth manager methods).
        close();
        throw e;
      } finally {
        finishResponse(request);
      }

      if (err != null) {
        close();
        break;
      }

      if (keyManager != null) {
        myKeyManager = keyManager;
        myTrustManager = trustManager;
        keyManager.acknowledgeAndClearAuthentication(null);
      }

      if (status.getCode() == HttpURLConnection.HTTP_FORBIDDEN) {
        myLastValidAuth = null;
        close();
        err = request.getErrorMessage();
      } else if (myIsProxied && status.getCode() == HttpURLConnection.HTTP_PROXY_AUTH) {
        Collection proxyAuthHeaders =
            request.getResponseHeader().getHeaderValues(HTTPHeader.PROXY_AUTHENTICATE_HEADER);
        try {
          myProxyAuthentication =
              HTTPAuthentication.parseAuthParameters(
                  proxyAuthHeaders, myProxyAuthentication, myCharset);
        } catch (SVNException svne) {
          myRepository.getDebugLog().logFine(SVNLogType.NETWORK, svne);
          err = svne.getErrorMessage();
          break;
        }

        if (myProxyAuthentication instanceof HTTPNTLMAuthentication) {
          ntlmProxyAuthIsRequired = true;
          HTTPNTLMAuthentication ntlmProxyAuth = (HTTPNTLMAuthentication) myProxyAuthentication;
          if (ntlmProxyAuth.isInType3State()) {
            continue;
          }
        }

        err =
            SVNErrorMessage.create(
                SVNErrorCode.RA_NOT_AUTHORIZED, "HTTP proxy authorization failed");
        SVNURL location = myRepository.getLocation();
        ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager();
        ISVNProxyManager proxyManager =
            authManager != null ? authManager.getProxyManager(location) : null;
        if (proxyManager != null) {
          proxyManager.acknowledgeProxyContext(false, err);
        }
        close();

        break;
      } else if (status.getCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
        authAttempts++; // how many times did we try?

        Collection authHeaderValues =
            request.getResponseHeader().getHeaderValues(HTTPHeader.AUTHENTICATE_HEADER);
        if (authHeaderValues == null || authHeaderValues.size() == 0) {
          err = request.getErrorMessage();
          status.setError(
              SVNErrorMessage.create(
                  SVNErrorCode.RA_DAV_REQUEST_FAILED,
                  err.getMessageTemplate(),
                  err.getRelatedObjects()));
          if ("LOCK".equalsIgnoreCase(method)) {
            status
                .getError()
                .setChildErrorMessage(
                    SVNErrorMessage.create(
                        SVNErrorCode.UNSUPPORTED_FEATURE,
                        "Probably you are trying to lock file in repository that only allows anonymous access"));
          }
          SVNErrorManager.error(status.getError(), SVNLogType.NETWORK);
          return status;
        }

        // we should work around a situation when a server
        // does not support Basic authentication while we're
        // forcing it, credentials should not be immediately
        // thrown away
        boolean skip = false;
        isAuthForced =
            myRepository.getAuthenticationManager() != null
                ? myRepository.getAuthenticationManager().isAuthenticationForced()
                : false;
        if (isAuthForced) {
          if (httpAuth != null
              && myChallengeCredentials != null
              && !HTTPAuthentication.isSchemeSupportedByServer(
                  myChallengeCredentials.getAuthenticationScheme(), authHeaderValues)) {
            skip = true;
          }
        }

        try {
          myChallengeCredentials =
              HTTPAuthentication.parseAuthParameters(
                  authHeaderValues, myChallengeCredentials, myCharset);
        } catch (SVNException svne) {
          err = svne.getErrorMessage();
          break;
        }

        myChallengeCredentials.setChallengeParameter("methodname", method);
        myChallengeCredentials.setChallengeParameter("uri", path);

        if (skip) {
          close();
          continue;
        }

        HTTPNTLMAuthentication ntlmAuth = null;
        HTTPNegotiateAuthentication negoAuth = null;
        if (myChallengeCredentials instanceof HTTPNTLMAuthentication) {
          ntlmAuthIsRequired = true;
          ntlmAuth = (HTTPNTLMAuthentication) myChallengeCredentials;
          if (ntlmAuth.isInType3State()) {
            continue;
          }
        } else if (myChallengeCredentials instanceof HTTPDigestAuthentication) {
          // continue (retry once) if previous request was acceppted?
          if (myLastValidAuth != null) {
            myLastValidAuth = null;
            continue;
          }
        } else if (myChallengeCredentials instanceof HTTPNegotiateAuthentication) {
          negoAuthIsRequired = true;
          negoAuth = (HTTPNegotiateAuthentication) myChallengeCredentials;
          if (negoAuth.isStarted()) {
            continue;
          }
        }

        myLastValidAuth = null;

        if (ntlmAuth != null && ntlmAuth.isNative() && authAttempts == 1) {
          /*
           * if this is the first time we get HTTP_UNAUTHORIZED, NTLM is the target auth scheme
           * and JNA is available, we should try a native auth mechanism first without calling
           * auth providers.
           */
          continue;
        }

        if (negoAuth != null) {
          continue;
        }

        ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager();
        if (authManager == null) {
          err = request.getErrorMessage();
          break;
        }

        realm = myChallengeCredentials.getChallengeParameter("realm");
        realm = realm == null ? "" : " " + realm;
        realm =
            "<"
                + myHost.getProtocol()
                + "://"
                + myHost.getHost()
                + ":"
                + myHost.getPort()
                + ">"
                + realm;

        if (httpAuth == null) {
          httpAuth =
              authManager.getFirstAuthentication(
                  ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation());
        } else {
          authManager.acknowledgeAuthentication(
              false,
              ISVNAuthenticationManager.PASSWORD,
              realm,
              request.getErrorMessage(),
              httpAuth);
          httpAuth =
              authManager.getNextAuthentication(
                  ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation());
        }

        if (httpAuth == null) {
          err = SVNErrorMessage.create(SVNErrorCode.CANCELLED, "HTTP authorization cancelled");
          break;
        }
        if (httpAuth != null) {
          myChallengeCredentials.setCredentials((SVNPasswordAuthentication) httpAuth);
        }
        continue;
      } else if (status.getCode() == HttpURLConnection.HTTP_MOVED_PERM
          || status.getCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
        close();
        String newLocation =
            request.getResponseHeader().getFirstHeaderValue(HTTPHeader.LOCATION_HEADER);
        if (newLocation == null) {
          err = request.getErrorMessage();
          break;
        }
        int hostIndex = newLocation.indexOf("://");
        if (hostIndex > 0) {
          hostIndex += 3;
          hostIndex = newLocation.indexOf("/", hostIndex);
        }
        if (hostIndex > 0 && hostIndex < newLocation.length()) {
          String newPath = newLocation.substring(hostIndex);
          if (newPath.endsWith("/")
              && !newPath.endsWith("//")
              && !path.endsWith("/")
              && newPath.substring(0, newPath.length() - 1).equals(path)) {
            path += "//";
            continue;
          }
        }
        err = request.getErrorMessage();
      } else if (request.getErrorMessage() != null) {
        err = request.getErrorMessage();
      } else {
        ntlmProxyAuthIsRequired = false;
        ntlmAuthIsRequired = false;
        negoAuthIsRequired = false;
      }

      if (err != null) {
        break;
      }

      if (myIsProxied) {
        SVNURL location = myRepository.getLocation();
        ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager();
        ISVNProxyManager proxyManager =
            authManager != null ? authManager.getProxyManager(location) : null;
        if (proxyManager != null) {
          proxyManager.acknowledgeProxyContext(true, null);
        }
      }

      if (httpAuth != null && realm != null && myRepository.getAuthenticationManager() != null) {
        myRepository
            .getAuthenticationManager()
            .acknowledgeAuthentication(
                true, ISVNAuthenticationManager.PASSWORD, realm, null, httpAuth);
      }
      if (trustManager != null && myRepository.getAuthenticationManager() != null) {
        myRepository.getAuthenticationManager().acknowledgeTrustManager(trustManager);
      }

      if (httpAuth != null) {
        myLastValidAuth = httpAuth;
      }

      status.setHeader(request.getResponseHeader());
      return status;
    }
    // force close on error that was not processed before.
    // these are errors that has no relation to http status (processing error or cancellation).
    close();
    if (err != null
        && err.getErrorCode().getCategory() != SVNErrorCode.RA_DAV_CATEGORY
        && err.getErrorCode() != SVNErrorCode.UNSUPPORTED_FEATURE) {
      SVNErrorManager.error(err, SVNLogType.NETWORK);
    }
    // err2 is another default context...
    //        myRepository.getDebugLog().info(err.getMessage());
    myRepository.getDebugLog().logFine(SVNLogType.NETWORK, new Exception(err.getMessage()));
    SVNErrorMessage err2 =
        SVNErrorMessage.create(
            SVNErrorCode.RA_DAV_REQUEST_FAILED,
            "{0} request failed on ''{1}''",
            new Object[] {method, path},
            err.getType(),
            err.getCause());
    SVNErrorManager.error(err, err2, SVNLogType.NETWORK);
    return null;
  }
      @Override
      public void run() {
        try {
          BufferedInputStream in = new BufferedInputStream(connectionSocket.getInputStream());
          while (true) {

            byte[] streamNameByteSize = loadData(in, new byte[4]);
            ByteBuffer sizeBuf = ByteBuffer.wrap(streamNameByteSize);
            int streamNameSize = sizeBuf.getInt();
            byte[] streamNameData = loadData(in, new byte[streamNameSize]);
            String streamId = new String(streamNameData, 0, streamNameData.length);
            StreamRuntimeInfo streamRuntimeInfo = streamRuntimeInfoMap.get(streamId);

            Object[] eventData = new Object[streamRuntimeInfo.getNoOfAttributes()];
            byte[] fixedMessageData =
                loadData(in, new byte[8 + streamRuntimeInfo.getFixedMessageSize()]);

            ByteBuffer bbuf = ByteBuffer.wrap(fixedMessageData, 0, fixedMessageData.length);
            long timestamp = bbuf.getLong();

            List<Integer> stringValueSizes = new ArrayList<>();
            Attribute.Type[] attributeTypes = streamRuntimeInfo.getAttributeTypes();
            for (int i = 0; i < attributeTypes.length; i++) {
              Attribute.Type type = attributeTypes[i];
              switch (type) {
                case INT:
                  eventData[i] = bbuf.getInt();
                  continue;
                case LONG:
                  eventData[i] = bbuf.getLong();
                  continue;
                case BOOL:
                  eventData[i] = bbuf.get() == 1;
                  continue;
                case FLOAT:
                  eventData[i] = bbuf.getFloat();
                  continue;
                case DOUBLE:
                  eventData[i] = bbuf.getDouble();
                  continue;
                case STRING:
                  int size = bbuf.getInt();
                  stringValueSizes.add(size);
              }
            }

            int stringSizePosition = 0;
            for (int i = 0; i < attributeTypes.length; i++) {
              Attribute.Type type = attributeTypes[i];
              if (Attribute.Type.STRING == type) {
                byte[] stringData =
                    loadData(in, new byte[stringValueSizes.get(stringSizePosition)]);
                stringSizePosition++;
                eventData[i] = new String(stringData, 0, stringData.length);
              }
            }
            streamCallback.receive(streamId, timestamp, eventData);
          }
        } catch (EOFException e) {
          log.info("Closing listener socket. " + e.getMessage());
        } catch (IOException e) {
          log.error("Error reading data from receiver socket:" + e.getMessage(), e);
        } catch (Throwable t) {
          log.error("Error :" + t.getMessage(), t);
        }
      }
예제 #21
0
  /**
   * Returns the next packet in the file, or null if no more packets remain. Call {@link
   * OggPacket#isBeginningOfStream()} to detect if it is the first packet in the stream or not, and
   * use {@link OggPacket#getSid()} to track which stream it belongs to.
   */
  public OggPacket getNextPacket() throws IOException {
    // If we skipped to a point in the stream, and
    //  have a packet waiting, return that
    if (nextPacket != null) {
      OggPacket p = nextPacket;
      nextPacket = null;
      return p;
    }

    // If we're already part way through a page,
    //  then fetch the next packet. If it's a
    //  full one, then we're done.
    OggPacketData leftOver = null;
    if (it != null && it.hasNext()) {
      OggPacketData packet = it.next();
      if (packet instanceof OggPacket) {
        return (OggPacket) packet;
      }
      leftOver = packet;
    }

    // Find the next page, from which
    //  to get our next packet from
    int searched = 0;
    int pos = -1;
    boolean found = false;
    int r;
    while (searched < 65536 && !found) {
      r = inp.read();
      if (r == -1) {
        // No more data
        return null;
      }

      switch (pos) {
        case -1:
          if (r == (int) 'O') {
            pos = 0;
          }
          break;
        case 0:
          if (r == (int) 'g') {
            pos = 1;
          } else {
            pos = -1;
          }
          break;
        case 1:
          if (r == (int) 'g') {
            pos = 2;
          } else {
            pos = -1;
          }
          break;
        case 2:
          if (r == (int) 'S') {
            found = true;
          } else {
            pos = -1;
          }
          break;
      }

      if (!found) {
        searched++;
      }
    }

    if (!found) {
      throw new IOException(
          "Next ogg packet header not found after searching " + searched + " bytes");
    }

    searched -= 3; // OggS
    if (searched > 0) {
      System.err.println(
          "Warning - had to skip "
              + searched
              + " bytes of junk data before finding the next packet header");
    }

    // Create the page, and prime the iterator on it
    try {
      OggPage page = new OggPage(inp);
      if (!page.isChecksumValid()) {
        System.err.println(
            "Warning - invalid checksum on page "
                + page.getSequenceNumber()
                + " of stream "
                + Integer.toHexString(page.getSid())
                + " ("
                + page.getSid()
                + ")");
      }
      it = page.getPacketIterator(leftOver);
      return getNextPacket();
    } catch (EOFException eof) {
      System.err.println("Warning - data ended mid-page: " + eof.getMessage());
      return null;
    }
  }