Exemplo n.º 1
0
 @SuppressWarnings("deprecation")
 private void writeObject(java.io.ObjectOutputStream out) throws IOException {
   String factoryName = vf.getClass().getName();
   out.write("factory".getBytes());
   out.write(':');
   out.writeInt(factoryName.length());
   out.write(':');
   out.write(factoryName.getBytes("UTF8"));
   out.write(':');
   new BinaryValueWriter().write(value, out);
 }
Exemplo n.º 2
0
  /**
   * Serializes this object to a stream. @serialdata The object is first written in the old JDK 1.1
   * format, so that it can be read by by the old classes. This means, that the <code>
   * start/endDay(OfWeek)</code>-Fields are written in the DOW_IN_MONTH_MODE rule, since this was
   * the only supported rule in 1.1.
   *
   * <p>In the optional section, we write first the length of an byte array as int and afterwards
   * the byte array itself. The byte array contains in this release four elements, namely the real
   * startDay, startDayOfWeek endDay, endDayOfWeek in that Order. These fields are needed, because
   * for compatibility reasons only approximative values are written to the required section, as
   * described above.
   */
  private void writeObject(java.io.ObjectOutputStream output) throws java.io.IOException {
    byte[] byteArray =
        new byte[] {(byte) startDay, (byte) startDayOfWeek, (byte) endDay, (byte) endDayOfWeek};

    /* calculate the approximation for JDK 1.1 */
    switch (startMode) {
      case DOM_MODE:
        startDayOfWeek = Calendar.SUNDAY; // random day of week
        // fall through
      case DOW_GE_DOM_MODE:
      case DOW_LE_DOM_MODE:
        startDay = (startDay + 6) / 7;
    }
    switch (endMode) {
      case DOM_MODE:
        endDayOfWeek = Calendar.SUNDAY;
        // fall through
      case DOW_GE_DOM_MODE:
      case DOW_LE_DOM_MODE:
        endDay = (endDay + 6) / 7;
    }

    // the required part:
    output.defaultWriteObject();
    // the optional part:
    output.writeInt(byteArray.length);
    output.write(byteArray, 0, byteArray.length);
  }
Exemplo n.º 3
0
 public void saveCache(
     JMXInstrumentedCache<K, V> cache, File savedCachePath, Function<K, byte[]> converter)
     throws IOException {
   long start = System.currentTimeMillis();
   String msgSuffix = " " + savedCachePath.getName() + " for " + cfname + " of " + ksname;
   logger.debug("saving" + msgSuffix);
   int count = 0;
   File tmpFile =
       File.createTempFile(savedCachePath.getName(), null, savedCachePath.getParentFile());
   FileOutputStream fout = new FileOutputStream(tmpFile);
   ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fout));
   FileDescriptor fd = fout.getFD();
   for (K key : cache.getKeySet()) {
     byte[] bytes = converter.apply(key);
     out.writeInt(bytes.length);
     out.write(bytes);
     ++count;
   }
   out.flush();
   fd.sync();
   out.close();
   if (!tmpFile.renameTo(savedCachePath))
     throw new IOException("Unable to rename cache to " + savedCachePath);
   if (logger.isDebugEnabled())
     logger.debug(
         "saved "
             + count
             + " keys in "
             + (System.currentTimeMillis() - start)
             + " ms from"
             + msgSuffix);
 }
Exemplo n.º 4
0
  /**
   * Serializes an {@link MBeanFeatureInfo} to an {@link ObjectOutputStream}.
   *
   * @serialData For compatibility reasons, an object of this class is serialized as follows.
   *     <ul>
   *       The method {@link ObjectOutputStream#defaultWriteObject defaultWriteObject()} is called
   *       first to serialize the object except the field {@code descriptor} which is declared as
   *       transient. The field {@code descriptor} is serialized as follows:
   *       <ul>
   *         <li>If {@code descriptor} is an instance of the class {@link ImmutableDescriptor}, the
   *             method {@link ObjectOutputStream#write write(int val)} is called to write a byte
   *             with the value {@code 1}, then the method {@link ObjectOutputStream#writeObject
   *             writeObject(Object obj)} is called twice to serialize the field names and the field
   *             values of the {@code descriptor}, respectively as a {@code String[]} and an {@code
   *             Object[]};
   *         <li>Otherwise, the method {@link ObjectOutputStream#write write(int val)} is called to
   *             write a byte with the value {@code 0}, then the method {@link
   *             ObjectOutputStream#writeObject writeObject(Object obj)} is called to serialize
   *             directly the field {@code descriptor}.
   *       </ul>
   *     </ul>
   *
   * @since 1.6
   */
  private void writeObject(ObjectOutputStream out) throws IOException {
    out.defaultWriteObject();

    if (descriptor != null && descriptor.getClass() == ImmutableDescriptor.class) {

      out.write(1);

      final String[] names = descriptor.getFieldNames();

      out.writeObject(names);
      out.writeObject(descriptor.getFieldValues(names));
    } else {
      out.write(0);

      out.writeObject(descriptor);
    }
  }
Exemplo n.º 5
0
  private void writeObject(final ObjectOutputStream out) throws IOException {
    out.defaultWriteObject();

    out.writeInt(_length);
    out.writeDouble(_p);
    out.writeInt(_genes.length);
    out.write(_genes);
  }
 /** java.io.ObjectOutputStream#write(int) */
 public void test_writeI() throws Exception {
   // Test for method void java.io.ObjectOutputStream.write(int)
   oos.write('T');
   oos.close();
   ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
   assertEquals("Read incorrect byte", 'T', ois.read());
   ois.close();
 }
Exemplo n.º 7
0
  public Game(boolean host) {
    try {
      if (host) {
        System.out.println("Hosting...");
        server = new ServerSocket(port, 4, InetAddress.getByName(serverIP));
        System.out.println("Ready!\nAwaiting client...");
        client = server.accept();
        System.out.println("Client connected!\nBuffering...");
        out = new ObjectOutputStream(client.getOutputStream());
        in = new ObjectInputStream(client.getInputStream());
        System.out.println("Buffered!\nPinging for 256 bytes...");
        long start = System.currentTimeMillis();
        byte[] ping = new byte[256];
        in.read(ping);
        System.out.println("Latency: " + (System.currentTimeMillis() - start));
        out.writeLong(start);
        out.flush();
        System.out.println("Starting threads...");
        new ThreadSend(world, out);
        new ThreadReceive(world, in);
        System.out.println("Started!\nCreating game world...");
      } else {
        System.out.println("Connecting...");
        socket = new Socket(connectIP, port);
        System.out.println("Connected!\nBuffering...");
        in = new ObjectInputStream(socket.getInputStream());
        out = new ObjectOutputStream(socket.getOutputStream());
        byte[] ping = new byte[256];
        new Random().nextBytes(ping);
        System.out.println("Buffered\nPinging for 256 bytes...");
        out.write(ping);
        out.flush();
        long latency = in.readLong();
        System.out.println("Latency: " + (System.currentTimeMillis() - latency));
        System.out.println("Starting threads...");
        new ThreadReceive(world, in);
        new ThreadSend(world, out);
        System.out.println("Started!\nCreating game world...");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    try {
      Display.setDisplayMode(new DisplayMode(width, height));
      Display.create();
    } catch (Exception e) {
      e.printStackTrace();
    }

    world.init();

    while (!Display.isCloseRequested()) {
      if (ended) break;
      world.update();
    }

    Display.destroy();
  }
 /** java.io.ObjectOutputStream#write(byte[]) */
 public void test_write$B() throws Exception {
   // Test for method void java.io.ObjectOutputStream.write(byte [])
   byte[] buf = new byte[10];
   oos.write("HelloWorld".getBytes());
   oos.close();
   ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
   ois.read(buf, 0, 10);
   ois.close();
   assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0, 10));
 }
Exemplo n.º 9
0
 /* Fixed versions of this are below with ObjectInputStream tests */
 public void objectOutputStreamClosedNestedBad() throws IOException {
   ObjectOutputStream oin = null;
   try {
     oin = new ObjectOutputStream(new FileOutputStream("file.txt"));
     oin.write(3);
   } catch (IOException e) {
   } finally {
     if (oin != null) oin.close();
   }
 }
Exemplo n.º 10
0
 public void objectOutputStreamNotClosedAfterWrite() {
   byte[] arr = {1, 2, 3, 4, 5};
   ObjectOutputStream oout;
   try {
     oout = new ObjectOutputStream(new FileOutputStream("file.txt"));
     oout.write(arr);
     oout.close();
   } catch (IOException e) {
   }
 }
Exemplo n.º 11
0
 private void writeObject(ObjectOutputStream out) throws IOException {
   if (image != null) {
     final ByteArrayOutputStream stream = new ByteArrayOutputStream();
     image.compress(Bitmap.CompressFormat.PNG, 100, stream);
     final byte[] imageByteArray = stream.toByteArray();
     out.writeInt(imageByteArray.length);
     out.write(imageByteArray);
   } else {
     out.writeInt(NO_IMAGE);
   }
 }
Exemplo n.º 12
0
  private void writeObject(java.io.ObjectOutputStream out) throws IOException {
    out.defaultWriteObject();

    if (userDefinedSchema != null) {
      byte[] json = userDefinedSchema.toString().getBytes();
      out.writeInt(json.length);
      out.write(json);
    } else {
      out.writeInt(0);
    }
  }
Exemplo n.º 13
0
  private void writeObject(ObjectOutputStream out) throws IOException {
    out.writeUTF(localPath.getName());
    out.writeLong(localPath.length());

    byte[] xfer = new byte[4096];
    FileInputStream fis = new FileInputStream(localPath);
    try {
      for (int read = fis.read(xfer); read >= 0; read = fis.read(xfer)) out.write(xfer, 0, read);
    } finally {
      fis.close();
    }
  }
Exemplo n.º 14
0
    /**
     * Get the signature data generated
     *
     * @return Signature data
     * @throws OpenStegoException
     */
    public byte[] getSigData() throws OpenStegoException {
      ByteArrayOutputStream baos = null;
      ObjectOutputStream oos = null;

      try {
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.write(this.sig);
        oos.writeInt(this.watermarkLength);
        oos.writeDouble(this.embeddingStrength);
        oos.writeInt(this.waveletFilterMethod);
        oos.writeInt(this.filterID);
        oos.writeInt(this.embeddingLevel);
        oos.write(this.watermark);
        oos.flush();
        oos.close();

        return baos.toByteArray();
      } catch (IOException ioEx) {
        throw new OpenStegoException(ioEx);
      }
    }
  @Override
  public void run() {
    while (true) {
      try {
        // New client appears:
        clientSocket = serverSocket.accept();
        out = new ObjectOutputStream(clientSocket.getOutputStream());
        in = new BufferedInputStream(clientSocket.getInputStream());
      } catch (IOException ex) {
        Logger.getLogger(FileDistributor.class.getName()).log(Level.SEVERE, null, ex);
      }
      System.out.println(
          "Accepted connection from address: "
              + clientSocket.getInetAddress()
              + ":"
              + clientSocket.getPort());

      byte[] msg = new byte[25];
      try {
        // Read the name of the file to Distribute:
        in.read(msg, 0, msg.length);
        fileName = new String(msg).replaceAll("\\s", "");

        // Create a new file and directory if that does not exist:
        File myFile = new File(shared_folder + "\\" + fileName);

        // Initialize variables:
        long fileSize = myFile.length();
        long completed = 0;
        int step = 100000;

        // Start a fileInputStream to read bytes from the requested file.
        FileInputStream fis = new FileInputStream(myFile);

        // Start sending the requested file.
        System.out.println("Start sending file: " + fileName);
        byte[] buffer = new byte[step];
        while (completed <= fileSize) {
          fis.read(buffer);
          out.write(buffer);
          completed += step;
        }
        out.flush();
        System.out.println("Sending file " + fileName + " completed successfully!");
      } catch (IOException ex) {
        Logger.getLogger(FileDistributor.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Exemplo n.º 16
0
 public void enviar(byte[] buffer) {
   try {
     // streamDeSaida.write(buffer);
     ObjectOutputStream oos = new ObjectOutputStream(streamDeSaida);
     oos.write(buffer);
     oos.flush();
     this.handle
         .obtainMessage(ManipuladorProtocolo.ENVIAR_MENSAGEM, buffer.length, -1, buffer)
         .sendToTarget();
   } catch (IOException e) {
     this.handle
         .obtainMessage(ManipuladorProtocolo.RECEBER_MENSAGEM, buffer.length, -1, buffer)
         .sendToTarget();
     Log.e(TAG, "Exception during write", e);
   }
 }
Exemplo n.º 17
0
  @Override
  public byte[] encode(Object value) {

    try {
      String className = value.getClass().getName();
      // TODO 这里最好能动态预测长度
      ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
      ObjectOutputStream oos = new ObjectOutputStream(bos);
      byte[] classNameInBytes = className.getBytes(Encoding.DEFAULT);
      oos.writeInt(classNameInBytes.length);
      oos.write(classNameInBytes);
      mapper.writeValue(oos, value);
      return bos.toByteArray();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 18
0
 /**
  * Saves the hashTable in the file specified by the <i>destination</i>. *
  *
  * @pre destination &ne; null AND location in file system where file is to be created exists AND
  *     the file location is writable AND every object in the ObjectDB is serializable.
  * @post the hashTable has been saved to the file named <i>destination</i> along with the size of
  *     the hashTable.
  */
 public void save(String destination) {
   String fileLocation = DEFAULT_FILE_LOCATION;
   if (FILE_LOCATION != null) {
     fileLocation = FILE_LOCATION;
   }
   if (destination != null) {
     fileLocation = destination;
   }
   try {
     ObjectOutputStream oos =
         new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileLocation)));
     oos.write(LocalObjectId.getNextId());
     oos.writeObject(hashTable);
     oos.flush();
     oos.close();
   } catch (Exception e) {
     System.err.println("In communicator.ObjectDB::save(String) -- ERROR could not save ObjectDB");
   }
 }
Exemplo n.º 19
0
  public static void safeSerialize(ObjectOutputStream out, Serializable data) throws IOException {
    if (data == null) {
      out.writeBoolean(false);
      return;
    } else {
      out.writeBoolean(true);
    }

    byte[] serialData;

    if (data instanceof SerializedData) {
      SerializedData dummyData = (SerializedData) data;
      serialData = dummyData.serialData;
    } else {
      serialData = serialize(data);
      ;
    }

    out.writeInt(serialData.length);

    out.write(serialData);
  }
Exemplo n.º 20
0
 /*     */ private void writeObject(ObjectOutputStream paramObjectOutputStream)
     /*     */ throws IOException
       /*     */ {
   /* 524 */ paramObjectOutputStream.defaultWriteObject();
   /*     */
   /* 526 */ if ((this.certs == null) || (this.certs.length == 0)) {
     /* 527 */ paramObjectOutputStream.writeInt(0);
     /*     */ }
   /*     */ else {
     /* 530 */ paramObjectOutputStream.writeInt(this.certs.length);
     /*     */
     /* 532 */ for (int i = 0; i < this.certs.length; i++) {
       /* 533 */ Certificate localCertificate = this.certs[i];
       /*     */ try {
         /* 535 */ paramObjectOutputStream.writeUTF(localCertificate.getType());
         /* 536 */ byte[] arrayOfByte = localCertificate.getEncoded();
         /* 537 */ paramObjectOutputStream.writeInt(arrayOfByte.length);
         /* 538 */ paramObjectOutputStream.write(arrayOfByte);
         /*     */ } catch (CertificateEncodingException localCertificateEncodingException) {
         /* 540 */ throw new IOException(localCertificateEncodingException.getMessage());
         /*     */ }
       /*     */ }
     /*     */ }
   /*     */ }
Exemplo n.º 21
0
 public void serializeTo(ObjectOutputStream out) throws IOException {
   out.write(root.array());
   out.writeUTF(auxInfoFilename);
   out.writeObject(auxInfoGuids);
   out.writeInt(storage.getStorageTypeId());
 }
Exemplo n.º 22
0
  private void doDownloadFile() throws IOException {
    try {
      final String base = (String) in.readObject(); // 第一次接收信息
      if (base == null) {
        out.write(FileBaseInfo.ANSWER_NO); // 第一次发送信息(取消)
        out.flush();
        return;
      }
      out.write(FileBaseInfo.ANSWER_YES); // 第一次发送信息(继续)
      out.flush();

      final long totalLength = in.readLong(); // 第二次接收信息(总长度)
      log.debug("totalLength : " + totalLength);
      getDisplay()
          .syncExec(
              new Runnable() {
                public void run() {
                  setMaximum(totalLength);
                  lblMsg.setText("Downloading file...");
                }
              });

      while (in.read() == FileBaseInfo.GOON) { // 连续接收信息
        byte fileOrFolder = (byte) in.read();
        String name = (String) in.readObject();
        final File f = new File(base + File.separatorChar + name);
        log.debug("download file: " + f);

        if (fileOrFolder == FileBaseInfo.FOLDER) {
          f.mkdir();
        } else {
          final long length = in.readLong();
          getDisplay()
              .syncExec(
                  new Runnable() {
                    public void run() {
                      lblFile.setText(
                          "File:\""
                              + f.getPath()
                              + "\" Size:"
                              + Util.byteCountToDisplaySize(length));
                    }
                  });
          RandomAccessFile raout = null;
          try {
            raout = new RandomAccessFile(f, "rw");
            StreamUtil2.copy(in, raout, length, FileDownloadShell.this);
          } catch (Exception e) {
            if (running) log.error("establish file error", e);
            f.delete();
            throw e;
          } finally {
            Util.closeQuietly(raout, log);
          }
        }
      }
      getDisplay()
          .syncExec(
              new Runnable() {
                public void run() {
                  lblMsg.setText("Download finished");
                  lblFile.setText("");
                  openFile(base);
                  FileDownloadShell.this.dispose();
                }
              });
    } catch (final Exception e) {
      if (running) {
        log.error("download file error", e);
        getDisplay()
            .syncExec(
                new Runnable() {
                  public void run() {
                    MessageDialog.openError(FileDownloadShell.this, "Error", e.getMessage());
                    FileDownloadShell.this.dispose();
                  }
                });
      }
    }
  }
  /**
   * Send screenshot
   *
   * @param fileName File name
   * @param mSeed World seed
   * @throws IOException
   */
  public void sendScreenShot(String fileName, long mSeed) throws IOException {
    synchronized (out) {
      sendMessage(
          NetworkProtocolHelper.COMMAND_SCREENSHOT_SEND
              + NetworkProtocolHelper.SEPARATOR_COMMAND
              + String.valueOf(mSeed));

      // File to send
      File myFile =
          new File(
              Minecraft.getMinecraft().mcDataDir.getCanonicalPath()
                  + File.separator
                  + "screenshots"
                  + File.separator,
              fileName);
      int fSize = (int) myFile.length();
      if (fSize < myFile.length()) {
        System.out.println("File is too big");
        sendMessage(NetworkProtocolHelper.COMMAND_SCREENSHOT_ERROR);
        return;
      }

      // Send the file's size
      byte[] bSize = new byte[4];
      bSize[0] = (byte) ((fSize & 0xff000000) >> 24);
      bSize[1] = (byte) ((fSize & 0x00ff0000) >> 16);
      bSize[2] = (byte) ((fSize & 0x0000ff00) >> 8);
      bSize[3] = (byte) (fSize & 0x000000ff);
      // 4 bytes containing the file size
      try {
        out.write(bSize, 0, 4);
      } catch (IOException e) {
        e.printStackTrace();
        sendMessage(NetworkProtocolHelper.COMMAND_SCREENSHOT_ERROR);
        return;
      }

      boolean noMemoryLimitation = false;

      FileInputStream fis = null;
      BufferedInputStream bis = null;
      try {
        fis = new FileInputStream(myFile);
        bis = new BufferedInputStream(fis);

        if (noMemoryLimitation) {

          byte[] outBuffer = new byte[fSize];
          int bRead = bis.read(outBuffer, 0, outBuffer.length);
          out.write(outBuffer, 0, bRead);

        } else {

          int bRead = 0;
          byte[] outBuffer = new byte[8 * 1024];
          while ((bRead = bis.read(outBuffer, 0, outBuffer.length)) > 0) {
            out.write(outBuffer, 0, bRead);
          }
        }
        out.flush();
      } catch (IOException e) {
        e.printStackTrace();
        sendMessage(NetworkProtocolHelper.COMMAND_SCREENSHOT_ERROR);
        return;
      } finally {
        try {
          bis.close();
        } catch (IOException e) {
          e.printStackTrace();
        } catch (NullPointerException e) {
          e.printStackTrace();
        }
        sendMessage(
            NetworkProtocolHelper.COMMAND_SCREENSHOT_FINISHED
                + NetworkProtocolHelper.SEPARATOR_COMMAND
                + String.valueOf(mSeed));
      }
    }
  }
Exemplo n.º 24
0
 // Sends the message stored in prefix+message to the server
 public synchronized void sendMessage(byte prefix, byte[] message) throws IOException {
   if (handlers[prefix].shouldSendToSelf()) sendToSelf(prefix, message);
   oos.write(prefix);
   oos.write(message);
   oos.flush();
 }
 @Override
 public void write(byte[] buf, int off, int len) throws IOException {
   out.write(buf, off, len);
 }
 @Override
 public void write(byte[] buf) throws IOException {
   out.write(buf);
 }
 @Override
 public void write(int val) throws IOException {
   out.write(val);
 }