/** * Deserializes an {@link MBeanFeatureInfo} from an {@link ObjectInputStream}. * * @serialData For compatibility reasons, an object of this class is deserialized as follows. * <ul> * The method {@link ObjectInputStream#defaultReadObject defaultReadObject()} is called * first to deserialize the object except the field {@code descriptor}, which is not * serialized in the default way. Then the method {@link ObjectInputStream#read read()} is * called to read a byte, the field {@code descriptor} is deserialized according to the * value of the byte value: * <ul> * <li>1. The method {@link ObjectInputStream#readObject readObject()} is called twice to * obtain the field names (a {@code String[]}) and the field values (a {@code * Object[]}) of the {@code descriptor}. The two obtained values then are used to * construct an {@link ImmutableDescriptor} instance for the field {@code descriptor}; * <li>0. The value for the field {@code descriptor} is obtained directly by calling the * method {@link ObjectInputStream#readObject readObject()}. If the obtained value is * null, the field {@code descriptor} is set to {@link * ImmutableDescriptor#EMPTY_DESCRIPTOR EMPTY_DESCRIPTOR}; * <li>-1. This means that there is no byte to read and that the object is from an earlier * version of the JMX API. The field {@code descriptor} is set to {@link * ImmutableDescriptor#EMPTY_DESCRIPTOR EMPTY_DESCRIPTOR} * <li>Any other value. A {@link StreamCorruptedException} is thrown. * </ul> * </ul> * * @since 1.6 */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); switch (in.read()) { case 1: final String[] names = (String[]) in.readObject(); if (names.length == 0) { descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR; } else { final Object[] values = (Object[]) in.readObject(); descriptor = new ImmutableDescriptor(names, values); } break; case 0: descriptor = (Descriptor) in.readObject(); if (descriptor == null) { descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR; } break; case -1: // from an earlier version of the JMX API descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR; break; default: throw new StreamCorruptedException("Got unexpected byte."); } }
public static Serializable safeDeserialize(ObjectInputStream in) throws IOException { if (!in.readBoolean()) { return null; } int length = in.readInt(); if (length > buffer.length - 4) { buffer = new byte[length]; } in.read(buffer, 0, length); buffer[length] = (byte) 0xFF; buffer[length + 1] = (byte) 0xFF; buffer[length + 2] = (byte) 0xFF; buffer[length + 3] = (byte) 0xFF; Serializable object; try { object = deserializeRaw(buffer); } catch (ClassNotFoundException cnfe) { SerializedData dummy = new SerializedData(); dummy.serialData = Arrays.copyOf(buffer, length); object = dummy; } return object; }
/** 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(); }
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(); }
public void objectInputStreamNotClosedAfterRead() { ObjectInputStream oin; try { oin = new ObjectInputStream(new FileInputStream("file.txt")); oin.read(); oin.close(); } catch (IOException e) { } }
/** 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)); }
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); int length = in.readInt(); if (length != 0) { byte[] json = new byte[length]; in.read(json); Schema schema = new Schema.Parser().parse(new String(json)); setSchema(schema); } }
@SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { try { in.read(new byte["factory".length()], 0, "factory".length()); in.read(); // ':' int length = in.readInt(); in.read(); // ':' byte[] factoryName = new byte[length]; in.read(factoryName, 0, length); in.read(); // ':' Class<?> clazz = getClass().getClassLoader().loadClass(new String(factoryName, "UTF8")); this.vf = (IValueFactory) clazz.getMethod("getInstance").invoke(null, new Object[0]); this.value = (T) new BinaryValueReader().read(vf, in); } catch (InvocationTargetException | IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | ClassCastException e) { throw new IOException("Could not load IValueFactory", e); } }
/** * Constructor that takes existing the signature data * * @param sigData Existing signature data * @throws OpenStegoException */ public Signature(byte[] sigData) throws OpenStegoException { ObjectInputStream ois = null; byte[] inputSig = new byte[this.sig.length]; try { ois = new ObjectInputStream(new ByteArrayInputStream(sigData)); ois.read(inputSig, 0, this.sig.length); if (!(new String(this.sig)).equals(new String(inputSig))) { throw new OpenStegoException(null, NAMESPACE, DWTXieErrors.ERR_SIG_NOT_VALID); } this.watermarkLength = ois.readInt(); this.embeddingStrength = ois.readDouble(); this.waveletFilterMethod = ois.readInt(); this.filterID = ois.readInt(); this.embeddingLevel = ois.readInt(); this.watermark = new byte[this.watermarkLength]; ois.read(this.watermark); } catch (IOException ioEx) { throw new OpenStegoException(ioEx); } }
@Override public Object decode(byte[] data) { try { ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(data)); int classNameLength = oin.readInt(); byte[] buff = new byte[classNameLength]; oin.read(buff); String className = new String(buff, Encoding.DEFAULT); Class<?> klass = Class.forName(className); return mapper.readValue(oin, klass); } catch (Exception e) { throw new RuntimeException(e); } }
public static Download createFrom(ObjectInputStream in, DownloadManager m) throws IOException { try { Hash h = new Hash(); int r = in.read(h.array()); String fn = in.readUTF(); ArrayList<Integer> guids = (ArrayList<Integer>) in.readObject(); if (T.t) { T.ass(r == h.array().length, "Incorrect length when deserializing download"); } BlockStorage bs = BlockStorage.getById(m.getCore(), in.readInt()); Download d = new Download(m, h, bs, fn, guids); d.fd = d.manager.getCore().getFileManager().getFd(h); return d; } catch (ClassNotFoundException e) { throw new IOException("Could not find class while deserializing: " + e); } }
private synchronized void startListener() { byte[] buffer = new byte[1024]; int tamanhoBuffer; while (true) { try { ObjectInputStream ois = new ObjectInputStream(streamDeEntrada); tamanhoBuffer = ois.read(buffer); // tamanhoBuffer = streamDeEntrada.read(buffer); this.handle .obtainMessage(ManipuladorProtocolo.RECEBER_MENSAGEM, tamanhoBuffer, -1, buffer) .sendToTarget(); buffer = new byte[1024]; } catch (IOException e) { Log.e(TAG, "Um erro ocorreu enquanto recebia dados.", e); break; } } }
/** * Retrieves the hashTable from the file specified by <i>source</i>. * * @param source the name of the file from which the hashTable is to be retrieved. * @pre <i>None</i> * @post If there is any error ⇒ LocalObjectId.nextId = LocalObjectId.INITIAL_ID and * |hashTable| = 0 Else the hashTable in the specified file is retrieved and stored in * hashTable AND LocalObjectId.nextId = |hashTable| */ public void restore(String source) { String fileLocation = DEFAULT_FILE_LOCATION; if (FILE_LOCATION != null) { fileLocation = FILE_LOCATION; } if (source != null) { fileLocation = source; } try { ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(fileLocation))); int nextId = ois.read(); LocalObjectId.setNextId(nextId); hashTable = (Hashtable<LocalObjectId, Object>) ois.readObject(); ois.close(); } catch (Exception e) { LocalObjectId.setNextId(LocalObjectId.INITIAL_ID); hashTable = new Hashtable<LocalObjectId, Object>(); } }
@Override public SecretKey loadKey() throws KeyLoadingException { // try to load key from file File keyFile = new File(FileSystemService.getUserRapidMinerDir(), DEFAULTKEY_FILE_NAME); try (FileInputStream fis = new FileInputStream(keyFile); ObjectInputStream in = new ObjectInputStream(fis)) { int length = in.readInt(); byte[] rawKey = new byte[length]; int actualLength = in.read(rawKey); if (length != actualLength) { throw new IOException("Cannot read key file (unexpected length)"); } return KeyGeneratorTool.makeKey(rawKey); } catch (IOException e) { // catch to log the problem, then throw again to indicate error LogService.getRoot() .log( Level.WARNING, "com.rapidminer.tools.cipher.KeyGeneratorTool.read_key_error", e.getMessage()); throw new KeyLoadingException("Cannot retrieve key: " + e.getMessage()); } }
/** * Reads a serialized simple time zone from stream. * * @see #writeObject */ private void readObject(java.io.ObjectInputStream input) throws java.io.IOException, ClassNotFoundException { input.defaultReadObject(); if (serialVersionOnStream == 0) { // initialize the new fields to default values. dstSavings = 60 * 60 * 1000; endMode = DOW_IN_MONTH_MODE; startMode = DOW_IN_MONTH_MODE; serialVersionOnStream = 1; } else { int length = input.readInt(); byte[] byteArray = new byte[length]; input.read(byteArray, 0, length); if (length >= 4) { // Lets hope that Sun does extensions to the serialized // form in a sane manner. startDay = byteArray[0]; startDayOfWeek = byteArray[1]; endDay = byteArray[2]; endDayOfWeek = byteArray[3]; } } }
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { String remote = in.readUTF(); String ext = ".data"; int dot = remote.lastIndexOf('.'); if (dot > 0) { ext = remote.substring(dot); remote = remote.substring(0, dot); } localPath = File.createTempFile(remote, ext); FileOutputStream fos = new FileOutputStream(localPath); try { long length = in.readLong(); byte[] xfer = new byte[4096]; while (length > 0) { int read = in.read(xfer, 0, (int) Math.min(xfer.length, length)); if (read < 0) throw new EOFException("Unexpected EOF (" + length + " bytes remaining)"); fos.write(xfer, 0, read); length -= read; } } finally { fos.close(); } }
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(); } }); } } }
/** The run method. */ public void run() { instances.add(this); try { listener.startUnpack(); String currentOs = System.getProperty("os.name").toLowerCase(); // // Initialisations FileOutputStream out = null; ArrayList parsables = new ArrayList(); ArrayList executables = new ArrayList(); List packs = idata.selectedPacks; int npacks = packs.size(); udata = UninstallData.getInstance(); // Specific to the web installers if (idata.kind.equalsIgnoreCase("web") || idata.kind.equalsIgnoreCase("web-kunststoff")) { InputStream kin = getClass().getResourceAsStream("/res/WebInstallers.url"); BufferedReader kreader = new BufferedReader(new InputStreamReader(kin)); jarLocation = kreader.readLine(); } // We unpack the selected packs for (int i = 0; i < npacks; i++) { // We get the pack stream int n = idata.allPacks.indexOf(packs.get(i)); ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(n)); // We unpack the files int nfiles = objIn.readInt(); listener.changeUnpack(0, nfiles, ((Pack) packs.get(i)).name); for (int j = 0; j < nfiles; j++) { // We read the header PackFile pf = (PackFile) objIn.readObject(); if (null == pf.os || matchOS(currentOs, pf.os.toLowerCase())) { // We translate & build the path String path = translatePath(pf.targetPath); File pathFile = new File(path); String fname = pathFile.getName(); int z = fname.length(); File dest = pathFile.getParentFile(); if (!dest.exists()) dest.mkdirs(); // We add the path to the log, udata.addFile(path); listener.progressUnpack(j, path); // if this file exists and shouldnot override skip this file if (((pf.override == false) && (pathFile.exists()))) { objIn.skip(pf.length); continue; } // We copy the file out = new FileOutputStream(path); byte[] buffer = new byte[5120]; long bytesCopied = 0; while (bytesCopied < pf.length) { int maxBytes = (pf.length - bytesCopied < buffer.length ? (int) (pf.length - bytesCopied) : buffer.length); int bytesInBuffer = objIn.read(buffer, 0, maxBytes); if (bytesInBuffer == -1) throw new IOException("Unexpected end of stream"); out.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } // Cleanings out.close(); // Empty dirs restoring String _n = pathFile.getName(); if (_n.startsWith("izpack-keepme") && _n.endsWith(".tmp")) pathFile.delete(); } else objIn.skip(pf.length); } // Load information about parsable files int numParsables = objIn.readInt(); int k; for (k = 0; k < numParsables; k++) { ParsableFile pf = (ParsableFile) objIn.readObject(); pf.path = translatePath(pf.path); parsables.add(pf); } // Load information about executable files int numExecutables = objIn.readInt(); for (k = 0; k < numExecutables; k++) { ExecutableFile ef = (ExecutableFile) objIn.readObject(); ef.path = translatePath(ef.path); if (null != ef.argList && !ef.argList.isEmpty()) { String arg = null; for (int j = 0; j < ef.argList.size(); j++) { arg = (String) ef.argList.get(j); arg = translatePath(arg); ef.argList.set(j, arg); } } executables.add(ef); if (ef.executionStage == ExecutableFile.UNINSTALL) { udata.addExecutable(ef); } } objIn.close(); } // We use the scripts parser ScriptParser parser = new ScriptParser(parsables, vs); parser.parseFiles(); // We use the file executor FileExecutor executor = new FileExecutor(executables); if (executor.executeFiles(ExecutableFile.POSTINSTALL) != 0) javax.swing.JOptionPane.showMessageDialog( null, "The installation was not completed.", "Installation warning", javax.swing.JOptionPane.WARNING_MESSAGE); // We put the uninstaller putUninstaller(); // The end :-) listener.stopUnpack(); } catch (Exception err) { listener.stopUnpack(); listener.errorUnpack(err.toString()); } instances.remove(instances.indexOf(this)); }