/**
   * 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());
      }
    }
  }
  @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
 public static void main(String[] args) {
   SimpleProducer sp = new SimpleProducer();
   EventMessage event = new EventMessage();
   String[] machines = {"pump_1", "pump_2", "tank_1", "tank_2"};
   event.setBuilding("building_3");
   event.setId("5ba51e3");
   event.setDate(new Date().getTime());
   float minX = 1f;
   float maxX = 100.0f;
   Random rand = new Random();
   try {
     EventMessageSerializer eventMessageSerializer = new EventMessageSerializer();
     for (int i = 0; i < 10; i++) {
       event.setStatus(rand.nextFloat() * (maxX - minX) + minX);
       event.setMachine(machines[new Random().nextInt(machines.length)]);
       sp.publish(eventMessageSerializer.serializeMessage(event), event.getId().toString());
     }
   } catch (EOFException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (InterruptedException e) {
     e.printStackTrace();
   } catch (ExecutionException e) {
     e.printStackTrace();
   }
 }
 /** 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);
   }
 }
 @SuppressWarnings("unchecked")
 public Map<Integer, String>[] readDictionary(String file) {
   try {
     Map<Integer, String>[] map = new TreeMap[2];
     map[0] = new TreeMap<Integer, String>();
     map[1] = new TreeMap<Integer, String>();
     BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
     String string = "";
     String[] array1 = null, array2 = null;
     while ((string = reader.readLine()) != null) {
       array1 = string.split("#");
       for (String data : array1) {
         array2 = data.split(":");
         if (array2.length == 3) {
           if (!array2[0].equals("") || array2[0] != null) {
             map[0].put(Integer.parseInt(array2[0]), array2[1]);
             map[1].put(Integer.parseInt(array2[0]), array2[2]);
           }
         }
       }
     }
     reader.close();
     return map;
   } catch (EOFException e) {
     e.printStackTrace();
     return null;
   } catch (IOException e) {
     e.printStackTrace();
     return null;
   }
 }
 @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);
   }
 }
 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());
       }
   }
 }
Exemple #8
0
  public Object receiveObject() {

    // If we are connected then we can receive
    if (isConnected()) {

      try {
        Object receive =
            getInputStream()
                .readObject(); // Read objects from the stream and set the receivable to it
        if (receive
            != null) // as long as the input stream is not null we can keep reading through the
        // stream
        {
          return receive; // return the object received from the server
        }
      }
      // This exception is reached when it is done reading the object
      catch (EOFException ex) {
        ex.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    }
    return null;
  }
 /* @see java.io.DataInput.readShort() */
 public short readShort() throws IOException {
   buffer(position, 2);
   position += 2;
   try {
     return buffer.getShort();
   } catch (BufferUnderflowException e) {
     EOFException eof = new EOFException(EOF_ERROR_MSG);
     eof.initCause(e);
     throw eof;
   }
 }
Exemple #10
0
 /* @see java.io.DataInput.readLong() */
 public long readLong() throws IOException {
   buffer(position, 8);
   position += 8;
   try {
     return buffer.getLong();
   } catch (BufferUnderflowException e) {
     EOFException eof = new EOFException(EOF_ERROR_MSG);
     eof.initCause(e);
     throw eof;
   }
 }
Exemple #11
0
 /* @see java.io.DataInput.readInt() */
 public int readInt() throws IOException {
   buffer(position, 4);
   position += 4;
   try {
     return buffer.getInt();
   } catch (BufferUnderflowException e) {
     EOFException eof = new EOFException(EOF_ERROR_MSG);
     eof.initCause(e);
     throw eof;
   }
 }
Exemple #12
0
 /* @see java.io.DataInput.readByte() */
 public byte readByte() throws IOException {
   buffer(position, 1);
   position += 1;
   try {
     return buffer.get();
   } catch (BufferUnderflowException e) {
     EOFException eof = new EOFException(EOF_ERROR_MSG);
     eof.initCause(e);
     throw eof;
   }
 }
  /**
   * 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();
  }
  /**
   * 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();
      }
    }
Exemple #16
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());
   }
 }
Exemple #17
0
 @Test
 public void testReadThrowsEOFException() throws Throwable {
   FSDMsg fSDMsg = new FSDMsg("testFSDMsgBasePath");
   when(is.read(new byte[] {(byte) 00})).thenReturn(Integer.valueOf(1));
   when(is.read(new byte[] {(byte) 00})).thenReturn(Integer.valueOf(1));
   when(is.read(new byte[] {(byte) 00})).thenReturn(Integer.valueOf(-1));
   try {
     fSDMsg.read(is, 100, " ", null);
     fail("Expected EOFException to be thrown");
   } catch (EOFException ex) {
     assertEquals("ex.getClass()", EOFException.class, ex.getClass());
   }
 }
  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();
    }
  }
  @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);
    }
  }
Exemple #20
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());
   }
 }
 private void rethrowEofException(IOException ioEx) throws IOException {
   boolean isEof = false;
   try {
     isEof = this.in.available() == 0;
   } catch (Throwable t) {
     LOG.trace("Error getting available for error message - ignoring", t);
   }
   if (!isEof) throw ioEx;
   if (LOG.isTraceEnabled()) {
     LOG.trace("Partial cell read caused by EOF", ioEx);
   }
   EOFException eofEx = new EOFException("Partial cell read");
   eofEx.initCause(ioEx);
   throw eofEx;
 }
 /**
  * Create RelatedUsersWritable from input stream.
  *
  * @param in input stream
  * @throws IOException -
  */
 @Override
 public void readFields(final DataInput in) throws IOException {
   try {
     int listSize = in.readInt();
     this.relatedUsers = new ArrayList<LongWritable>(listSize);
     for (int i = 0; i < listSize; i++) {
       long userID = in.readLong();
       this.relatedUsers.add(new LongWritable(userID));
     }
   } catch (EOFException e) {
     e.printStackTrace();
   } catch (ArrayIndexOutOfBoundsException e) {
     e.printStackTrace();
   }
 }
  private void readJournal() throws IOException {
    InputStream in = new BufferedInputStream(new FileInputStream(journalFile), IO_BUFFER_SIZE);
    try {
      String magic = readAsciiLine(in);
      String version = readAsciiLine(in);
      String appVersionString = readAsciiLine(in);
      String valueCountString = readAsciiLine(in);
      String blank = readAsciiLine(in);
      if (!MAGIC.equals(magic)
          || !VERSION_1.equals(version)
          || !Integer.toString(appVersion).equals(appVersionString)
          || !Integer.toString(valueCount).equals(valueCountString)
          || !"".equals(blank)) {
        Logger.d(
            BitmapLoader.TAG,
            "unexpected journal header: ["
                + magic
                + ", "
                + version
                + ", "
                + valueCountString
                + ", "
                + blank
                + "]");
        throw new IOException(
            "unexpected journal header: ["
                + magic
                + ", "
                + version
                + ", "
                + valueCountString
                + ", "
                + blank
                + "]");
      }

      while (true) {
        try {
          readJournalLine(readAsciiLine(in));
        } catch (EOFException endOfJournal) {
          endOfJournal.printStackTrace();
          break;
        }
      }
    } finally {
      closeQuietly(in);
    }
  }
 /*
  * Receive an integer from the client
  * @return the received int or error number
  * @throws Exception if a null string was received
  */
 private int receiveInt() throws Exception {
   int val = RHErrors.RHE_GENERAL;
   try {
     String str = receiveString();
     val = Integer.parseInt(str);
   } catch (EOFException eofe) {
     eofe.printStackTrace();
     return RHErrors.RHE_IOE;
   } catch (IOException ioe) {
     ioe.printStackTrace();
     return RHErrors.RHE_IOE;
   } catch (Exception e) {
     throw new Exception("Received null string");
   }
   return val;
 }
Exemple #25
0
  public static void main(String[] args) throws PcapNativeException, NotOpenException {
    String filter = args.length != 0 ? args[0] : "";

    System.out.println(COUNT_KEY + ": " + COUNT);
    System.out.println(READ_TIMEOUT_KEY + ": " + READ_TIMEOUT);
    System.out.println(SNAPLEN_KEY + ": " + SNAPLEN);
    System.out.println("\n");

    PcapNetworkInterface nif;
    try {
      nif = new NifSelector().selectNetworkInterface();
    } catch (IOException e) {
      e.printStackTrace();
      return;
    }

    if (nif == null) {
      return;
    }

    System.out.println(nif.getName() + "(" + nif.getDescription() + ")");

    PcapHandle handle = nif.openLive(SNAPLEN, PromiscuousMode.PROMISCUOUS, READ_TIMEOUT);

    handle.setFilter(filter, BpfCompileMode.OPTIMIZE);

    int num = 0;
    while (true) {
      try {
        Packet packet = handle.getNextPacketEx();
        Timestamp ts = new Timestamp(handle.getTimestampInts() * 1000L);
        ts.setNanos(handle.getTimestampMicros() * 1000);

        System.out.println(ts);
        System.out.println(packet);
        num++;
        if (num >= COUNT) {
          break;
        }
      } catch (TimeoutException e) {
      } catch (EOFException e) {
        e.printStackTrace();
      }
    }

    handle.close();
  }
Exemple #26
0
 private void handleEOF(EOFException exp, Snapshot snapshot) {
   if (debugLevel > 0) {
     exp.printStackTrace();
   }
   warn("Unexpected EOF. Will miss information...");
   // we have EOF, we have to tolerate missing references
   snapshot.setUnresolvedObjectsOK(true);
 }
Exemple #27
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);
   }
 }
 protected synchronized Message receiveMessage() throws IOException {
   if (messageBuffer.size() > 0) {
     Message m = (Message) messageBuffer.get(0);
     messageBuffer.remove(0);
     return m;
   }
   try {
     InetSocketAddress remoteAddress = (InetSocketAddress) channel.receive(receiveBuffer);
     if (remoteAddress != null) {
       int len = receiveBuffer.position();
       receiveBuffer.rewind();
       receiveBuffer.get(buf, 0, len);
       try {
         IP address = IP.fromInetAddress(remoteAddress.getAddress());
         int port = remoteAddress.getPort();
         extractor.appendData(buf, 0, len, new SocketDescriptor(address, port));
         receiveBuffer.clear();
         extractor.updateAvailableMessages();
         return extractor.nextMessage();
       } catch (EOFException exc) {
         exc.printStackTrace();
         System.err.println(buf.length + ", " + len);
       } catch (InvocationTargetException exc) {
         exc.printStackTrace();
       } catch (IllegalAccessException exc) {
         exc.printStackTrace();
       } catch (InstantiationException exc) {
         exc.printStackTrace();
       } catch (IllegalArgumentException e) {
         e.printStackTrace();
       } catch (InvalidCompressionMethodException e) {
         e.printStackTrace();
       }
     }
   } catch (ClosedChannelException exc) {
     if (isKeepAlive()) {
       throw exc;
     }
   }
   return null;
 }
Exemple #29
0
 public Object deserialize(String fileName) {
   try {
     ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
     int count = 0;
     while (true) {
       count++;
       try {
         feedbackObject = in.readObject();
       } catch (ClassNotFoundException e) {
         Log.d("Error-Deserializer", "Cant read object");
       }
     }
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (EOFException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return feedbackObject;
 }
  @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) {

      }
    }
  }