Example #1
0
        /// <summary>
        /// Convert a string into an input stream.
        /// @throws UnsupportedEncodingException if the encoding is not supported
        /// </summary>
        /// <param name="content">the string</param>
        /// <param name="encoding">the encoding to use when converting the string to a stream</param>
        /// <returns>the resulting input stream</returns>
        public static InputStream ToInputStream(String content, String encoding)
        {
            try
            {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(content.Length * 2);
                OutputStreamWriter writer = new OutputStreamWriter(byteArrayOutputStream, encoding);
                writer.write(content);
                writer.flush();

                byte[] byteArray = byteArrayOutputStream.toByteArray();
                return new ByteArrayInputStream(byteArray);
            }
            /*        catch (UnsupportedEncodingException e) {
                        throw e;
                    }*/
            catch (IOException e)
            {
                // Theoretically impossible since all the "IO" is in memory but it's a
                // checked exception so we have to catch it.
                throw new IllegalStateException("Exception when converting a string to an input stream: '" + e + "'", e);
            }
            catch (Exception e)
            {
                throw;
            }
        }
Example #2
0
        public byte[] doRequest(byte type, byte[] data = null, File f = null)
        {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            if (data == null)
            {
                bout.writeInt(1);
                bout.writeByte(type);
            }
            else
            {
                bout.writeInt(data.Length+1);
                bout.writeByte(type);
                bout.write(data);
            }
            byte[] aout = bout.getArray();
            stream.Write(aout, 0, aout.Length);
            stream.Flush();

            byte[] resp = readBytes(8);
            ByteArrayInputStream bin = new ByteArrayInputStream(resp);
            int error = bin.readInt();
            int len = bin.readInt();
            resp = readBytes(len);

            if (error == 2) throw new AlreadyEditingException(f);
            if (error != 0)
            {
                ByteArrayInputStream i = new ByteArrayInputStream(resp);
                string s = i.ReadString();
                throw new Exception("Network error: " + s);
            }

            return resp;
        }
Example #3
0
        /// <summary>
        /// Download a resource from the specified URI.
        /// </summary>
        public byte[] DownloadData(URL address)
        {
            URLConnection connection = null;
            InputStream inputStream = null;
            try
            {
                connection = OpenConnection(address);
                inputStream = connection.InputStream;
                var memStream = new ByteArrayOutputStream();
                var buffer = new byte[BUFFER_SIZE];
                int len;

                while ((len = inputStream.Read(buffer, 0, BUFFER_SIZE)) > 0)
                {
                    memStream.Write(buffer, 0, len);
                }

                return memStream.ToByteArray();
            }
            finally
            {
                if (inputStream != null)
                    inputStream.Close();
                var httpConnection = connection as HttpURLConnection;
                if (httpConnection != null)
                    httpConnection.Disconnect();
            }
        }
Example #4
0
 public override byte[] getInterval(int start, int end)
 {
     ByteArrayOutputStream request = new ByteArrayOutputStream();
     request.writeInt(id);
     request.writeInt(start);
     request.writeInt(end);
     return netfs.doRequest(3, request.getArray(), this);
 }
Example #5
0
 public override void replace(byte[] newFile, object editor)
 {
     ByteArrayOutputStream request = new ByteArrayOutputStream();
     request.writeInt(id);
     request.writeInt(newFile.Length);
     request.write(newFile);
     netfs.doRequest(6, request.getArray(), this);
 }
Example #6
0
 public override void replaceInterval(byte[] newFile, int start)
 {
     ByteArrayOutputStream request = new ByteArrayOutputStream();
     request.writeInt(id);
     request.writeInt(start);
     request.writeInt(start + newFile.Length);
     request.write(newFile);
     netfs.doRequest(7, request.getArray(), this);
 }
Example #7
0
 public String Read(File file) {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    InputStream source = new FileInputStream(file);
    byte[] chunk = new byte[1024];
    int count = 0;
    while((count = source.Read(chunk)) != -1) {
       buffer.write(chunk, 0, count);
    }
    return buffer.toString("UTF-8");
 }
        public virtual void TestRandomWrites()
        {
            TemporaryBuffer b   = new TemporaryBuffer.LocalFile();
            TestRng         rng = new TestRng(Sharpen.Extensions.GetTestName());
            int             max = TemporaryBuffer.DEFAULT_IN_CORE_LIMIT * 2;

            byte[] expect = new byte[max];
            try
            {
                int  written = 0;
                bool onebyte = true;
                while (written < max)
                {
                    if (onebyte)
                    {
                        byte v = unchecked ((byte)rng.NextInt());
                        b.Write(v);
                        expect[written++] = v;
                    }
                    else
                    {
                        int    len = Math.Min(rng.NextInt() & 127, max - written);
                        byte[] tmp = rng.NextBytes(len);
                        b.Write(tmp, 0, len);
                        System.Array.Copy(tmp, 0, expect, written, len);
                        written += len;
                    }
                    onebyte = !onebyte;
                }
                NUnit.Framework.Assert.AreEqual(expect.Length, written);
                b.Close();
                NUnit.Framework.Assert.AreEqual(expect.Length, b.Length());
                {
                    byte[] r = b.ToByteArray();
                    NUnit.Framework.Assert.IsNotNull(r);
                    NUnit.Framework.Assert.AreEqual(expect.Length, r.Length);
                    NUnit.Framework.Assert.IsTrue(Arrays.Equals(expect, r));
                }
                {
                    ByteArrayOutputStream o = new ByteArrayOutputStream();
                    b.WriteTo(o, null);
                    o.Close();
                    byte[] r = o.ToByteArray();
                    NUnit.Framework.Assert.AreEqual(expect.Length, r.Length);
                    NUnit.Framework.Assert.IsTrue(Arrays.Equals(expect, r));
                }
            }
            finally
            {
                b.Destroy();
            }
        }
Example #9
0
        /// <exception cref="System.IO.IOException"></exception>
        protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData
                                                                         , SignerInformation si, SignatureParameters parameters, Document originalData)
        {
            si = base.ExtendCMSSignature(signedData, si, parameters, originalData);
            DerObjectIdentifier   attributeId = null;
            ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream();

            switch (GetExtendedValidationType())
            {
            case 1:
            {
                attributeId = PkcsObjectIdentifiers.IdAAEtsEscTimeStamp;
                toTimestamp.Write(si.GetSignature());
                // We don't include the outer SEQUENCE, only the attrType and attrValues as stated by the TS §6.3.5,
                // NOTE 2)
                toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken]
                                  .AttrType.GetDerEncoded());
                toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken]
                                  .AttrValues.GetDerEncoded());
                break;
            }

            case 2:
            {
                attributeId = PkcsObjectIdentifiers.IdAAEtsCertCrlTimestamp;
                break;
            }

            default:
            {
                throw new InvalidOperationException("CAdES-X Profile: Extended validation is set but no valid type (1 or 2)"
                                                    );
            }
            }
            toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs]
                              .AttrType.GetDerEncoded());
            toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs]
                              .AttrValues.GetDerEncoded());
            toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs]
                              .AttrType.GetDerEncoded());
            toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs]
                              .AttrValues.GetDerEncoded());
            //IDictionary<DerObjectIdentifier, Attribute> unsignedAttrHash = si.UnsignedAttributes.ToDictionary();
            IDictionary unsignedAttrHash = si.UnsignedAttributes.ToDictionary();

            BcCms.Attribute extendedTimeStamp = GetTimeStampAttribute(attributeId, GetSignatureTsa(
                                                                          ), digestAlgorithm, toTimestamp.ToByteArray());
            //unsignedAttrHash.Put(attributeId, extendedTimeStamp);
            unsignedAttrHash.Add(attributeId, extendedTimeStamp);
            return(SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable(unsignedAttrHash
                                                                                            )));
        }
Example #10
0
        /// <exception cref="System.IO.IOException"/>
        private int AddSpanReceiver(IList <string> args)
        {
            string className = StringUtils.PopOptionWithArgument("-class", args);

            if (className == null)
            {
                System.Console.Error.WriteLine("You must specify the classname with -class.");
                return(1);
            }
            ByteArrayOutputStream   configStream = new ByteArrayOutputStream();
            TextWriter              configsOut   = new TextWriter(configStream, false, "UTF-8");
            SpanReceiverInfoBuilder factory      = new SpanReceiverInfoBuilder(className);
            string prefix = string.Empty;

            for (int i = 0; i < args.Count; ++i)
            {
                string str = args[i];
                if (!str.StartsWith(ConfigPrefix))
                {
                    System.Console.Error.WriteLine("Can't understand argument: " + str);
                    return(1);
                }
                str = Runtime.Substring(str, ConfigPrefix.Length);
                int equalsIndex = str.IndexOf("=");
                if (equalsIndex < 0)
                {
                    System.Console.Error.WriteLine("Can't parse configuration argument " + str);
                    System.Console.Error.WriteLine("Arguments must be in the form key=value");
                    return(1);
                }
                string key   = Runtime.Substring(str, 0, equalsIndex);
                string value = Runtime.Substring(str, equalsIndex + 1);
                factory.AddConfigurationPair(key, value);
                configsOut.Write(prefix + key + " = " + value);
                prefix = ", ";
            }
            string configStreamStr = configStream.ToString("UTF-8");

            try
            {
                long id = remote.AddSpanReceiver(factory.Build());
                System.Console.Out.WriteLine("Added trace span receiver " + id + " with configuration "
                                             + configStreamStr);
            }
            catch (IOException e)
            {
                System.Console.Out.WriteLine("addSpanReceiver error with configuration " + configStreamStr
                                             );
                throw;
            }
            return(0);
        }
Example #11
0
        public void TestAlternateCorePropertyTimezones()
        {
            Stream                is1   = OpenXml4NetTestDataSamples.OpenSampleStream("OPCCompliance_CoreProperties_AlternateTimezones.docx");
            OPCPackage            pkg   = OPCPackage.Open(is1);
            PackagePropertiesPart props = (PackagePropertiesPart)pkg.GetPackageProperties();

            is1.Close();

            // We need predictable dates for testing!
            //SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"); //use fff for millisecond.

            df.TimeZone = TimeZoneInfo.Utc;
            // Check text properties first
            Assert.AreEqual("Lorem Ipsum", props.GetTitleProperty());
            Assert.AreEqual("Apache POI", props.GetCreatorProperty());

            // Created at has a +3 timezone and milliseconds
            //   2006-10-13T18:06:00.123+03:00
            // = 2006-10-13T15:06:00.123+00:00
            Assert.AreEqual("2006-10-13T15:06:00Z", props.GetCreatedPropertyString());
            Assert.AreEqual("2006-10-13T15:06:00.123Z", df.Format(props.GetCreatedProperty()));

            // Modified at has a -13 timezone but no milliseconds
            //   2007-06-20T07:59:00-13:00
            // = 2007-06-20T20:59:00-13:00
            Assert.AreEqual("2007-06-20T20:59:00Z", props.GetModifiedPropertyString());
            Assert.AreEqual("2007-06-20T20:59:00.000Z", df.Format(props.GetModifiedProperty()));


            // Ensure we can change them with other timezones and still read back OK
            props.SetCreatedProperty("2007-06-20T20:57:00+13:00");
            props.SetModifiedProperty("2007-06-20T20:59:00.123-13:00");

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            pkg.Save(baos);
            pkg = OPCPackage.Open(new ByteArrayInputStream(baos.ToByteArray()));

            // Check text properties first - should be unchanged
            Assert.AreEqual("Lorem Ipsum", props.GetTitleProperty());
            Assert.AreEqual("Apache POI", props.GetCreatorProperty());

            // Check the updated times
            //   2007-06-20T20:57:00+13:00
            // = 2007-06-20T07:57:00Z
            Assert.AreEqual("2007-06-20T07:57:00.000Z", df.Format(props.GetCreatedProperty().Value));

            //   2007-06-20T20:59:00.123-13:00
            // = 2007-06-21T09:59:00.123Z
            Assert.AreEqual("2007-06-21T09:59:00.123Z", df.Format(props.GetModifiedProperty().Value));
        }
        private static string ReadStreamOutput(InputStream inputStream)
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int    length = 0;

            while ((length = inputStream.Read(buffer)) != -1)
            {
                baos.Write(buffer, 0, length);
            }
            return(baos.ToString("UTF-8"));
        }
Example #13
0
        public override void SetUp()
        {
            base.SetUp();
            os     = new ByteArrayOutputStream();
            config = new PackConfig(db);
            dst    = CreateBareRepository();
            FilePath alt = new FilePath(((ObjectDirectory)dst.ObjectDatabase).GetDirectory(),
                                        "info/alternates");

            alt.GetParentFile().Mkdirs();
            Write(alt, ((ObjectDirectory)db.ObjectDatabase).GetDirectory().GetAbsolutePath()
                  + "\n");
        }
Example #14
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static byte[] getBytes(java.io.InputStream is) throws java.io.IOException
        private static sbyte[] getBytes(InputStream @is)
        {
            using (ByteArrayOutputStream os = new ByteArrayOutputStream(), )
            {
                sbyte[] buffer = new sbyte[0xFFFF];
                for (int len; (len = @is.read(buffer)) != -1;)
                {
                    os.write(buffer, 0, len);
                }
                os.flush();
                return(os.toByteArray());
            }
        }
        public virtual void TestPBImageXmlWriter()
        {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            TextWriter            o      = new TextWriter(output);
            PBImageXmlWriter      v      = new PBImageXmlWriter(new Configuration(), o);

            v.Visit(new RandomAccessFile(originalFsimage, "r"));
            SAXParserFactory spf    = SAXParserFactory.NewInstance();
            SAXParser        parser = spf.NewSAXParser();
            string           xml    = output.ToString();

            parser.Parse(new InputSource(new StringReader(xml)), new DefaultHandler());
        }
Example #16
0
        /// <exception cref="System.Exception"/>
        internal static void RunFsck(Configuration conf)
        {
            ByteArrayOutputStream bStream = new ByteArrayOutputStream();
            TextWriter            @out    = new TextWriter(bStream, true);
            int errCode = ToolRunner.Run(new DFSck(conf, @out), new string[] { "/", "-files" }
                                         );
            string result = bStream.ToString();

            System.Console.Out.WriteLine("output from fsck:\n" + result);
            NUnit.Framework.Assert.AreEqual(0, errCode);
            NUnit.Framework.Assert.IsTrue(result.Contains("/test1"));
            NUnit.Framework.Assert.IsTrue(result.Contains("/test2"));
        }
        /// <exception cref="System.Exception"/>
        internal static string ExecCmd(FsShell shell, string[] args)
        {
            ByteArrayOutputStream baout = new ByteArrayOutputStream();
            TextWriter            @out  = new TextWriter(baout, true);
            TextWriter            old   = System.Console.Out;

            Runtime.SetOut(@out);
            int ret = shell.Run(args);

            @out.Close();
            Runtime.SetOut(old);
            return(ret.ToString());
        }
        private string LoadRawString(int rawId)
        {
            var iStream = Resources.OpenRawResource(rawId);
            var baos    = new ByteArrayOutputStream();
            var buf     = new byte[1024];
            int oneByte;

            while ((oneByte = iStream.ReadByte()) != -1)
            {
                baos.Write(oneByte);
            }
            return(baos.ToString());
        }
Example #19
0
 /*
  * public void addPatterns(String id, Map<Integer, Set<Integer>> p, PreparedStatement pstmt) throws IOException, SQLException {
  * for (Map.Entry<Integer, Set<Integer>> en2 : p.entrySet()) {
  * addPattern(id, en2.getKey(), en2.getValue(), pstmt);
  * if(useDBForTokenPatterns)
  * pstmt.addBatch();
  * }
  * }
  */
 /*
  * public void addPatterns(String sentId, int tokenId, Set<Integer> patterns) throws SQLException, IOException{
  * PreparedStatement pstmt = null;
  * Connection conn= null;
  * if(useDBForTokenPatterns) {
  * conn = SQLConnection.getConnection();
  * pstmt = getPreparedStmt(conn);
  * }
  *
  * addPattern(sentId, tokenId, patterns, pstmt);
  *
  * if(useDBForTokenPatterns){
  * pstmt.execute();
  * conn.commit();
  * pstmt.close();
  * conn.close();
  * }
  * }
  */
 /*
  * private void addPattern(String sentId, int tokenId, Set<Integer> patterns, PreparedStatement pstmt) throws SQLException, IOException {
  *
  * if(pstmt != null){
  * //      ByteArrayOutputStream baos = new ByteArrayOutputStream();
  * //      ObjectOutputStream oos = new ObjectOutputStream(baos);
  * //      oos.writeObject(patterns);
  * //      byte[] patsAsBytes = baos.toByteArray();
  * //      ByteArrayInputStream bais = new ByteArrayInputStream(patsAsBytes);
  * //      pstmt.setBinaryStream(1, bais, patsAsBytes.length);
  * //      pstmt.setObject(2, sentId);
  * //      pstmt.setInt(3, tokenId);
  * //      pstmt.setString(4,sentId);
  * //      pstmt.setInt(5, tokenId);
  * //      ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
  * //      ObjectOutputStream oos2 = new ObjectOutputStream(baos2);
  * //      oos2.writeObject(patterns);
  * //      byte[] patsAsBytes2 = baos2.toByteArray();
  * //      ByteArrayInputStream bais2 = new ByteArrayInputStream(patsAsBytes2);
  * //      pstmt.setBinaryStream(6, bais2, patsAsBytes2.length);
  * //      pstmt.setString(7,sentId);
  * //      pstmt.setInt(8, tokenId);
  *
  * ByteArrayOutputStream baos = new ByteArrayOutputStream();
  * ObjectOutputStream oos = new ObjectOutputStream(baos);
  * oos.writeObject(patterns);
  * byte[] patsAsBytes = baos.toByteArray();
  * ByteArrayInputStream bais = new ByteArrayInputStream(patsAsBytes);
  * pstmt.setBinaryStream(3, bais, patsAsBytes.length);
  * pstmt.setObject(1, sentId);
  * pstmt.setInt(2, tokenId);
  *
  *
  * } else{
  * if(!patternsForEachToken.containsKey(sentId))
  * patternsForEachToken.put(sentId, new ConcurrentHashMap<Integer, Set<Integer>>());
  * patternsForEachToken.get(sentId).put(tokenId, patterns);
  * }
  * }*/
 /// <exception cref="Java.Sql.SQLException"/>
 /// <exception cref="System.IO.IOException"/>
 private void AddPattern(string sentId, IDictionary <int, ICollection <E> > patterns, IPreparedStatement pstmt)
 {
     if (pstmt != null)
     {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream    oos  = new ObjectOutputStream(baos);
         oos.WriteObject(patterns);
         byte[] patsAsBytes        = baos.ToByteArray();
         ByteArrayInputStream bais = new ByteArrayInputStream(patsAsBytes);
         pstmt.SetBinaryStream(2, bais, patsAsBytes.Length);
         pstmt.SetObject(1, sentId);
     }
 }
Example #20
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static ByteBuffer toByteBuffer(java.io.InputStream inputStream) throws java.io.IOException
        public static ByteBuffer toByteBuffer(System.IO.Stream inputStream)
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            sbyte[] buffer = new sbyte[4096];
            int     l;

            while ((l = inputStream.Read(buffer, 0, buffer.Length)) != -1)
            {
                baos.write(buffer, 0, l);
            }
            return(ByteBuffer.wrap(baos.toByteArray()));
        }
Example #21
0
        /// <summary>print counters</summary>
        /// <exception cref="System.Exception"/>
        public virtual void TestGetCounter(string jobId, Configuration conf)
        {
            ByteArrayOutputStream @out = new ByteArrayOutputStream();
            // bad command
            int exitCode = RunTool(conf, CreateJobClient(), new string[] { "-counter" }, @out
                                   );

            NUnit.Framework.Assert.AreEqual("Exit code", -1, exitCode);
            exitCode = RunTool(conf, CreateJobClient(), new string[] { "-counter", jobId, "org.apache.hadoop.mapreduce.TaskCounter"
                                                                       , "MAP_INPUT_RECORDS" }, @out);
            NUnit.Framework.Assert.AreEqual("Exit code", 0, exitCode);
            NUnit.Framework.Assert.AreEqual("Counter", "3", @out.ToString().Trim());
        }
        /// <exception cref="System.Exception"/>
        internal static string RunFsck(Configuration conf, int expectedErrCode, bool checkErrorCode
                                       , params string[] path)
        {
            ByteArrayOutputStream bStream = new ByteArrayOutputStream();
            TextWriter            @out    = new TextWriter(bStream, true);
            int errCode = ToolRunner.Run(new DFSck(conf, @out), path);

            if (checkErrorCode)
            {
                NUnit.Framework.Assert.AreEqual(expectedErrCode, errCode);
            }
            return(bStream.ToString());
        }
Example #23
0
        /// <summary>
        /// Convert ByteArrayOutputStream to System.Xml.XPath.XPathDocument
        /// </summary>
        /// <param name="self">ByteArrayOutputStream object</param>
        /// <returns>XPathDocument converted from ByteArrayOutputStream</returns>
        public static XPathDocument ToXPathDocument(this ByteArrayOutputStream self)
        {
            XPathDocument doc = null;

            using (MemoryStream resultStream = new MemoryStream(self.toByteArray()))
            {
                using (XmlReader reader = XmlReader.Create(resultStream))
                {
                    doc = new XPathDocument(reader);
                }
            }
            return(doc);
        }
Example #24
0
        /// <exception cref="System.IO.IOException"></exception>
        private byte[] CompressStandardFormat(string type, string length, byte[] data)
        {
            ByteArrayOutputStream @out = new ByteArrayOutputStream();
            DeflaterOutputStream  d    = new DeflaterOutputStream(@out);

            d.Write(Constants.EncodeASCII(type));
            d.Write(' ');
            d.Write(Constants.EncodeASCII(length));
            d.Write(0);
            d.Write(data);
            d.Finish();
            return(@out.ToByteArray());
        }
Example #25
0
        public virtual MCommittedInfo Encode(CallbackObjectInfoCollections callbackInfo,
                                             int dispatcherID)
        {
            ByteArrayOutputStream os = new ByteArrayOutputStream();

            PrimitiveCodec.WriteInt(os, dispatcherID);
            byte[]         bytes         = EncodeInfo(callbackInfo, os);
            MCommittedInfo committedInfo = (MCommittedInfo)GetWriterForLength(Transaction(),
                                                                              bytes.Length + Const4.IntLength);

            committedInfo._payLoad.Append(bytes);
            return(committedInfo);
        }
Example #26
0
 public virtual void SetUp()
 {
     Assert.True(FileUtil.FullyDelete(TestDir));
     Assert.True(TestDir.Mkdirs());
     oldStdout   = System.Console.Out;
     oldStderr   = System.Console.Error;
     stdout      = new ByteArrayOutputStream();
     printStdout = new TextWriter(stdout);
     Runtime.SetOut(printStdout);
     stderr      = new ByteArrayOutputStream();
     printStderr = new TextWriter(stderr);
     Runtime.SetErr(printStderr);
 }
        /// <exception cref="System.Exception"/>
        private string ReadInputStream(InputStream input)
        {
            ByteArrayOutputStream data = new ByteArrayOutputStream();

            byte[] buffer = new byte[512];
            int    read;

            while ((read = input.Read(buffer)) >= 0)
            {
                data.Write(buffer, 0, read);
            }
            return(Sharpen.Runtime.GetStringForBytes(data.ToByteArray(), "UTF-8"));
        }
        /// <exception cref="System.Exception"/>
        protected internal virtual void SetupInternal(int numNodeManager)
        {
            Log.Info("Starting up YARN cluster");
            conf = new YarnConfiguration();
            conf.SetInt(YarnConfiguration.RmSchedulerMinimumAllocationMb, 128);
            conf.Set("yarn.log.dir", "target");
            conf.SetBoolean(YarnConfiguration.TimelineServiceEnabled, true);
            conf.Set(YarnConfiguration.RmScheduler, typeof(CapacityScheduler).FullName);
            conf.SetBoolean(YarnConfiguration.NodeLabelsEnabled, true);
            if (yarnCluster == null)
            {
                yarnCluster = new MiniYARNCluster(typeof(TestDistributedShell).Name, 1, numNodeManager
                                                  , 1, 1);
                yarnCluster.Init(conf);
                yarnCluster.Start();
                conf.Set(YarnConfiguration.TimelineServiceWebappAddress, MiniYARNCluster.GetHostname
                             () + ":" + yarnCluster.GetApplicationHistoryServer().GetPort());
                WaitForNMsToRegister();
                Uri url = Sharpen.Thread.CurrentThread().GetContextClassLoader().GetResource("yarn-site.xml"
                                                                                             );
                if (url == null)
                {
                    throw new RuntimeException("Could not find 'yarn-site.xml' dummy file in classpath"
                                               );
                }
                Configuration yarnClusterConfig = yarnCluster.GetConfig();
                yarnClusterConfig.Set("yarn.application.classpath", new FilePath(url.AbsolutePath
                                                                                 ).GetParent());
                //write the document to a buffer (not directly to the file, as that
                //can cause the file being written to get read -which will then fail.
                ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
                yarnClusterConfig.WriteXml(bytesOut);
                bytesOut.Close();
                //write the bytes to the file in the classpath
                OutputStream os = new FileOutputStream(new FilePath(url.AbsolutePath));
                os.Write(bytesOut.ToByteArray());
                os.Close();
            }
            FileContext fsContext = FileContext.GetLocalFSFileContext();

            fsContext.Delete(new Path(conf.Get("yarn.timeline-service.leveldb-timeline-store.path"
                                               )), true);
            try
            {
                Sharpen.Thread.Sleep(2000);
            }
            catch (Exception e)
            {
                Log.Info("setup thread sleep interrupted. message=" + e.Message);
            }
        }
Example #29
0
        /// <summary>
        ///     Encodes this <seealso cref="Archive" /> into a <seealso cref="ByteBuffer" />.
        ///     <p />
        ///     Please note that this is a fairly simple implementation that does not
        ///     attempt to use more than one chunk.
        /// </summary>
        /// <returns> An encoded <seealso cref="ByteBuffer" />. </returns>
        /// <exception cref="IOException"> if an I/O error occurs. </exception>
        public virtual ByteBuffer Encode() // TODO: an implementation that can use more than one chunk
        {
            var bout = new ByteArrayOutputStream();
            var os   = new DataOutputStream(bout);

            try
            {
                /* add the data for each entry */
                for (var id = 0; id < entries.Length; id++)
                {
                    /* copy to temp buffer */
                    var temp = new byte[entries[id].limit()];
                    entries[id].position(0);
                    try
                    {
                        entries[id].get(temp);
                    }
                    finally
                    {
                        entries[id].position(0);
                    }

                    /* copy to output stream */
                    os.write(temp);
                }

                /* write the chunk lengths */
                var prev = 0;
                for (var id = 0; id < entries.Length; id++)
                {
                    /*
                     * since each file is stored in the only chunk, just write the
                     * delta-encoded file size
                     */
                    var chunkSize = entries[id].limit();
                    os.writeInt(chunkSize - prev);
                    prev = chunkSize;
                }

                /* we only used one chunk due to a limitation of the implementation */
                bout.write(1);

                /* wrap the bytes from the stream in a buffer */
                var bytes = bout.toByteArray();
                return(ByteBuffer.wrap(bytes));
            }
            finally
            {
                os.close();
            }
        }
Example #30
0
        public virtual void TestCopyFromHostExtraBytes()
        {
            Fetcher <Text, Text> underTest = new TestFetcher.FakeFetcher <Text, Text>(job, id,
                                                                                      ss, mm, r, metrics, except, key, connection);
            string replyHash = SecureShuffleUtils.GenerateHash(Sharpen.Runtime.GetBytesForString
                                                                   (encHash), key);

            Org.Mockito.Mockito.When(connection.GetResponseCode()).ThenReturn(200);
            Org.Mockito.Mockito.When(connection.GetHeaderField(ShuffleHeader.HttpHeaderName))
            .ThenReturn(ShuffleHeader.DefaultHttpHeaderName);
            Org.Mockito.Mockito.When(connection.GetHeaderField(ShuffleHeader.HttpHeaderVersion
                                                               )).ThenReturn(ShuffleHeader.DefaultHttpHeaderVersion);
            Org.Mockito.Mockito.When(connection.GetHeaderField(SecureShuffleUtils.HttpHeaderReplyUrlHash
                                                               )).ThenReturn(replyHash);
            ShuffleHeader         header = new ShuffleHeader(map1ID.ToString(), 14, 10, 1);
            ByteArrayOutputStream bout   = new ByteArrayOutputStream();
            DataOutputStream      dos    = new DataOutputStream(bout);
            IFileOutputStream     ios    = new IFileOutputStream(dos);

            header.Write(dos);
            ios.Write(Sharpen.Runtime.GetBytesForString("MAPDATA123"));
            ios.Finish();
            ShuffleHeader     header2 = new ShuffleHeader(map2ID.ToString(), 14, 10, 1);
            IFileOutputStream ios2    = new IFileOutputStream(dos);

            header2.Write(dos);
            ios2.Write(Sharpen.Runtime.GetBytesForString("MAPDATA456"));
            ios2.Finish();
            ByteArrayInputStream @in = new ByteArrayInputStream(bout.ToByteArray());

            Org.Mockito.Mockito.When(connection.GetInputStream()).ThenReturn(@in);
            // 8 < 10 therefore there appear to be extra bytes in the IFileInputStream
            InMemoryMapOutput <Text, Text> mapOut = new InMemoryMapOutput <Text, Text>(job, map1ID
                                                                                       , mm, 8, null, true);
            InMemoryMapOutput <Text, Text> mapOut2 = new InMemoryMapOutput <Text, Text>(job, map2ID
                                                                                        , mm, 10, null, true);

            Org.Mockito.Mockito.When(mm.Reserve(Matchers.Eq(map1ID), Matchers.AnyLong(), Matchers.AnyInt
                                                    ())).ThenReturn(mapOut);
            Org.Mockito.Mockito.When(mm.Reserve(Matchers.Eq(map2ID), Matchers.AnyLong(), Matchers.AnyInt
                                                    ())).ThenReturn(mapOut2);
            underTest.CopyFromHost(host);
            Org.Mockito.Mockito.Verify(allErrs).Increment(1);
            Org.Mockito.Mockito.Verify(ss).CopyFailed(map1ID, host, true, false);
            Org.Mockito.Mockito.Verify(ss, Org.Mockito.Mockito.Never()).CopyFailed(map2ID, host
                                                                                   , true, false);
            Org.Mockito.Mockito.Verify(ss).PutBackKnownMapOutput(Matchers.Any <MapHost>(), Matchers.Eq
                                                                     (map1ID));
            Org.Mockito.Mockito.Verify(ss).PutBackKnownMapOutput(Matchers.Any <MapHost>(), Matchers.Eq
                                                                     (map2ID));
        }
Example #31
0
        /// <exception cref="System.IO.IOException"/>
        public virtual void TestFileSink()
        {
            outFile = GetTestTempFile("test-file-sink-", ".out");
            string outPath = outFile.GetAbsolutePath();

            // NB: specify large period to avoid multiple metrics snapshotting:
            new ConfigBuilder().Add("*.period", 10000).Add("test.sink.mysink0.class", typeof(
                                                               FileSink).FullName).Add("test.sink.mysink0.filename", outPath).Add("test.sink.mysink0.context"
                                                                                                                                  , "test1").Save(TestMetricsConfig.GetTestFilename("hadoop-metrics2-test"));
            // NB: we filter by context to exclude "metricssystem" context metrics:
            MetricsSystemImpl ms = new MetricsSystemImpl("test");

            ms.Start();
            TestFileSink.MyMetrics1 mm1 = new TestFileSink.MyMetrics1().RegisterWith(ms);
            new TestFileSink.MyMetrics2().RegisterWith(ms);
            mm1.testMetric1.Incr();
            mm1.testMetric2.Incr(2);
            ms.PublishMetricsNow();
            // publish the metrics
            ms.Stop();
            ms.Shutdown();
            InputStream           @is  = null;
            ByteArrayOutputStream baos = null;
            string outFileContent      = null;

            try
            {
                @is  = new FileInputStream(outFile);
                baos = new ByteArrayOutputStream((int)outFile.Length());
                IOUtils.CopyBytes(@is, baos, 1024, true);
                outFileContent = Runtime.GetStringForBytes(baos.ToByteArray(), "UTF-8");
            }
            finally
            {
                IOUtils.Cleanup(null, baos, @is);
            }
            // Check the out file content. Should be something like the following:
            //1360244820087 test1.testRecord1: Context=test1, testTag1=testTagValue1, testTag2=testTagValue2, Hostname=myhost, testMetric1=1, testMetric2=2
            //1360244820089 test1.testRecord2: Context=test1, testTag22=testTagValue22, Hostname=myhost
            // Note that in the below expression we allow tags and metrics to go in arbitrary order.
            Pattern expectedContentPattern = Pattern.Compile("^\\d+\\s+test1.testRecord1:\\s+Context=test1,\\s+"
                                                             + "(testTag1=testTagValue1,\\s+testTag2=testTagValue2|testTag2=testTagValue2,\\s+testTag1=testTagValue1),"
                                                             + "\\s+Hostname=.*,\\s+(testMetric1=1,\\s+testMetric2=2|testMetric2=2,\\s+testMetric1=1)"
                                                             + "$[\\n\\r]*^\\d+\\s+test1.testRecord2:\\s+Context=test1," + "\\s+testTag22=testTagValue22,\\s+Hostname=.*$[\\n\\r]*"
                                                             , Pattern.Multiline);

            // line #1:
            // line #2:
            Assert.True(expectedContentPattern.Matcher(outFileContent).Matches
                            ());
        }
Example #32
0
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        private void AddDocWithId(string docId, string attachmentName, bool gzipped)
        {
            string docJson;
            IDictionary <string, object> documentProperties = new Dictionary <string, object>();

            if (attachmentName == null)
            {
                documentProperties.Put("foo", 1);
                documentProperties.Put("bar", false);
                Document doc = database.GetDocument(docId);
                doc.PutProperties(documentProperties);
            }
            else
            {
                // add attachment to document
                InputStream           attachmentStream = GetAsset(attachmentName);
                ByteArrayOutputStream baos             = new ByteArrayOutputStream();
                IOUtils.Copy(attachmentStream, baos);
                if (gzipped == false)
                {
                    string attachmentBase64 = Base64.EncodeBytes(baos.ToByteArray());
                    documentProperties.Put("foo", 1);
                    documentProperties.Put("bar", false);
                    IDictionary <string, object> attachment = new Dictionary <string, object>();
                    attachment.Put("content_type", "image/png");
                    attachment.Put("data", attachmentBase64);
                    IDictionary <string, object> attachments = new Dictionary <string, object>();
                    attachments.Put(attachmentName, attachment);
                    documentProperties.Put("_attachments", attachments);
                    Document doc = database.GetDocument(docId);
                    doc.PutProperties(documentProperties);
                }
                else
                {
                    byte[] bytes            = baos.ToByteArray();
                    string attachmentBase64 = Base64.EncodeBytes(bytes, Base64.Gzip);
                    documentProperties.Put("foo", 1);
                    documentProperties.Put("bar", false);
                    IDictionary <string, object> attachment = new Dictionary <string, object>();
                    attachment.Put("content_type", "image/png");
                    attachment.Put("data", attachmentBase64);
                    attachment.Put("encoding", "gzip");
                    attachment.Put("length", bytes.Length);
                    IDictionary <string, object> attachments = new Dictionary <string, object>();
                    attachments.Put(attachmentName, attachment);
                    documentProperties.Put("_attachments", attachments);
                    Document doc = database.GetDocument(docId);
                    doc.PutProperties(documentProperties);
                }
            }
        }
Example #33
0
                internal override void AssertCompression(string name, Compressor compressor, Decompressor
                                                         decompressor, byte[] originalRawData)
                {
                    byte[] buf = null;
                    ByteArrayInputStream    bytesIn = null;
                    BlockDecompressorStream blockDecompressorStream = null;
                    ByteArrayOutputStream   bytesOut = new ByteArrayOutputStream();

                    // close without write
                    try
                    {
                        compressor.Reset();
                        // decompressor.end();
                        BlockCompressorStream blockCompressorStream = new BlockCompressorStream(bytesOut,
                                                                                                compressor, 1024, 0);
                        blockCompressorStream.Close();
                        // check compressed output
                        buf = bytesOut.ToByteArray();
                        int emSize = this.emptySize[compressor.GetType()];
                        Assert.Equal(this.joiner.Join(name, "empty stream compressed output size != "
                                                      + emSize), emSize, buf.Length);
                        // use compressed output as input for decompression
                        bytesIn = new ByteArrayInputStream(buf);
                        // create decompression stream
                        blockDecompressorStream = new BlockDecompressorStream(bytesIn, decompressor, 1024
                                                                              );
                        // no byte is available because stream was closed
                        Assert.Equal(this.joiner.Join(name, " return value is not -1")
                                     , -1, blockDecompressorStream.Read());
                    }
                    catch (IOException e)
                    {
                        NUnit.Framework.Assert.Fail(this.joiner.Join(name, e.Message));
                    }
                    finally
                    {
                        if (blockDecompressorStream != null)
                        {
                            try
                            {
                                bytesOut.Close();
                                blockDecompressorStream.Close();
                                bytesIn.Close();
                                blockDecompressorStream.Close();
                            }
                            catch (IOException)
                            {
                            }
                        }
                    }
                }
Example #34
0
        /// <summary>Format this builder's state as a commit object.</summary>
        /// <remarks>Format this builder's state as a commit object.</remarks>
        /// <returns>
        /// this object in the canonical commit format, suitable for storage
        /// in a repository.
        /// </returns>
        /// <exception cref="Sharpen.UnsupportedEncodingException">
        /// the encoding specified by
        /// <see cref="Encoding()">Encoding()</see>
        /// is not
        /// supported by this Java runtime.
        /// </exception>
        public virtual byte[] Build()
        {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            OutputStreamWriter    w  = new OutputStreamWriter(os, Encoding);

            try
            {
                os.Write(htree);
                os.Write(' ');
                TreeId.CopyTo(os);
                os.Write('\n');
                foreach (ObjectId p in ParentIds)
                {
                    os.Write(hparent);
                    os.Write(' ');
                    p.CopyTo(os);
                    os.Write('\n');
                }
                os.Write(hauthor);
                os.Write(' ');
                w.Write(Author.ToExternalString());
                w.Flush();
                os.Write('\n');
                os.Write(hcommitter);
                os.Write(' ');
                w.Write(Committer.ToExternalString());
                w.Flush();
                os.Write('\n');
                if (Encoding != Constants.CHARSET)
                {
                    os.Write(hencoding);
                    os.Write(' ');
                    os.Write(Constants.EncodeASCII(Encoding.Name()));
                    os.Write('\n');
                }
                os.Write('\n');
                if (Message != null)
                {
                    w.Write(Message);
                    w.Flush();
                }
            }
            catch (IOException err)
            {
                // This should never occur, the only way to get it above is
                // for the ByteArrayOutputStream to throw, but it doesn't.
                //
                throw new RuntimeException(err);
            }
            return(os.ToByteArray());
        }
Example #35
0
        public virtual void TestCompressorDecompressorEmptyStreamLogic()
        {
            ByteArrayInputStream  bytesIn  = null;
            ByteArrayOutputStream bytesOut = null;

            byte[] buf = null;
            BlockDecompressorStream blockDecompressorStream = null;

            try
            {
                // compress empty stream
                bytesOut = new ByteArrayOutputStream();
                BlockCompressorStream blockCompressorStream = new BlockCompressorStream(bytesOut,
                                                                                        new Lz4Compressor(), 1024, 0);
                // close without write
                blockCompressorStream.Close();
                // check compressed output
                buf = bytesOut.ToByteArray();
                Assert.Equal("empty stream compressed output size != 4", 4, buf
                             .Length);
                // use compressed output as input for decompression
                bytesIn = new ByteArrayInputStream(buf);
                // create decompression stream
                blockDecompressorStream = new BlockDecompressorStream(bytesIn, new Lz4Decompressor
                                                                          (), 1024);
                // no byte is available because stream was closed
                Assert.Equal("return value is not -1", -1, blockDecompressorStream
                             .Read());
            }
            catch (Exception e)
            {
                NUnit.Framework.Assert.Fail("testCompressorDecompressorEmptyStreamLogic ex error !!!"
                                            + e.Message);
            }
            finally
            {
                if (blockDecompressorStream != null)
                {
                    try
                    {
                        bytesIn.Close();
                        bytesOut.Close();
                        blockDecompressorStream.Close();
                    }
                    catch (IOException)
                    {
                    }
                }
            }
        }
 private byte[] GetBytes(IDictionary <int, ICollection <E> > p)
 {
     try
     {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream    oos  = new ObjectOutputStream(baos);
         oos.WriteObject(p);
         return(baos.ToByteArray());
     }
     catch (IOException e)
     {
         throw new Exception(e);
     }
 }
Example #37
0
 // inherit javadoc
 public override string ToString()
 {
     try
     {
         ByteArrayOutputStream s = new ByteArrayOutputStream();
         CsvRecordOutput       a = new CsvRecordOutput(s);
         this.Serialize(a);
         return(Runtime.GetStringForBytes(s.ToByteArray(), "UTF-8"));
     }
     catch (Exception ex)
     {
         throw new RuntimeException(ex);
     }
 }
        //020985f0 02098620
        public void saveSections()
        {
            Console.Out.WriteLine("Saving sections...");
            f.beginEdit(this);
            ByteArrayOutputStream o = new ByteArrayOutputStream();
            foreach (Arm9BinSection s in sections)
            {
                Console.Out.WriteLine(String.Format("{0:X8} - {1:X8} - {2:X8}: {3:X8}",
                    s.ramAddr, s.ramAddr + s.len, s.ramAddr + s.len + s.bssSize, o.getPos()));

                o.write(s.data);
                o.align(4);
            }

            uint sectionTableAddr = ROM.arm9RAMAddress + 0xE00;
            ByteArrayOutputStream o2 = new ByteArrayOutputStream();
            foreach (Arm9BinSection s in sections)
            {
                if (!s.real) continue;
                if (s.len == 0) continue;
                o2.writeUInt((uint)s.ramAddr);
                o2.writeUInt((uint)s.len);
                o2.writeUInt((uint)s.bssSize);
            }

            //Write BSS sections last
            //because they overwrite huge areas with zeros (?)
            foreach (Arm9BinSection s in sections)
            {
                if (!s.real) continue;
                if (s.len != 0) continue;
                o2.writeUInt((uint)s.ramAddr);
                o2.writeUInt((uint)s.len);
                o2.writeUInt((uint)s.bssSize);
            }

            byte[] data = o.getArray();
            byte[] sectionTable = o2.getArray();
            Array.Copy(sectionTable, 0, data, sectionTableAddr - ROM.arm9RAMAddress, sectionTable.Length);
            f.replace(data, this);
            f.endEdit(this);

            f.setUintAt(getCodeSettingsOffs() + 0x00, (uint)sectionTableAddr);
            Console.Out.WriteLine(String.Format("{0:X8} {1:X8}", getCodeSettingsOffs() + 0x04, (uint)o2.getPos() + sectionTableAddr));
            f.setUintAt(getCodeSettingsOffs() + 0x04, (uint)o2.getPos() + sectionTableAddr);
            f.setUintAt(getCodeSettingsOffs() + 0x08, (uint)(sections[0].len + ROM.arm9RAMAddress));

            Console.Out.WriteLine("DONE");
        }
		private Bitmap captureBitmap(I420Frame i420Frame)
		{
			YuvImage yuvImage = i420ToYuvImage(i420Frame);
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			Rect rect = new Rect(0, 0, yuvImage.Width, yuvImage.Height);

			// Compress YuvImage to jpeg
			yuvImage.compressToJpeg(rect, 100, stream);

			// Convert jpeg to Bitmap
			sbyte[] imageBytes = stream.toByteArray();
			Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.Length);
			Matrix matrix = new Matrix();

			// Apply any needed rotation
			matrix.postRotate(i420Frame.rotationDegree);
			bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true);

			return bitmap;
		}
 public void TestNamespacePrefix() {
    AaaWithPrefix parent = new AaaWithPrefix();
    BbbWithPrefix child = new BbbWithPrefix();
    parent.bbb = child;
    AaaWithPrefix grandchild = new AaaWithPrefix();
    child.aaa = grandchild;
    grandchild.bbb = new BbbWithPrefix();
    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    Serializer serializer = new Persister();
    serializer.write(parent, tmp);
    String result = new String(tmp.toByteArray());
    System.out.println(result);
    assertElementHasAttribute(result, "/aaaWithPrefix", "xmlns:aaa", "namespace1");
    assertElementHasAttribute(result, "/aaaWithPrefix/bbb", "xmlns:bbb", "namespace2");
    assertElementDoesNotHaveAttribute(result, "/aaaWithPrefix/bbb/aaa", "xmlns:aaa", "namespace1");
    assertElementDoesNotHaveAttribute(result, "/aaaWithPrefix/bbb/aaa/bbb", "xmlns:bbb", "namespace2");
    assertElementHasNamespace(result, "/aaaWithPrefix", "namespace1");
    assertElementHasNamespace(result, "/aaaWithPrefix/bbb", "namespace2");
    assertElementHasNamespace(result, "/aaaWithPrefix/bbb/aaa", "namespace1");
    assertElementHasNamespace(result, "/aaaWithPrefix/bbb/aaa/bbb", "namespace2");
 }
Example #41
0
        public static byte[] read(System.IO.Stream stream)
        {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            try
            {
                byte[] buffer = new byte[1024];
                int length;

                while ((length = stream.Read(buffer, 0, 1024)) >= 0)
                {
                    byteArrayOutputStream.Write(buffer, 0, length);
                }
                stream.Close();
                return byteArrayOutputStream.ToByteArray();
            }
            finally
            {
                byteArrayOutputStream.Flush();
                byteArrayOutputStream.Close();

            }
        }
		/**
     	* Write a file to internal storage.  Used to set up our dummy "cloud server".
     	*
     	* @param resId     the resource ID of the file to write to internal storage
     	* @param extension the file extension (ex. .png, .mp3)
     	*/
		void WriteFileToInternalStorage (int resId, String extension)
		{
			using (System.IO.Stream ins = Context.Resources.OpenRawResource (resId)) {
				var outputStream = new ByteArrayOutputStream ();
				int size;
				byte[] buffer = new byte [1024];
				while ((size = ins.Read (buffer, 0, 1024)) > 0) {
					outputStream.Write (buffer, 0, size);
				}
				buffer = outputStream.ToByteArray ();
				var filename = Context.Resources.GetResourceEntryName (resId) + extension;
				using (System.IO.Stream fos = Context.OpenFileOutput (filename, FileCreationMode.Private)) {
					fos.Write (buffer, 0, buffer.Length);
				}
			}
		}
Example #43
0
        public void saveSections()
        {
            Console.Out.WriteLine("Saving sections...");
            f.beginEdit(this);
            ByteArrayOutputStream o = new ByteArrayOutputStream();
            foreach (Arm9BinSection s in sections)
            {
                o.write(s.data);
                o.align(4);
            }

            int pos = o.getPos();
            bool first = true;
            foreach (Arm9BinSection s in sections)
            {
                Console.Out.WriteLine(String.Format("{0:X8} - {1:X8}", s.ramAddr, s.ramAddr + s.len - 1));
                if(first)
                {
                    first = false;
                    continue;
                }

                o.writeUInt((uint)s.ramAddr);
                o.writeUInt((uint)s.len);
                o.writeUInt((uint)s.bssSize);
            }
            o.writeUInt((uint)nullSection.ramAddr);
            o.writeUInt((uint)nullSection.len);
            o.writeUInt((uint)nullSection.bssSize);

            f.replace(o.getArray(), this);

            f.setUintAt(getCodeSettingsOffs() + 0x00, (uint)pos + 0x02000000);
            f.setUintAt(getCodeSettingsOffs() + 0x04, (uint)o.getPos() + 0x02000000);
            f.setUintAt(getCodeSettingsOffs() + 0x08, (uint)(sections[0].len + 0x02000000));

            f.endEdit(this);
            Console.Out.WriteLine("DONE");
        }
		private void pullDownscaledImg(string path, int width, int height)
		{
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final android.graphics.BitmapFactory.Options opt = new android.graphics.BitmapFactory.Options();
			BitmapFactory.Options opt = new BitmapFactory.Options();
			opt.inScaled = false;
			opt.inSampleSize = 4; // logic based on original and requested size.
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final android.graphics.Bitmap scaledbitmap = android.graphics.Bitmap.createScaledBitmap(android.graphics.BitmapFactory.decodeFile(path, opt), width, height, false);
			Bitmap scaledbitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(path, opt), width, height, false);
			if (scaledbitmap != null)
			{
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.io.ByteArrayOutputStream stream = new java.io.ByteArrayOutputStream();
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				scaledbitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
				mImgData = Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);
				try
				{
					stream.close();
				}
//JAVA TO C# CONVERTER WARNING: 'final' catch parameters are not available in C#:
//ORIGINAL LINE: catch (final java.io.IOException e)
				catch (IOException e)
				{
					Console.WriteLine(e.ToString());
					Console.Write(e.StackTrace);
				}
			}
			mResult = "success"; // success
			mReason = REASON_OK; // ok
		}
		private bool pullThumbnails(Cursor imageCursor)
		{
			string data = "";
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final long img_id = imageCursor.getLong(imageCursor.getColumnIndex(android.provider.MediaStore.Images.Media._ID));
			long img_id = imageCursor.getLong(imageCursor.getColumnIndex(MediaStore.Images.Media._ID));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final android.graphics.Bitmap bm = android.provider.MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), img_id, android.provider.MediaStore.Images.Thumbnails.MICRO_KIND, null);
			Bitmap bm = MediaStore.Images.Thumbnails.getThumbnail(ApplicationContext.ContentResolver, img_id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
			if (bm == null)
			{
				return false;
			}
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.io.ByteArrayOutputStream stream = new java.io.ByteArrayOutputStream();
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			bm.compress(Bitmap.CompressFormat.JPEG, 80, stream);
			data = Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);
			try
			{
				stream.close();
			}
//JAVA TO C# CONVERTER WARNING: 'final' catch parameters are not available in C#:
//ORIGINAL LINE: catch (final java.io.IOException e)
			catch (IOException e)
			{
				Console.WriteLine(e.ToString());
				Console.Write(e.StackTrace);
			}
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final long img_size = imageCursor.getLong(imageCursor.getColumnIndex(android.provider.MediaStore.Images.Media.SIZE));
			long img_size = imageCursor.getLong(imageCursor.getColumnIndex(MediaStore.Images.Media.SIZE));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String name = imageCursor.getString(imageCursor.getColumnIndex(android.provider.MediaStore.Images.Media.DISPLAY_NAME));
			string name = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int width = imageCursor.getInt(imageCursor.getColumnIndex(android.provider.MediaStore.Images.Media.WIDTH));
			int width = imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.Media.WIDTH));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int height = imageCursor.getInt(imageCursor.getColumnIndex(android.provider.MediaStore.Images.Media.HEIGHT));
			int height = imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.Media.HEIGHT));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final TBModelJson msg = new TBModelJson(img_id, name, data, img_size, width, height);
			ImageFetchModelImpl.TBModelJson msg = new ImageFetchModelImpl.TBModelJson(img_id, name, data, img_size, width, height);
			mTb.Add(msg);
			return true;
		}
Example #46
0
        private static string terminalNo = "12345678"; // ������ AN8

        #endregion Fields

        #region Methods

        /**
         * ����
         * @param cmd ��������������CMD��
         * @param path ������������
         * @param amount ��������N12
         * @param certificateNo ������������n6(��������)
         * @return

        public static byte[] InitMessage(byte[] cmd, byte path, BigDecimal amount,
            string certificateNo) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                baos.write(PostDefine.START);
                baos.write(PostDefine.STX);

                ByteArrayOutputStream lsContent = new ByteArrayOutputStream();
                lsContent.write(path);
                lsContent.write(PostDefine.TYPE_1);
                lsContent.write(id);
                lsContent.write(cmd);
                lsContent.write(PostDefine.FS);
                lsContent.write(businessNo.getBytes());
                lsContent.write(PostDefine.FS);
                lsContent.write(terminalNo.getBytes());
                lsContent.write(PostDefine.FS);
                lsContent.write(business_zh.getBytes());
                lsContent.write(PostDefine.FS);
                lsContent.write(business_en.getBytes());

                if (amount.intValue() > -1) {
                    lsContent.write(PostDefine.FS);
                    //	int value = (int) (amount.intValue() * 100);
                    int value = (int) amount.intValue();
                    NumberFormat numberFormat = new DecimalFormat("#000000000000");
                    lsContent.write(numberFormat.format(value).getBytes());

                    // ��������,������������
                    if (certificateNo != null) {
                        lsContent.write(PostDefine.FS);
                        lsContent.write(certificateNo.getBytes());
                    }
                }
                int len = lsContent.size();
                baos.write(Function.toHex2Len(len));
                baos.write(lsContent.toByteArray());
                baos.write(PostDefine.ETX);

                byte[] buffer = baos.toByteArray();
                byte[] LRCContent = new byte[buffer.length-4];
                System.arraycopy(buffer, 4, LRCContent, 0, buffer.length-4);
                byte LRC = Function.Enteryparity(LRCContent);

                baos.write(LRC);
                baos.write(PostDefine.END);
                lsContent.close();
                baos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return baos.toByteArray();
        }

        /**
         * ��������
         * @param cmd AN
         * @param code ACK/NAK����
         * @param tip ����
         * @param path ������������
         * @return
         */
        public static sbyte[] InitMessage(byte[] cmd, string code, string tip, sbyte path)
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try
            {
                baos.write(PostDefine.START);
                baos.write(PostDefine.STX);

                ByteArrayOutputStream lsContent = new ByteArrayOutputStream();
                lsContent.write(path); // PostDefine.PATH_1
                lsContent.write(PostDefine.TYPE_1);
                lsContent.write(id);
                lsContent.write(cmd);
                if (code != null)
                {
                    lsContent.write(PostDefine.FS);
                    lsContent.write(code.Bytes);
                    if (tip != null)
                    {
                        lsContent.write(PostDefine.FS);
                        lsContent.write(tip.Bytes);
                    }
                }
                int len = lsContent.size();
                baos.write(Function.toHex2Len(len));
                baos.write(lsContent.toByteArray());
                baos.write(PostDefine.ETX);

                sbyte[] buffer = baos.toByteArray();
                byte[] LRCContent = new byte[buffer.Length - 4];
                Array.Copy(buffer, 4, LRCContent, 0, buffer.Length - 4);
                sbyte LRC = Function.Enteryparity(LRCContent);

                baos.write(LRC);
                baos.write(PostDefine.END);
                lsContent.close();
                baos.close();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }
            return baos.toByteArray();
        }
		public static string encodeToBase64(Bitmap image)
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			image.compress(Bitmap.CompressFormat.PNG, 100, baos);
			sbyte[] b = baos.toByteArray();
			string imageEncoded = com.firebase.client.utilities.Base64.encodeBytes(b);

			return imageEncoded;
		}
Example #48
0
        public void generatePatch()
        {
        	int codeAddr = (int) getCodeAddr();
            Console.Out.WriteLine(String.Format("New code address: {0:X8}", codeAddr));

            FileInfo f = new FileInfo(romdir.FullName + "/newcode.bin");
            if (!f.Exists) return;
            FileStream fs = f.OpenRead();

            byte[] newdata = new byte[fs.Length];
            fs.Read(newdata, 0, (int)fs.Length);
            fs.Close();

            ByteArrayOutputStream extradata = new ByteArrayOutputStream();

            extradata.write(newdata);
            extradata.align(4);
            int hookAddr = codeAddr + extradata.getPos();


            f = new FileInfo(romdir.FullName + "/newcode.sym");
            StreamReader s = f.OpenText();

            while (!s.EndOfStream)
            {
                string l = s.ReadLine();

                int ind = -1;
                if (l.Contains("nsub_"))
                    ind = l.IndexOf("nsub_");
                if (l.Contains("hook_"))
                    ind = l.IndexOf("hook_");
                if (l.Contains("repl_"))
                    ind = l.IndexOf("repl_");

                if (ind != -1)
                {
                    int destRamAddr= parseHex(l.Substring(0, 8));    //Redirect dest addr
                    int ramAddr = parseHex(l.Substring(ind + 5, 8)); //Patched addr
                    uint val = 0;

                    int ovId = -1;
                    if (l.Contains("_ov_"))
                        ovId = parseHex(l.Substring(l.IndexOf("_ov_") + 4, 2));

                    int patchCategory = 0;

                    string cmd = l.Substring(ind, 4);
                    int thisHookAddr = 0;

                    switch(cmd)
                    {
                        case "nsub":
                            val = makeBranchOpcode(ramAddr, destRamAddr, false);
                            break;
                        case "repl":
                            val = makeBranchOpcode(ramAddr, destRamAddr, true);
                            break;
                        case "hook":
                            //Jump to the hook addr
                            thisHookAddr = hookAddr;
                            val = makeBranchOpcode(ramAddr, hookAddr, false);

                            uint originalOpcode = handler.readFromRamAddr(ramAddr, ovId);
                            
                            //TODO: Parse and fix original opcode in case of BL instructions
                            //so it's possible to hook over them too.
                            extradata.writeUInt(originalOpcode);
                            hookAddr += 4;
                            extradata.writeUInt(0xE92D5FFF); //push {r0-r12, r14}
                            hookAddr += 4;
                            extradata.writeUInt(makeBranchOpcode(hookAddr, destRamAddr, true));
                            hookAddr += 4;
                            extradata.writeUInt(0xE8BD5FFF); //pop {r0-r12, r14}
                            hookAddr += 4;
                            extradata.writeUInt(makeBranchOpcode(hookAddr, ramAddr+4, false));
                            hookAddr += 4;
                            extradata.writeUInt(0x12345678);
                            hookAddr += 4;
                            break;
                        default:
                            continue;
                    }

                    //Console.Out.WriteLine(String.Format("{0:X8}:{1:X8} = {2:X8}", patchCategory, ramAddr, val));
                    Console.Out.WriteLine(String.Format("              {0:X8} {1:X8}", destRamAddr, thisHookAddr));

                    handler.writeToRamAddr(ramAddr, val, ovId);
                }
            }

            s.Close();

            int newArenaOffs = codeAddr + extradata.getPos();
            handler.writeToRamAddr(ArenaLoOffs, (uint)newArenaOffs, -1);

            handler.sections.Add(new Arm9BinSection(extradata.getArray(), codeAddr, 0));
            handler.saveSections();
        }
Example #49
0
        public static sbyte[] readInputStreamToByte(System.IO.Stream @in)
        {
            sbyte[] bytes = new sbyte[0];
            ByteArrayOutputStream @out = new ByteArrayOutputStream();

            sbyte[] cache = new sbyte[1024 * 4];
            int read = -1;
            while ((read = @in.Read(cache, 0, cache.Length)) != -1)
            {
                @out.write(cache, 0, read);
            }
            bytes = @out.toByteArray();
            @out.close();
            return bytes;
        }
Example #50
0
 public override void endEdition()
 {
     ByteArrayOutputStream request = new ByteArrayOutputStream();
     request.writeInt(id);
     netfs.doRequest(5, request.getArray(), this);
 }
		/// <summary>
		/// Load default image.
		/// </summary>
		private void makeBufferWithDefaultPath()
		{
			Log.v(TAG, "makeBufferWithDefaultPath");
			buffer = null;
			System.IO.Stream inputStream = Resources.openRawResource(R.raw.flower_resize);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

			int i;
			try
			{
				i = inputStream.Read();
				while (i != -1)
				{
					byteArrayOutputStream.write(i);
					i = inputStream.Read();
				}

				buffer = byteArrayOutputStream.toByteArray();
				inputStream.Close();
			}
			catch (IOException e)
			{
				Console.WriteLine(e.ToString());
				Console.Write(e.StackTrace);
			}

			mInputImage = new SCameraImage(SCameraImage.FORMAT_DEFAULT, buffer);
			mInputBitmap = getOutputBitmap(mInputImage);
			mInputView.ImageBitmap = mInputBitmap;
		}
Example #52
0
		// --------------------------------------------------------------------------------
		//
		// Interface functions
		//
		// --------------------------------------------------------------------------------

		public override void writeHeader(VCFHeader header)
		{
			// make sure the header is sorted correctly
			header = new VCFHeader(header.MetaDataInSortedOrder, header.GenotypeSampleNames);

			// create the config offsets map
			if (header.ContigLines.Count == 0)
			{
				if (ALLOW_MISSING_CONTIG_LINES)
				{
					if (GeneralUtils.DEBUG_MODE_ENABLED)
					{
						Console.Error.WriteLine("No contig dictionary found in header, falling back to reference sequence dictionary");
					}
					createContigDictionary(VCFUtils.makeContigHeaderLines(RefDict, null));
				}
				else
				{
					throw new IllegalStateException("Cannot write BCF2 file with missing contig lines");
				}
			}
			else
			{
				createContigDictionary(header.ContigLines);
			}

			// set up the map from dictionary string values -> offset
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final ArrayList<String> dict = org.broadinstitute.variant.bcf2.BCF2Utils.makeDictionary(header);
			List<string> dict = BCF2Utils.makeDictionary(header);
			for (int i = 0; i < dict.Count; i++)
			{
				stringDictionaryMap[dict[i]] = i;
			}

			sampleNames = header.GenotypeSampleNames.ToArray();

			// setup the field encodings
			fieldManager.setup(header, encoder, stringDictionaryMap);

			try
			{
				// write out the header into a byte stream, get it's length, and write everything to the file
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final ByteArrayOutputStream capture = new ByteArrayOutputStream();
				ByteArrayOutputStream capture = new ByteArrayOutputStream();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final OutputStreamWriter writer = new OutputStreamWriter(capture);
				OutputStreamWriter writer = new OutputStreamWriter(capture);
				this.header = VCFWriter.writeHeader(header, writer, doNotWriteGenotypes, VCFWriter.VersionLine, "BCF2 stream");
				writer.append('\0'); // the header is null terminated by a byte
				writer.close();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final byte[] headerBytes = capture.toByteArray();
				sbyte[] headerBytes = capture.toByteArray();
				(new BCFVersion(MAJOR_VERSION, MINOR_VERSION)).write(outputStream);
				BCF2Type.INT32.write(headerBytes.Length, outputStream);
				outputStream.write(headerBytes);
			}
			catch (IOException e)
			{
				throw new Exception("BCF2 stream: Got IOException while trying to write BCF2 header", e);
			}
		}
Example #53
0
 /**
  *
  * @param cmd ��������������CMD��
  * @param code ACK/NAK����
  * @return
  */
 public static byte[] InitMessage(byte cmd, string code)
 {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     try {
         baos.write(PostDefine.START);
         baos.write(cmd);
         if (code != null) {
             baos.write(PostDefine.FS);
             baos.write(code.getBytes());
         }
         baos.write(PostDefine.END);
     } catch (IOException e) {
         // TODO Auto-generated catch block
     //	e.printStackTrace();
     }
     return baos.toByteArray();
 }
Example #54
0
        /**
         * ������������������
         * @param content
         * @return
         */
        public static byte[] InitMessage(byte[] content)
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                baos.write(PostDefine.START);
                baos.write(PostDefine.STX);
                int len = content.Length + 8;//��path��type��id��������8����
                baos.write(Function.toHex2Len(len));
                baos.write(PostDefine.PATH_4);
                baos.write(PostDefine.TYPE_1); //
                baos.write(id);
                baos.write(content);
                baos.write(PostDefine.ETX);

                byte[] buffer = baos.toByteArray();
                byte[] LRCContent = new byte[buffer.Length-4];
                System.Array.Copy(buffer, 4, LRCContent, 0, buffer.Length-4);
                byte LRC = Function.Enteryparity(LRCContent);

                baos.write(LRC);
                baos.write(PostDefine.END);
                baos.close();
            } catch (IOException e) {
            //	e.printStackTrace();
            }
            return baos.toByteArray();
        }
Example #55
0
		private static string ReadStreamOutput (InputStream inputStream)
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream ();
			byte[] buffer = new byte[1024];
			int length = 0;
			while ((length = inputStream.Read (buffer)) != -1) {
				baos.Write (buffer, 0, length);
			}
			return baos.ToString ("UTF-8");
		}
Example #56
0
	/**
	 * バイト列読み込み
	 *
	 * @param in
	 *			読み出し元
	 * @param size
	 *			バッファサイズ
	 * @return 読み出したバイト列
	 * @exception IOException
	 */
	public static byte[] toByteArray(InputStream in, int size){
		ByteArrayOutputStream bout;
		try {
			/* バッファ確保 */
			bout = new ByteArrayOutputStream(size * 2);
			byte[] bytes = new byte[size];
			/* size を流用 */
			while ((size = in.read(bytes)) > 0) {
				bout.write(bytes, 0, size);
			}
			// bytes = null;
			bout.close();
		} finally {
			/* 閉じる */
			in.close();
		}
Example #57
0
        public ImageTexeler(Bitmap img, int paletteMaxNum)
        {
            this.img = img;

            int tx = img.Width / 4;
            int ty = img.Height / 4;
            palettes = new Color[tx*ty][];
            paletteCounts = new int[tx*ty];
            paletteNumbers = new int[tx, ty];
            paletteDiffs = new float[tx*ty, tx*ty];

            int palNum = 0;
            for(int x = 0; x < tx; x++)
                for (int y = 0; y < ty; y++)
                {
                    ImageIndexerFast iif = new ImageIndexerFast(img, x * 4, y * 4);
                    palettes[palNum] = iif.palette;
                    paletteNumbers[x, y] = palNum;
                    paletteCounts[palNum] = 1;
                    int similar = calcPaletteDiffs(palNum);
            /*                    if (similar != -1)
                    {
                        paletteCounts[palNum] = 0;
                        paletteCounts[similar]++;
                        paletteNumbers[x, y] = similar;
                    }
                    */
                    palNum++;
                }

            while (countUsedPalettes() > paletteMaxNum)
            {
                Console.Out.WriteLine(countUsedPalettes());
                int besta = -1;
                int bestb = -1;
                float bestDif = float.MaxValue;

                //Find the two most similar palettes
                for (int i = 0; i < palettes.Length; i++)
                {
                    if (paletteCounts[i] == 0) continue;
                    for (int j = 0; j < palettes.Length; j++)
                    {
                        if (i == j) continue;
                        if (paletteCounts[j] == 0) continue;

                        if (paletteDiffs[i, j] < bestDif)
                        {
                            bestDif = paletteDiffs[i, j];
                            besta = j;
                            bestb = i;
                        }
                    }
                }

                //Merge the Palettes!!!
                palettes[besta] = palMerge(palettes[besta], palettes[bestb]);
                calcPaletteDiffs(besta);
                paletteCounts[besta] += paletteCounts[bestb];
                paletteCounts[bestb] = 0;

                for (int x = 0; x < tx; x++)
                    for (int y = 0; y < ty; y++)
                        if (paletteNumbers[x, y] == bestb)
                            paletteNumbers[x, y] = besta;
            }

            //CREATE THE FINAL PAL
            int currNum = 0;
            finalPalette = new Color[paletteMaxNum*4];
            int[] newPalNums = new int[palettes.Length];
            for(int i = 0; i < palettes.Length; i++)
            {
                if(paletteCounts[i] != 0)
                {
                    //transparentToTheEnd(palettes[i]);
                    newPalNums[i] = currNum;
                    Array.Copy(palettes[i], 0, finalPalette, currNum*4, 4);
                    currNum++;
                }
            }

            ByteArrayOutputStream texDat = new ByteArrayOutputStream();
            ByteArrayOutputStream f5Dat = new ByteArrayOutputStream();
            for (int y = 0; y < ty; y++)
                for (int x = 0; x < tx; x++)
                {
                    //Find out if texel has transparent.

                    bool hasTransparent = false;
                    for (int yy = 0; yy < 4; yy++)
                        for (int xx = 0; xx < 4; xx++)
                        {
                            Color coll = img.GetPixel(x * 4 + xx, y * 4 + yy);
                            if (coll.A < 128)
                                hasTransparent = true;
                        }

                    //WRITE THE IMAGE DATA
                    for (int yy = 0; yy < 4; yy++)
                    {
                        byte b = 0;
                        byte pow = 1;
                        for (int xx = 0; xx < 4; xx++)
                        {
                            Color coll = img.GetPixel(x*4+xx, y*4+yy);
                            byte col;
                            if (coll.A < 128)
                            {
                                col = 3;
                            }
                            else
                            {
                                col = (byte)ImageIndexer.closest(coll, palettes[paletteNumbers[x, y]]);
                                if (col == 3) col = 2;
                            }
                            b |= (byte)(pow * col);
                            pow *= 4;
                        }
                        texDat.writeByte(b);
                    }

                    //WRITE THE FORMAT-5 SPECIFIC DATA
                    ushort dat = (ushort)(newPalNums[paletteNumbers[x, y]] * 2);
                    if(!hasTransparent)
                        dat |= 2 << 14;
                    f5Dat.writeUShort(dat);
                }

            f5data = f5Dat.getArray();
            texdata = texDat.getArray();
        }
Example #58
0
		public virtual void Write(float value) {

			if (disposed)
				throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter");

            var byteArrayOutputStream = new ByteArrayOutputStream();
            var dataOutputStream = new DataOutputStream(byteArrayOutputStream);
            dataOutputStream.WriteFloat(value);
            byteArrayOutputStream.Flush();

		    WriteSwapped(byteArrayOutputStream.ToByteArray(), 4);

            byteArrayOutputStream.Close();
            dataOutputStream.Close();
		}
Example #59
0
 public override byte[] getContents()
 {
     ByteArrayOutputStream request = new ByteArrayOutputStream();
     request.writeInt(id);
     return netfs.doRequest(2, request.getArray(), this);
 }
Example #60
0
        static void GetPhoto(Context ctx, ref AndroidContact destination, Android.Net.Uri photoUri)
        {
            ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
            const int bufSize = 0x100;
            byte[] buf = new byte[bufSize];
            int n;
            using (Stream fileStream = ctx.ContentResolver.OpenInputStream(photoUri))
            {
                while ((n = fileStream.Read(buf, 0, bufSize)) > 0)
                    byteBuffer.Write(buf, 0, n);
            }

            destination.Photo = byteBuffer.ToByteArray();
        }