@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;
   }
 }
 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();
   }
 }
Exemple #3
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;
  }
Exemple #4
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);
 }
    /** @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();
      }
    }
 /**
  * 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 #9
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();
  }
 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 #11
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;
 }
  // see DbFile.java for javadocs
  public Page readPage(PageId pid) {
    // some code goes here
    if (pid.pageNumber() >= numPages()) {
      throw new IllegalArgumentException("page not in file");
    }
    Page returnme = null;

    byte[] data = HeapPage.createEmptyPageData();
    long offset = (long) BufferPool.PAGE_SIZE * pid.pageNumber();
    try {
      raf.seek(offset);
      for (int i = 0; i < data.length; i++) {
        data[i] = raf.readByte();
      }
      returnme = new HeapPage((HeapPageId) pid, data);
    } catch (EOFException eofe) {
      eofe.printStackTrace();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
    return returnme;
  }
  public Object readObject(String key, Object o) {
    Object object = null;

    ByteArrayInputStream bis = null;
    ObjectInputStream ois;
    try {
      String value = getString(key, "");
      byte[] bytes = Base64.decode(value);

      if (bytes.length > 0) {
        // 封装到字节流
        bis = new ByteArrayInputStream(bytes);
        // 再次封装
        ois = new ObjectInputStream(bis);
        // 读取对象
        object = ois.readObject();
      } else {
        object = o;
      }
    } catch (EOFException e) {
      e.printStackTrace();
    } catch (StreamCorruptedException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {
        if (bis != null) bis.close();
        if (bis != null) bis.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return object;
  }
  // check if compressed file seems ok
  public static long testValid(String ufilename) throws IOException {
    boolean lookForHeader = false;

    // gotta make it
    RandomAccessFile raf = new RandomAccessFile(ufilename, "r");
    raf.order(RandomAccessFile.BIG_ENDIAN);
    raf.seek(0);
    byte[] b = new byte[8];
    raf.read(b);
    String test = new String(b);
    if (test.equals(Level2VolumeScan.ARCHIVE2) || test.equals(Level2VolumeScan.AR2V0001)) {
      System.out.println("--Good header= " + test);
      raf.seek(24);
    } else {
      System.out.println("--No header ");
      lookForHeader = true;
      raf.seek(0);
    }

    boolean eof = false;
    int numCompBytes;
    try {

      while (!eof) {

        if (lookForHeader) {
          raf.read(b);
          test = new String(b);
          if (test.equals(Level2VolumeScan.ARCHIVE2) || test.equals(Level2VolumeScan.AR2V0001)) {
            System.out.println("  found header= " + test);
            raf.skipBytes(16);
            lookForHeader = false;
          } else {
            raf.skipBytes(-8);
          }
        }

        try {
          numCompBytes = raf.readInt();
          if (numCompBytes == -1) {
            System.out.println("\n--done: numCompBytes=-1 ");
            break;
          }
        } catch (EOFException ee) {
          System.out.println("\n--got EOFException ");
          break; // assume this is ok
        }

        System.out.print(" " + numCompBytes + ",");
        if (numCompBytes < 0) {
          System.out.println("\n--last block " + numCompBytes);
          numCompBytes = -numCompBytes;
          if (!lookForHeader) eof = true;
        }

        raf.skipBytes(numCompBytes);
      }
    } catch (EOFException e) {
      e.printStackTrace();
    }

    return raf.getFilePointer();
  }
  @Override
  public void run() {
    try {
      aes = new AESEncryptDecrypt();
      while (bConnected) {
        String MsgFromClient = br.readLine();

        if (MsgFromClient != null) {
          // Request for log in
          System.out.println(MsgFromClient);
          if (MsgFromClient.equals(LOGINREQUESTLABEL)) {
            userIdStr = br.readLine();
            passwordStr = br.readLine();

            passwordFromDB = DBAccess.getPasswordFromDB(userIdStr);
            priorityFromDB = DBAccess.getPriorityFromDB(userIdStr);
            System.out.println("password from db: " + passwordFromDB);

            // sent the LOGINRESPONSELABLE to client
            bw.write(LOGINRESPONSELABEL);
            bw.newLine();
            bw.flush();
            System.out.println(userIdStr);
            System.out.println(passwordStr);
            // System.out.println(passwordFromDB);

            // sent the log in result to client, fail or successful
            if (passwordFromDB != null && passwordStr.equals(passwordFromDB)) {
              if (priorityFromDB.equals("guest")) {
                bw.write(USERLOGINRESULT);
                bw.newLine();
                bw.flush();
              } else if (priorityFromDB.equals("admin")) {
                bw.write(ADMINLOGINRESULT);
                bw.newLine();
                bw.flush();
              }
            } else {
              bw.write(LOGINFAIL);
              bw.newLine();
              bw.flush();
            }
          }

          // Request for the MedRecordsPackage
          else if (MsgFromClient.equals(REQUESTMEDRECORDSPACKAGE)) {
            MedRecordsPackage MRP = DBAccess.getAllMedRecords();
            oos = new ObjectOutputStream(socket.getOutputStream());

            if (MRP != null) {
              oos.writeObject(MRP);
              oos.flush();
            }

          }

          // Request for one MedRecord
          else if (MsgFromClient.equals(REQUESTONEMEDRECORD)) {
            MedRecord MR = DBAccess.getOneMedRecord(userIdStr);
            oos = new ObjectOutputStream(socket.getOutputStream());

            if (MR != null) {
              oos.writeObject(MR);
              oos.flush();
            }

          }

          // Request for update user's info
          else if (MsgFromClient.equals(REQUESTUPDATE)) {
            MedRecord mr = null;
            // wait to get the MedRecordsPackage
            try {
              ois = new ObjectInputStream(socket.getInputStream());
              mr = (MedRecord) ois.readObject();

            } catch (IOException e) {
              e.printStackTrace();
            } catch (ClassNotFoundException e) {
              e.printStackTrace();
            }

            if (mr != null) {
              DBAccess.updateMedRecord(mr);
            }
          }

          // App log out request
          else if (MsgFromClient.equals(APPLOGOUT)) {
            bConnected = false;
          }
        }
      }
    } catch (EOFException e) {
      e.printStackTrace();
      System.out.println("Client disconnect!");
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (socket != null) socket.close();
        if (br != null) br.close();
        if (bw != null) bw.close();
        if (ois != null) ois.close();
        if (oos != null) oos.close();
        // if (DBAccess != null) DBAccess.DBclose();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  /** Network communication thread */
  public void run() {

    while (!Thread.currentThread().isInterrupted() && getKeepRunning()) {

      try {
        // Starting the server (reuse & bind)
        System.out.println("k9d3 Starting the server (reuse & bind)");
        mServerSocket = new ServerSocket();
        mServerSocket.setReuseAddress(true);
        mServerSocket.bind(new InetSocketAddress(NetworkManager.PORT));

        // Waiting for a client to connect
        System.out.println("k9d3 Waiting for a client to connect");
        mClientSocket = mServerSocket.accept();
        setConnectivity(true);

        // IO setup
        System.out.println("k9d3 IO setup");
        in = new ObjectInputStream(mClientSocket.getInputStream());
        out = new ObjectOutputStream(mClientSocket.getOutputStream());
        out.flush();

        // The first time a client is connected, you need to send him everything over the socket
        System.out.println(
            "k9d3 The first time a client is connected, you need to send him everything over the socket");
        if (!mThread.isInterrupted() && getKeepRunning() && getConnectivity()) {
          mCallback.sendEverything();
        }

        // Socket communication main loop
        System.out.println("k9d3 Socket communication main loop");
        while (!Thread.currentThread().isInterrupted() && getKeepRunning() && getConnectivity()) {
          try {
            msg = (String) in.readObject();
            processMessage(msg);
          } catch (ClassNotFoundException e) {
            e.printStackTrace();
          } catch (EOFException e) {
            e.printStackTrace();
            setConnectivity(false);
          } catch (SocketException e) {
            e.printStackTrace();
            setConnectivity(false);
          }
        }

      } catch (IOException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          if (out != null) {
            synchronized (out) {
              out.close();
              out = null;
            }
          }

          if (in != null) {
            in.close();
            in = null;
          }

          if (mClientSocket != null) {
            mClientSocket.close();
            mClientSocket = null;
          }

          if (mServerSocket != null) {
            mServerSocket.close();
            mServerSocket = null;
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
        setConnectivity(false);
      } // finally
    } // while
  } // run
 @SuppressWarnings("unchecked")
 public Map<String, ArrayList<Integer>[]> read(String file) {
   try {
     Map<String, ArrayList<Integer>[]> map = new TreeMap<String, ArrayList<Integer>[]>();
     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 == 4) {
           if (!array2[0].equals("") || array2[0] != null) {
             ArrayList<Integer>[] list = new ArrayList[3];
             list[0] = new ArrayList<Integer>();
             for (String str : array2[1].replace("[", "").replace("]", "").split(", ")) {
               list[0].add(Integer.parseInt(str));
             }
             list[1] = new ArrayList<Integer>();
             for (String str : array2[2].replace("[", "").replace("]", "").split(", ")) {
               list[1].add(Integer.parseInt(str));
             }
             list[2] = new ArrayList<Integer>();
             for (String str : array2[3].replace("[", "").replace("]", "").split(", ")) {
               list[2].add(Integer.parseInt(str));
             }
             map.put(array2[0], list);
           }
         } else if (array2.length == 5) {
           if (!array2[0].equals("") || array2[0] != null) {
             ArrayList<Integer>[] list = new ArrayList[4];
             list[0] = new ArrayList<Integer>();
             for (String str : array2[1].replace("[", "").replace("]", "").split(", ")) {
               list[0].add(Integer.parseInt(str));
             }
             list[1] = new ArrayList<Integer>();
             for (String str : array2[2].replace("[", "").replace("]", "").split(", ")) {
               list[1].add(Integer.parseInt(str));
             }
             list[2] = new ArrayList<Integer>();
             for (String str : array2[3].replace("[", "").replace("]", "").split(", ")) {
               list[2].add(Integer.parseInt(str));
             }
             list[3] = new ArrayList<Integer>();
             for (String str : array2[4].replace("[", "").replace("]", "").split(", ")) {
               list[3].add(Integer.parseInt(str));
             }
             map.put(array2[0], list);
           }
         }
       }
     }
     reader.close();
     return map;
   } catch (EOFException e) {
     e.printStackTrace();
     return null;
   } catch (IOException e) {
     e.printStackTrace();
     return null;
   }
 }