Пример #1
0
            /// <exception cref="System.IO.IOException"/>
            private static void ReadContainerLogs(DataInputStream valueStream, TextWriter @out
                                                  , long logUploadedTime)
            {
                byte[] buf           = new byte[65535];
                string fileType      = valueStream.ReadUTF();
                string fileLengthStr = valueStream.ReadUTF();
                long   fileLength    = long.Parse(fileLengthStr);

                @out.Write("LogType:");
                @out.WriteLine(fileType);
                if (logUploadedTime != -1)
                {
                    @out.Write("Log Upload Time:");
                    @out.WriteLine(Times.Format(logUploadedTime));
                }
                @out.Write("LogLength:");
                @out.WriteLine(fileLengthStr);
                @out.WriteLine("Log Contents:");
                long curRead     = 0;
                long pendingRead = fileLength - curRead;
                int  toRead      = pendingRead > buf.Length ? buf.Length : (int)pendingRead;
                int  len         = valueStream.Read(buf, 0, toRead);

                while (len != -1 && curRead < fileLength)
                {
                    @out.Write(buf, 0, len);
                    curRead    += len;
                    pendingRead = fileLength - curRead;
                    toRead      = pendingRead > buf.Length ? buf.Length : (int)pendingRead;
                    len         = valueStream.Read(buf, 0, toRead);
                }
                @out.WriteLine("End of LogType:" + fileType);
                @out.WriteLine(string.Empty);
            }
Пример #2
0
            /// <exception cref="System.IO.IOException"/>
            public override int Read()
            {
                if (CheckEOF())
                {
                    return(-1);
                }
                int ret = @in.Read();

                if (ret < 0)
                {
                    throw new IOException("Corrupted chunk encoding stream");
                }
                --remain;
                return(ret);
            }
Пример #3
0
 /*
  * Reads the information from the index and data files.
  *
  * @param index holds the sprite indices
  * @param data  holds the sprite data per index
  * @throws IOException
  */
 public void readValues(DataInputStream index, DataInputStream data)
 {
     do
     {
         int opCode = data.ReadByte();
         if (opCode == 0)
         {
             break;
         }
         if (opCode == 1)
         {
             id = data.ReadShort();
         }
         else if (opCode == 2)
         {
             name = data.ReadUTF();
         }
         else if (opCode == 3)
         {
             drawOffsetX = data.ReadShort();
         }
         else if (opCode == 4)
         {
             drawOffsetY = data.ReadShort();
         }
         else if (opCode == 5)
         {
             int    indexLength = index.ReadInt();
             byte[] dataread    = new byte[indexLength];
             data.Read(dataread, 0, indexLength);
             spriteData = dataread;
         }
     } while (true);
 }
        /// <exception cref="System.IO.IOException"/>
        private void ProcessTokenAddOrUpdate(ChildData data)
        {
            ByteArrayInputStream bin   = new ByteArrayInputStream(data.GetData());
            DataInputStream      din   = new DataInputStream(bin);
            TokenIdent           ident = CreateIdentifier();

            ident.ReadFields(din);
            long renewDate = din.ReadLong();
            int  pwdLen    = din.ReadInt();

            byte[] password = new byte[pwdLen];
            int    numRead  = din.Read(password, 0, pwdLen);

            if (numRead > -1)
            {
                AbstractDelegationTokenSecretManager.DelegationTokenInformation tokenInfo = new AbstractDelegationTokenSecretManager.DelegationTokenInformation
                                                                                                (renewDate, password);
                lock (this)
                {
                    currentTokens[ident] = tokenInfo;
                    // The cancel task might be waiting
                    Runtime.NotifyAll(this);
                }
            }
        }
Пример #5
0
        /// <summary>Read word vectors from an input stream.</summary>
        /// <remarks>Read word vectors from an input stream. The stream is not closed on finishing the function.</remarks>
        /// <param name="in">The stream to read from. This is not closed.</param>
        /// <returns>The word vectors encoded on the stream.</returns>
        /// <exception cref="System.IO.IOException">Thrown if we could not read from the stream.</exception>
        public static VectorMap Deserialize(InputStream @in)
        {
            DataInputStream dataIn = new DataInputStream(@in);

            // Read the max key length
            VectorMap.Itype keyIntType = VectorMap.Itype.GetType(dataIn.ReadInt());
            // Read the vector dimensionality
            int dim = dataIn.ReadInt();
            // Read the size of the dataset
            int size = dataIn.ReadInt();
            // Read the vectors
            VectorMap vectors = new VectorMap();

            for (int i = 0; i < size; ++i)
            {
                // Read the key
                int    strlen = keyIntType.Read(dataIn);
                byte[] buffer = new byte[strlen];
                if (dataIn.Read(buffer, 0, strlen) != strlen)
                {
                    throw new IOException("Could not read string buffer fully!");
                }
                string key = Sharpen.Runtime.GetStringForBytes(buffer);
                // Read the vector
                float[] vector = new float[dim];
                for (int k = 0; k < vector.Length; ++k)
                {
                    vector[k] = ToFloat(dataIn.ReadShort());
                }
                // Add the key/value
                vectors[key] = vector;
            }
            return(vectors);
        }
Пример #6
0
        /// <exception cref="System.IO.IOException"/>
        public static float[] ReadFloatArr(DataInputStream rf)
        {
            int size = rf.ReadInt();

            byte[] b = new byte[4 * size];
            rf.Read(b);
            return(ByteArrToFloatArr(b));
        }
Пример #7
0
        /// <exception cref="System.IO.IOException"/>
        public static double[] ReadDoubleArr(DataInputStream rf)
        {
            int size = rf.ReadInt();

            byte[] b = new byte[8 * size];
            rf.Read(b);
            return(ByteArrToDoubleArr(b));
        }
Пример #8
0
        /// <exception cref="System.IO.IOException"/>
        private void ReadFile(FileSystem fileSys, Path name)
        {
            //Just read file so that getNumBlockLocations are incremented
            DataInputStream stm = fileSys.Open(name);

            byte[] buffer = new byte[4];
            stm.Read(buffer, 0, 4);
            stm.Close();
        }
Пример #9
0
        /// <exception cref="System.IO.IOException"/>
        private void ReadFile(FileSystem fileSys, Path name)
        {
            DataInputStream stm = fileSys.Open(name);

            byte[] buffer    = new byte[4];
            int    bytesRead = stm.Read(buffer, 0, 4);

            NUnit.Framework.Assert.AreEqual("oom", Sharpen.Runtime.GetStringForBytes(buffer,
                                                                                     0, bytesRead));
            stm.Close();
        }
Пример #10
0
        public void handle(byte[] data, model.RtpMidiServer appleMidiServer)
        {
            DataInputStream dataInputStream = new DataInputStream(new MemoryStream(data));

            try {
                byte header1 = (byte)dataInputStream.ReadByte();
                if (header1 != RtpMidiCommand.MIDI_COMMAND_HEADER1)
                {
                    Log.Info("RtpMidi", "Header did not contain first MIDI command header");
                    return;
                }
                byte header2 = (byte)dataInputStream.ReadByte();
                if (header2 != RtpMidiCommand.MIDI_COMMAND_HEADER2)
                {
                    Log.Info("RtpMidi", "Header did not contain second MIDI command header");
                    return;
                }
                byte[] commandBuffer    = new byte[COMMAND_BUFFER_LENGTH];
                int    commandBytesRead = dataInputStream.Read(commandBuffer);
                if (commandBytesRead != COMMAND_BUFFER_LENGTH)
                {
                    Log.Info("RtpMidi", "The number of command bytes: {} did not match: {}", commandBytesRead, COMMAND_BUFFER_LENGTH);
                    return;
                }
                string      command = Encoding.UTF8.GetString(commandBuffer);
                CommandWord commandWord;
                try
                {
                    commandWord = (CommandWord)System.Enum.Parse(typeof(CommandWord), command);
                }
                catch (IllegalArgumentException e) {
                    Log.Info("RtpMidi", "Could not parse command word from: {}", command);
                    return;
                }
                switch (commandWord)
                {
                case CommandWord.IN:
                    HandleInvitation(dataInputStream, appleMidiServer);
                    break;

                case CommandWord.CK:
                    HandleSynchronization(dataInputStream, appleMidiServer);
                    break;

                case CommandWord.BY:
                    HandleEndSession(dataInputStream, appleMidiServer);
                    break;
                }
            }
            catch (System.IO.IOException e)
            {
                Log.Error("RtpMidi", "IOException while parsing message", e);
            }
        }
Пример #11
0
        public virtual void TestCompressorDecopressorLogicWithCompressionStreams()
        {
            DataOutputStream deflateOut = null;
            DataInputStream  inflateIn  = null;
            int ByteSize = 1024 * 100;

            byte[] bytes               = Generate(ByteSize);
            int    bufferSize          = 262144;
            int    compressionOverhead = (bufferSize / 6) + 32;

            try
            {
                DataOutputBuffer        compressedDataBuffer = new DataOutputBuffer();
                CompressionOutputStream deflateFilter        = new BlockCompressorStream(compressedDataBuffer
                                                                                         , new Lz4Compressor(bufferSize), bufferSize, compressionOverhead);
                deflateOut = new DataOutputStream(new BufferedOutputStream(deflateFilter));
                deflateOut.Write(bytes, 0, bytes.Length);
                deflateOut.Flush();
                deflateFilter.Finish();
                DataInputBuffer deCompressedDataBuffer = new DataInputBuffer();
                deCompressedDataBuffer.Reset(compressedDataBuffer.GetData(), 0, compressedDataBuffer
                                             .GetLength());
                CompressionInputStream inflateFilter = new BlockDecompressorStream(deCompressedDataBuffer
                                                                                   , new Lz4Decompressor(bufferSize), bufferSize);
                inflateIn = new DataInputStream(new BufferedInputStream(inflateFilter));
                byte[] result = new byte[ByteSize];
                inflateIn.Read(result);
                Assert.AssertArrayEquals("original array not equals compress/decompressed array",
                                         result, bytes);
            }
            catch (IOException)
            {
                NUnit.Framework.Assert.Fail("testLz4CompressorDecopressorLogicWithCompressionStreams ex error !!!"
                                            );
            }
            finally
            {
                try
                {
                    if (deflateOut != null)
                    {
                        deflateOut.Close();
                    }
                    if (inflateIn != null)
                    {
                        inflateIn.Close();
                    }
                }
                catch (Exception)
                {
                }
            }
        }
Пример #12
0
 /// <summary>Reads the next byte of data from this input stream.</summary>
 /// <remarks>
 /// Reads the next byte of data from this input stream. The value byte is
 /// returned as an <code>int</code> in the range <code>0</code> to
 /// <code>255</code>. If no byte is available because the end of the stream has
 /// been reached, the value <code>-1</code> is returned. This method blocks
 /// until input data is available, the end of the stream is detected, or an
 /// exception is thrown.
 /// <p>
 /// </remarks>
 /// <returns>
 /// the next byte of data, or <code>-1</code> if the end of the stream
 /// is reached.
 /// </returns>
 /// <exception>
 /// IOException
 /// if an I/O error occurs.
 /// </exception>
 /// <exception cref="System.IO.IOException"/>
 public override int Read()
 {
     if (!useWrap)
     {
         return(inStream.Read());
     }
     if (ostart >= ofinish)
     {
         // we loop for new data as we are blocking
         int i = 0;
         while (i == 0)
         {
             i = ReadMoreData();
         }
         if (i == -1)
         {
             return(-1);
         }
     }
     return((int)obuffer[ostart++] & unchecked ((int)(0xff)));
 }
Пример #13
0
 /// <summary>
 /// Reads all remaining bytes from an input stream and returns
 /// them as a byte array.
 /// </summary>
 /// <param name="input">The input stream.</param>
 /// <returns>Reads all remaining bytes from an input stream and returns
 /// them as a byte array.</returns>
 /// <exception cref="IOException">Rethrown if an I/O exception occurs.</exception>
 internal static byte[] ReadRemaining(DataInputStream input)
 {
     using (var baos = new MemoryStream())
     {
         byte[] buffer = new byte[1024 * 8];
         int    len;
         while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
         {
             baos.Write(buffer, 0, len);
         }
         return(baos.ToArray());
     }
 }
Пример #14
0
        /// <exception cref="System.IO.IOException"/>
        private static bool IsSequenceFile(FileSystem fs, Path f)
        {
            DataInputStream @in = fs.Open(f);

            byte[] seq = Sharpen.Runtime.GetBytesForString("SEQ");
            for (int i = 0; i < seq.Length; ++i)
            {
                if (seq[i] != @in.Read())
                {
                    return(false);
                }
            }
            return(true);
        }
Пример #15
0
        /* (non-Javadoc)
         * @see org.gogpsproject.Streamable#read(java.io.DataInputStream)
         */
        public void read(DataInputStream dai, bool oldVersion)
        {
            int v = 1;

            if (!oldVersion)
            {
                v = dai.ReadInt();
            }

            if (v == 1)
            {
                long l = dai.ReadLong();
                refTime  = new Time(l > 0 ? l : GetCurrentMilli());
                satID    = dai.Read();
                week     = dai.ReadInt();
                L2Code   = dai.ReadInt();
                L2Flag   = dai.ReadInt();
                svAccur  = dai.ReadInt();
                svHealth = dai.ReadInt();
                iode     = dai.ReadInt();
                iodc     = dai.ReadInt();
                toc      = dai.ReadDouble();
                toe      = dai.ReadDouble();
                af0      = dai.ReadDouble();
                af1      = dai.ReadDouble();
                af2      = dai.ReadDouble();
                tgd      = dai.ReadDouble();
                rootA    = dai.ReadDouble();
                e        = dai.ReadDouble();
                i0       = dai.ReadDouble();
                iDot     = dai.ReadDouble();
                omega    = dai.ReadDouble();
                omega0   = dai.ReadDouble();
                omegaDot = dai.ReadDouble();
                M0       = dai.ReadDouble();
                deltaN   = dai.ReadDouble();
                crc      = dai.ReadDouble();
                crs      = dai.ReadDouble();
                cuc      = dai.ReadDouble();
                cus      = dai.ReadDouble();
                cic      = dai.ReadDouble();
                cis      = dai.ReadDouble();
                fitInt   = dai.ReadLong();
            }
            else
            {
                throw new IOException("Unknown format version:" + v);
            }
        }
            /// <exception cref="System.IO.IOException"/>
            public virtual FileSystemApplicationHistoryStore.HistoryFileReader.Entry Next()
            {
                TFile.Reader.Scanner.Entry entry = this.scanner.Entry();
                DataInputStream            dis   = entry.GetKeyStream();

                FileSystemApplicationHistoryStore.HistoryDataKey key = new FileSystemApplicationHistoryStore.HistoryDataKey
                                                                           ();
                key.ReadFields(dis);
                dis = entry.GetValueStream();
                byte[] value = new byte[entry.GetValueLength()];
                dis.Read(value);
                this.scanner.Advance();
                return(new FileSystemApplicationHistoryStore.HistoryFileReader.Entry(this, key, value
                                                                                     ));
            }
Пример #17
0
        /// <summary>
        /// 读取数据流
        /// </summary>
        ///
        /// <param name="dis"></param>
        /// <param name="header"></param>
        /// <param name="fileTable"></param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static byte[] ReadFileFromPak(DataInputStream dis, LPKHeader header,
                                             LPKTable fileTable)
        {
            dis.Skip(fileTable.GetOffSet() - OutputOffset(header));
            int fileLength = (int)fileTable.GetFileSize();

            byte[] fileBuff   = new byte[fileLength];
            int    readLength = dis.Read(fileBuff, 0, fileLength);

            if (readLength < fileLength)
            {
                return(null);
            }
            else
            {
                MakeBuffer(fileBuff, readLength);
                return(fileBuff);
            }
        }
Пример #18
0
        /// <exception cref="System.IO.IOException"/>
        private void SomeReadingWithMetaBlock(TFile.Reader reader)
        {
            DataInputStream din = null;

            ReadNumMetablocks(reader, 10);
            try
            {
                din = reader.GetMetaBlock("NO ONE");
                Assert.True(false);
            }
            catch (MetaBlockDoesNotExist)
            {
            }
            // should catch
            din = reader.GetMetaBlock("TFileMeta100");
            int read = din.Read();

            Assert.True("check for status", (read == -1));
            din.Close();
        }
Пример #19
0
        private void HandleSynchronization(DataInputStream dataInputStream, model.RtpMidiServer rtpMidiServer)
        {
            int  ssrc         = dataInputStream.ReadInt();
            byte count        = (byte)dataInputStream.ReadByte();
            int  paddingBytes = dataInputStream.Read(new byte[NUMBER_OF_PADDING_BYTES]);

            if (paddingBytes != NUMBER_OF_PADDING_BYTES)
            {
                Log.Info("RtpMidi", "The number of padding bytes: {} did not match: {}", paddingBytes, NUMBER_OF_PADDING_BYTES);
                return;
            }
            long timestamp1 = dataInputStream.ReadLong();
            long timestamp2 = dataInputStream.ReadLong();
            long timestamp3 = dataInputStream.ReadLong();

            foreach (IRtpMidiCommandListener listener in listeners)
            {
                listener.OnClockSynchronization(new RtpMidiClockSynchronization(ssrc, count, timestamp1, timestamp2, timestamp3), rtpMidiServer);
            }
        }
Пример #20
0
        private void Read()
        {
            int bytes = 0;

            byte[] buffer = new byte[32];
            isReading = true;

            while (isReading)
            {
                try
                {
                    bytes = mInputStream.Read(buffer);
                    Java.Lang.String str = new Java.Lang.String(buffer, 0, bytes);
                    mSaveLastMessage(str.ToString());
                }
                catch (Java.Lang.Exception ex)
                {
                    Log.Debug("WifiSocketReader", "Error while reading");
                }
            }
        }
        /// <exception cref="System.IO.IOException"/>
        private AbstractDelegationTokenSecretManager.DelegationTokenInformation GetTokenInfoFromZK
            (TokenIdent ident, bool quiet)
        {
            string nodePath = GetNodePath(ZkDtsmTokensRoot, DelegationTokenPrefix + ident.GetSequenceNumber
                                              ());

            try
            {
                byte[] data = zkClient.GetData().ForPath(nodePath);
                if ((data == null) || (data.Length == 0))
                {
                    return(null);
                }
                ByteArrayInputStream bin = new ByteArrayInputStream(data);
                DataInputStream      din = new DataInputStream(bin);
                CreateIdentifier().ReadFields(din);
                long   renewDate = din.ReadLong();
                int    pwdLen    = din.ReadInt();
                byte[] password  = new byte[pwdLen];
                int    numRead   = din.Read(password, 0, pwdLen);
                if (numRead > -1)
                {
                    AbstractDelegationTokenSecretManager.DelegationTokenInformation tokenInfo = new AbstractDelegationTokenSecretManager.DelegationTokenInformation
                                                                                                    (renewDate, password);
                    return(tokenInfo);
                }
            }
            catch (KeeperException.NoNodeException)
            {
                if (!quiet)
                {
                    Log.Error("No node in path [" + nodePath + "]");
                }
            }
            catch (Exception ex)
            {
                throw new IOException(ex);
            }
            return(null);
        }
Пример #22
0
 protected internal virtual void Read(DataInputStream rf)
 {
     try
     {
         int    len  = rf.ReadInt();
         byte[] buff = new byte[len];
         if (rf.Read(buff) != len)
         {
             log.Info("Error: rewrite CountWrapper.read");
         }
         word = Sharpen.Runtime.GetStringForBytes(buff);
         System.Diagnostics.Debug.Assert((word != null));
         countPart = rf.ReadInt();
         countThat = rf.ReadInt();
         countIn   = rf.ReadInt();
         countRB   = rf.ReadInt();
     }
     catch (IOException e)
     {
         Sharpen.Runtime.PrintStackTrace(e);
     }
 }
Пример #23
0
        private void ReadFromDisk(System.IO.IsolatedStorage.IsolatedStorageFile iso, string storeFile)
        {
            DataInputStream dis = FileUtils.ReadIsolatedStorageFileToDataInput(iso, storeFile);

            try
            {
                string header = dis.ReadUTF();
                if (!header.Equals(HEADER))
                {
                    throw new RecordStoreException("Store file header mismatch: " + header);
                }
                nextRecordId = dis.ReadInt();
                int size = dis.ReadInt();
                records.Clear();
                for (int i = 0; i < size; i++)
                {
                    long   pSize  = dis.ReadLong();
                    int    pId    = dis.ReadInt();
                    byte[] buffer = new byte[pSize];
                    dis.Read(buffer);
                    RecordItem ri = new RecordItem(pId, buffer);
                    records.Add(ri);
                }
            }
            catch (Exception e)
            {
                throw new RecordStoreException("ERROR reading store from disk (" + storeFile + "): " + e.StackTrace);
            }
            finally
            {
                if (dis != null)
                {
                    dis.Close();
                    dis = null;
                }
            }
        }
Пример #24
0
        public void Handle(byte[] data, RtpMidiServer rtpMidiServer)
        {
            DataInputStream dataInputStream = new DataInputStream(new MemoryStream(data));
            byte            header1         = (byte)dataInputStream.ReadByte();
            byte            version         = (byte)((header1 >> 6) & 0x03);
            bool            paddingFlag     = ((header1 >> 5) & 0x01) == 1;
            bool            extensionFlag   = ((header1 >> 4) & 0x01) == 1;
            byte            contributingSourceIdentifiersCount = (byte)(header1 & 0x0F);

            byte header2     = (byte)dataInputStream.ReadByte();
            bool markerFlag  = ((header2 >> 7) & 0x01) == 1;
            byte payloadType = (byte)(header2 & 0x7F);

            if (payloadType != RTP_MIDI)
            {
                return;
            }

            short sequenceNumber = dataInputStream.ReadShort();
            int   timestamp      = dataInputStream.ReadInt();
            int   ssrc           = dataInputStream.ReadInt();

            RtpHeader rtpHeader = new RtpHeader(version, paddingFlag, extensionFlag, contributingSourceIdentifiersCount, markerFlag,
                                                payloadType, sequenceNumber, timestamp, ssrc);

            byte midiCommandHeader1 = (byte)dataInputStream.ReadByte();
            bool b = ((midiCommandHeader1 >> 7) & 0x01) == 1;
            bool j = ((midiCommandHeader1 >> 6) & 0x01) == 1;
            bool z = ((midiCommandHeader1 >> 5) & 0x01) == 1;
            bool p = ((midiCommandHeader1 >> 4) & 0x01) == 1;
            // Header 2 octets
            short length;

            if (b)
            {
                byte midiCommandHeader2 = (byte)dataInputStream.ReadByte();
                length = (short)((midiCommandHeader1 << 8 | midiCommandHeader2) & 0x0FFF);
            }
            else
            {
                length = (short)(midiCommandHeader1 & 0x0F);
            }

            MidiCommandHeader midiCommandHeader = new MidiCommandHeader(b, j, z, p, length, rtpHeader);

            byte[] midiCommandBuffer    = new byte[length];
            int    midiCommandBytesRead = dataInputStream.Read(midiCommandBuffer);

            if (((short)midiCommandBytesRead) != length)
            {
                return;
            }

            List <MidiTimestampPair> messages = new List <MidiTimestampPair>();

            try
            {
                DataInputStream midiInputStream = new DataInputStream(new MemoryStream(midiCommandBuffer));
                messages.AddRange(ReadMidiMessages(midiCommandHeader, midiInputStream));
                HandleMessage(new RtpMidiMessage(midiCommandHeader, messages));
            }
            catch (System.IO.IOException e)
            {
                Log.Error("RtpMidi", "IOException while processing MIDI message", e);
            }
        }
Пример #25
0
        static void LoadResToCache()
        {
            string loon_default_font       = "lfcache";
            IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication();

            if (!isoStorage.FileExists(loon_default_font))
            {
                IsolatedStorageFileStream outStream = isoStorage.CreateFile(loon_default_font);
                Stream gzip = null;
                try
                {
                    gzip = new GZipInputStream(XNAConfig.LoadStream(LSystem.FRAMEWORK_IMG_NAME + "font.zip"));
                    byte[] buffer = new byte[4096];
                    int    charsRead;
                    while ((charsRead = gzip.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        outStream.Write(buffer, 0, charsRead);
                    }
                    outStream.Flush();
                    if (gzip != null)
                    {
                        gzip.Close();
                        gzip.Dispose();
                        gzip = null;
                    }
                    buffer = null;
                }
                catch (Exception)
                {
                    if (outStream != null)
                    {
                        outStream.Close();
                        outStream.Dispose();
                        outStream = null;
                    }
                    if (gzip != null)
                    {
                        gzip.Close();
                        gzip.Dispose();
                        gzip = null;
                    }
                    IsolatedStorageFile.GetUserStoreForApplication().DeleteFile(loon_default_font);
                }
                finally
                {
                    if (outStream != null)
                    {
                        outStream.Close();
                        outStream = null;
                    }
                }
            }
            Stream ins = null;

            try
            {
                ins = isoStorage.OpenFile(loon_default_font, FileMode.Open);
                DataInputStream resStream = new DataInputStream(ins);
                realsize  = resStream.ReadUnsignedByte();
                offy      = resStream.ReadByte();
                fontSpace = (realsize + offy) * 2;
                if (realsize > 0x10)
                {
                    fontSpace *= 2;
                }
                int    num        = resStream.ReadInt();
                int    num2       = resStream.ReadByte();
                byte[] bufferData = new byte[resStream.Available()];
                resStream.Read(bufferData);
                fontData = bufferData;
                if (resStream != null)
                {
                    resStream.Close();
                    resStream = null;
                }
            }
            catch (Exception)
            {
                fontData = null;
                if (ins != null)
                {
                    ins.Close();
                    ins.Dispose();
                    ins = null;
                }
                LoadResToMemory();
            }
            finally
            {
                if (ins != null)
                {
                    ins.Close();
                    ins.Dispose();
                    ins = null;
                }
            }
        }
Пример #26
0
        private void decompress(byte[] data)
        {
            DataInputStream stream = new DataInputStream(data);

            if (_keys != null && _keys.Length != 0)
            {
                stream.decodeXTEA(_keys);
            }

            int compression = stream.readUnsignedByte();

            _compression = (CompressionType)(compression > 2 ? 2 : compression);

            int compressedLength = stream.readInt();

            if (compressedLength < 0 || compressedLength > 1000000)
            {
                throw new InvalidOperationException("INVALID ARCHIVE HEADER");
            }

            int length;

            switch (_compression)
            {
            case CompressionType.RAW:
                _data = new byte[compressedLength];
                checkRevision(stream, compressedLength);

                stream.Read(_data, 0, compressedLength);
                break;

            case CompressionType.BZIP:
                length = stream.readInt();

                if (length <= 0)
                {
                    _data = null;
                }
                else
                {
                    _data = new byte[length];
                    checkRevision(stream, compressedLength);
                    BZip2Decompressor.Decompress(_data, data);
                }
                break;

            default:                     // GZIP
                length = stream.readInt();

                if (length <= 0 || length > 1000000000)
                {
                    _data = null;
                }
                else
                {
                    _data = new byte[length];
                    checkRevision(stream, compressedLength);
                    GZipDecompressor.Decompress(_data, stream);
                }
                break;
            }
        }
Пример #27
0
        /// <summary>
        /// Reads data from Raspberry in a thread.
        /// </summary>
        private void OnRead()
        {
            int bytes = 0;

            byte[] buffer = new byte[41];
            int    count  = 0;

            isReading = true;
            while (true)
            {
                try
                {
                    bytes = mDataInputStream.Read(buffer);
                    if (buffer[0] != 1 && buffer[0] != 99)
                    {
                        bool isRight = ControlChecksum(buffer);
                        if (isRight == true)
                        {
                            string line = "";
                            // For testing
                            if (mDroneLogs.Keys.Contains("ControlsDrone") == true)
                            {
                                byte  altitudeControl = buffer[1];
                                byte  speed           = buffer[2];
                                int   rawRudder       = (buffer[6] & 0xFF) | ((buffer[5] & 0xFF) << 8) | ((buffer[4] & 0xFF) << 16) | ((buffer[3] & 0xFF) << 24);
                                float rudder          = Float.IntBitsToFloat(rawRudder);
                                int   rawAileron      = (buffer[10] & 0xFF) | ((buffer[9] & 0xFF) << 8) | ((buffer[8] & 0xFF) << 16) | ((buffer[7] & 0xFF) << 24);
                                float aileron         = Float.IntBitsToFloat(rawAileron);
                                int   rawElevator     = (buffer[14] & 0xFF) | ((buffer[13] & 0xFF) << 8) | ((buffer[12] & 0xFF) << 16) | ((buffer[11] & 0xFF) << 24);
                                float elevator        = Float.IntBitsToFloat(rawElevator);

                                line = count + ";" + altitudeControl + ";" + speed + ";" + rudder + ";" + aileron + ";" + elevator;
                                mDroneLogs["ControlsDrone"].Add(line);
                            }
                            // For testing

                            if (mDroneLogs.Keys.Contains("CollisionStatus") == true)
                            {
                                byte collisionStatus = buffer[35];
                                line = count + ";" + collisionStatus.ToString();
                                mDroneLogs["CollisionStatus"].Add(line);
                            }

                            if (mDroneLogs.Keys.Contains("Battery") == true)
                            {
                                byte battery = buffer[36];
                                line = count + ";" + battery.ToString();
                                mDroneLogs["Battery"].Add(line);
                            }

                            if (mDroneLogs.Keys.Contains("Radar") == true)
                            {
                                int   rawRadar = (buffer[18] & 0xFF) | ((buffer[17] & 0xFF) << 8) | ((buffer[16] & 0xFF) << 16) | ((buffer[15] & 0xFF) << 24);
                                float radar    = Float.IntBitsToFloat(rawRadar);
                                line = count + ";" + radar.ToString();
                                Log.Debug("!!!", line);
                                mDroneLogs["Radar"].Add(radar.ToString());
                            }

                            if (mDroneLogs.Keys.Contains("Debug1") == true)
                            {
                                int   rawDebug = (buffer[22] & 0xFF) | ((buffer[21] & 0xFF) << 8) | ((buffer[20] & 0xFF) << 16) | ((buffer[19] & 0xFF) << 24);
                                float debug    = Float.IntBitsToFloat(rawDebug);
                                line = count + ";" + debug.ToString();
                                mDroneLogs["Debug1"].Add(line);
                            }

                            if (mDroneLogs.Keys.Contains("Debug2") == true)
                            {
                                int   rawDebug = (buffer[26] & 0xFF) | ((buffer[25] & 0xFF) << 8) | ((buffer[24] & 0xFF) << 16) | ((buffer[23] & 0xFF) << 24);
                                float debug    = Float.IntBitsToFloat(rawDebug);
                                line = count + ";" + debug.ToString();
                                mDroneLogs["Debug2"].Add(line);
                            }

                            if (mDroneLogs.Keys.Contains("Debug3") == true)
                            {
                                int   rawDebug = (buffer[30] & 0xFF) | ((buffer[29] & 0xFF) << 8) | ((buffer[28] & 0xFF) << 16) | ((buffer[27] & 0xFF) << 24);
                                float debug    = Float.IntBitsToFloat(rawDebug);
                                line = count + ";" + debug.ToString();
                                mDroneLogs["Debug3"].Add(line);
                            }

                            if (mDroneLogs.Keys.Contains("Debug4") == true)
                            {
                                int   rawDebug = (buffer[34] & 0xFF) | ((buffer[33] & 0xFF) << 8) | ((buffer[32] & 0xFF) << 16) | ((buffer[31] & 0xFF) << 24);
                                float debug    = Float.IntBitsToFloat(rawDebug);
                                line = count + ";" + debug.ToString();
                                mDroneLogs["Debug4"].Add(line);
                            }
                        }
                        count += 10;
                    }
                    else
                    {
                        mCurrentMsg = buffer[1].ToString();
                        if (mCurrentMsg == "99")
                        {
                            break;
                        }
                    }
                }
                catch (Java.IO.IOException ex)
                {
                    Log.Debug(TAG, "Error reading (" + ex.Message + ")1");
                    break;
                }
                catch (NullReferenceException ex)
                {
                    Log.Debug(TAG, "No socket connection (" + ex.Message + ")2");
                    // throw new NullReferenceException();
                    break;
                }
                catch (Java.Lang.StringIndexOutOfBoundsException ex)
                {
                    Log.Debug(TAG, "Connection was interrupted by RPI");
                    break;
                }
            }
            isReading = false;
            mRaspberryCloseEvent();
        }
Пример #28
0
        private void decodeHeader()
        {
            DataInputStream stream   = new DataInputStream(_archive.Data);
            int             protocol = stream.readUnsignedByte();

            if (protocol < 5 || protocol > 7)
            {
                throw new ArgumentOutOfRangeException("INVALID PROTOCOL");
            }

            if (protocol >= 6)
            {
                _revision = stream.readInt();
            }

            int hash = stream.readUnsignedByte();

            _named         = (0x1 & hash) != 0;
            _usingWhirpool = (0x2 & hash) != 0;

            int validArchivesCount = protocol >= 7 ? stream.readBigSmart() : stream.readUnsignedShort();

            _validArchiveIds = new int[validArchivesCount];

            int lastArchiveId    = 0;
            int biggestArchiveId = 0;

            for (int i = 0; i < validArchivesCount; i++)
            {
                int archiveId = (lastArchiveId = lastArchiveId + (protocol >= 7 ? stream.readBigSmart() : stream.readUnsignedShort()));
                if (archiveId > biggestArchiveId)
                {
                    biggestArchiveId = archiveId;
                }

                _validArchiveIds[i] = archiveId;
            }

            _archiveList = new ArchiveReference[biggestArchiveId + 1];

            for (int i = 0; i < validArchivesCount; i++)
            {
                _archiveList[_validArchiveIds[i]] = new ArchiveReference();
            }

            if (_named)
            {
                for (int i = 0; i < validArchivesCount; i++)
                {
                    _archiveList[_validArchiveIds[i]].NameHash = stream.readInt();
                }
            }

            if (_usingWhirpool)
            {
                for (int i = 0; i < validArchivesCount; i++)
                {
                    byte[] whirpool = new byte[64];
                    stream.Read(whirpool, 0, 64);
                    _archiveList[_validArchiveIds[i]].Whirpool = (whirpool);
                }
            }

            for (int i = 0; i < validArchivesCount; i++)
            {
                _archiveList[_validArchiveIds[i]].CRC = stream.readInt();
            }
            for (int i = 0; i < validArchivesCount; i++)
            {
                _archiveList[_validArchiveIds[i]].Revision = stream.readInt();
            }
            for (int i = 0; i < validArchivesCount; i++)
            {
                _archiveList[_validArchiveIds[i]].ValidFileIds = new int[(protocol >= 7 ? stream.readBigSmart() : stream.readUnsignedShort())];
            }

            for (int i = 0; i < validArchivesCount; i++)
            {
                int lastFileId           = 0;
                int biggestFileId        = 0;
                ArchiveReference archive = _archiveList[_validArchiveIds[i]];

                for (int j = 0; j < archive.ValidFileIds.Length; j++)
                {
                    int fileId = (lastFileId = lastFileId + (protocol >= 7 ? stream.readBigSmart() : stream.readUnsignedShort()));
                    if (fileId > biggestFileId)
                    {
                        biggestFileId = fileId;
                    }

                    archive.ValidFileIds[j] = fileId;
                }

                archive.FileList = (new FileReference[biggestFileId + 1]);

                for (int j = 0; j < archive.ValidFileIds.Length; j++)
                {
                    archive.FileList[archive.ValidFileIds[j]] = new FileReference();
                }
            }

            if (_named)
            {
                for (int i = 0; i < validArchivesCount; i++)
                {
                    ArchiveReference archive = _archiveList[_validArchiveIds[i]];
                    for (int j = 0; j < archive.ValidFileIds.Length; j++)
                    {
                        archive.FileList[archive.ValidFileIds[j]].NameHash = (stream.readInt());
                    }
                }
            }
        }
Пример #29
0
        /// <exception cref="System.IO.IOException"/>
        private static void CodecTest(Configuration conf, int seed, int count, string codecClass
                                      )
        {
            // Create the codec
            CompressionCodec codec = null;

            try
            {
                codec = (CompressionCodec)ReflectionUtils.NewInstance(conf.GetClassByName(codecClass
                                                                                          ), conf);
            }
            catch (TypeLoadException)
            {
                throw new IOException("Illegal codec!");
            }
            Log.Info("Created a Codec object of type: " + codecClass);
            // Generate data
            DataOutputBuffer data = new DataOutputBuffer();

            RandomDatum.Generator generator = new RandomDatum.Generator(seed);
            for (int i = 0; i < count; ++i)
            {
                generator.Next();
                RandomDatum key   = generator.GetKey();
                RandomDatum value = generator.GetValue();
                key.Write(data);
                value.Write(data);
            }
            Log.Info("Generated " + count + " records");
            // Compress data
            DataOutputBuffer        compressedDataBuffer = new DataOutputBuffer();
            CompressionOutputStream deflateFilter        = codec.CreateOutputStream(compressedDataBuffer
                                                                                    );
            DataOutputStream deflateOut = new DataOutputStream(new BufferedOutputStream(deflateFilter
                                                                                        ));

            deflateOut.Write(data.GetData(), 0, data.GetLength());
            deflateOut.Flush();
            deflateFilter.Finish();
            Log.Info("Finished compressing data");
            // De-compress data
            DataInputBuffer deCompressedDataBuffer = new DataInputBuffer();

            deCompressedDataBuffer.Reset(compressedDataBuffer.GetData(), 0, compressedDataBuffer
                                         .GetLength());
            CompressionInputStream inflateFilter = codec.CreateInputStream(deCompressedDataBuffer
                                                                           );
            DataInputStream inflateIn = new DataInputStream(new BufferedInputStream(inflateFilter
                                                                                    ));
            // Check
            DataInputBuffer originalData = new DataInputBuffer();

            originalData.Reset(data.GetData(), 0, data.GetLength());
            DataInputStream originalIn = new DataInputStream(new BufferedInputStream(originalData
                                                                                     ));

            for (int i_1 = 0; i_1 < count; ++i_1)
            {
                RandomDatum k1 = new RandomDatum();
                RandomDatum v1 = new RandomDatum();
                k1.ReadFields(originalIn);
                v1.ReadFields(originalIn);
                RandomDatum k2 = new RandomDatum();
                RandomDatum v2 = new RandomDatum();
                k2.ReadFields(inflateIn);
                v2.ReadFields(inflateIn);
                Assert.True("original and compressed-then-decompressed-output not equal"
                            , k1.Equals(k2) && v1.Equals(v2));
                // original and compressed-then-decompressed-output have the same hashCode
                IDictionary <RandomDatum, string> m = new Dictionary <RandomDatum, string>();
                m[k1] = k1.ToString();
                m[v1] = v1.ToString();
                string result = m[k2];
                Assert.Equal("k1 and k2 hashcode not equal", result, k1.ToString
                                 ());
                result = m[v2];
                Assert.Equal("v1 and v2 hashcode not equal", result, v1.ToString
                                 ());
            }
            // De-compress data byte-at-a-time
            originalData.Reset(data.GetData(), 0, data.GetLength());
            deCompressedDataBuffer.Reset(compressedDataBuffer.GetData(), 0, compressedDataBuffer
                                         .GetLength());
            inflateFilter = codec.CreateInputStream(deCompressedDataBuffer);
            // Check
            originalIn = new DataInputStream(new BufferedInputStream(originalData));
            int expected;

            do
            {
                expected = originalIn.Read();
                Assert.Equal("Inflated stream read by byte does not match", expected
                             , inflateFilter.Read());
            }while (expected != -1);
            Log.Info("SUCCESS! Completed checking " + count + " records");
        }
Пример #30
0
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="GeneralSecurityException"/>
        private void CryptoCodecTest(Configuration conf, int seed, int count, string encCodecClass
                                     , string decCodecClass, byte[] iv)
        {
            CryptoCodec encCodec = null;

            try
            {
                encCodec = (CryptoCodec)ReflectionUtils.NewInstance(conf.GetClassByName(encCodecClass
                                                                                        ), conf);
            }
            catch (TypeLoadException)
            {
                throw new IOException("Illegal crypto codec!");
            }
            Log.Info("Created a Codec object of type: " + encCodecClass);
            // Generate data
            DataOutputBuffer data = new DataOutputBuffer();

            RandomDatum.Generator generator = new RandomDatum.Generator(seed);
            for (int i = 0; i < count; ++i)
            {
                generator.Next();
                RandomDatum key   = generator.GetKey();
                RandomDatum value = generator.GetValue();
                key.Write(data);
                value.Write(data);
            }
            Log.Info("Generated " + count + " records");
            // Encrypt data
            DataOutputBuffer   encryptedDataBuffer = new DataOutputBuffer();
            CryptoOutputStream @out = new CryptoOutputStream(encryptedDataBuffer, encCodec, bufferSize
                                                             , key, iv);

            @out.Write(data.GetData(), 0, data.GetLength());
            @out.Flush();
            @out.Close();
            Log.Info("Finished encrypting data");
            CryptoCodec decCodec = null;

            try
            {
                decCodec = (CryptoCodec)ReflectionUtils.NewInstance(conf.GetClassByName(decCodecClass
                                                                                        ), conf);
            }
            catch (TypeLoadException)
            {
                throw new IOException("Illegal crypto codec!");
            }
            Log.Info("Created a Codec object of type: " + decCodecClass);
            // Decrypt data
            DataInputBuffer decryptedDataBuffer = new DataInputBuffer();

            decryptedDataBuffer.Reset(encryptedDataBuffer.GetData(), 0, encryptedDataBuffer.GetLength
                                          ());
            CryptoInputStream @in = new CryptoInputStream(decryptedDataBuffer, decCodec, bufferSize
                                                          , key, iv);
            DataInputStream dataIn = new DataInputStream(new BufferedInputStream(@in));
            // Check
            DataInputBuffer originalData = new DataInputBuffer();

            originalData.Reset(data.GetData(), 0, data.GetLength());
            DataInputStream originalIn = new DataInputStream(new BufferedInputStream(originalData
                                                                                     ));

            for (int i_1 = 0; i_1 < count; ++i_1)
            {
                RandomDatum k1 = new RandomDatum();
                RandomDatum v1 = new RandomDatum();
                k1.ReadFields(originalIn);
                v1.ReadFields(originalIn);
                RandomDatum k2 = new RandomDatum();
                RandomDatum v2 = new RandomDatum();
                k2.ReadFields(dataIn);
                v2.ReadFields(dataIn);
                Assert.True("original and encrypted-then-decrypted-output not equal"
                            , k1.Equals(k2) && v1.Equals(v2));
                // original and encrypted-then-decrypted-output have the same hashCode
                IDictionary <RandomDatum, string> m = new Dictionary <RandomDatum, string>();
                m[k1] = k1.ToString();
                m[v1] = v1.ToString();
                string result = m[k2];
                Assert.Equal("k1 and k2 hashcode not equal", result, k1.ToString
                                 ());
                result = m[v2];
                Assert.Equal("v1 and v2 hashcode not equal", result, v1.ToString
                                 ());
            }
            // Decrypt data byte-at-a-time
            originalData.Reset(data.GetData(), 0, data.GetLength());
            decryptedDataBuffer.Reset(encryptedDataBuffer.GetData(), 0, encryptedDataBuffer.GetLength
                                          ());
            @in = new CryptoInputStream(decryptedDataBuffer, decCodec, bufferSize, key, iv);
            // Check
            originalIn = new DataInputStream(new BufferedInputStream(originalData));
            int expected;

            do
            {
                expected = originalIn.Read();
                Assert.Equal("Decrypted stream read by byte does not match", expected
                             , @in.Read());
            }while (expected != -1);
            // Seek to a certain position and decrypt
            originalData.Reset(data.GetData(), 0, data.GetLength());
            decryptedDataBuffer.Reset(encryptedDataBuffer.GetData(), 0, encryptedDataBuffer.GetLength
                                          ());
            @in = new CryptoInputStream(new TestCryptoStreams.FakeInputStream(decryptedDataBuffer
                                                                              ), decCodec, bufferSize, key, iv);
            int seekPos = data.GetLength() / 3;

            @in.Seek(seekPos);
            // Check
            TestCryptoStreams.FakeInputStream originalInput = new TestCryptoStreams.FakeInputStream
                                                                  (originalData);
            originalInput.Seek(seekPos);
            do
            {
                expected = originalInput.Read();
                Assert.Equal("Decrypted stream read by byte does not match", expected
                             , @in.Read());
            }while (expected != -1);
            Log.Info("SUCCESS! Completed checking " + count + " records");
            // Check secure random generator
            TestSecureRandom(encCodec);
        }