コード例 #1
0
        protected void SaveStateInClient(FacesContext facesContext, StateManager.SerializedView serializedView)
        {
            //UIViewRoot uiViewRoot = facesContext.getViewRoot ();
            ////save state in response (client-side: full state; server-side: sequence)
            //RenderKit renderKit = RenderKitFactory.getRenderKit (facesContext, uiViewRoot.getRenderKitId ());
            //// not us.
            //renderKit.getResponseStateManager ().writeState (facesContext, serializedView);

            java.io.ByteArrayOutputStream bytearrayoutputstream = new java.io.ByteArrayOutputStream();
            java.io.ObjectOutputStream    objectoutputstream    = new java.io.ObjectOutputStream(bytearrayoutputstream);

            //ignore tree structure
            //objectoutputstream.writeObject (serializedView.getStructure ());
            objectoutputstream.writeObject(serializedView.getState());
            objectoutputstream.close();
            bytearrayoutputstream.close();

            string s =
                @"<div>
	<input type=""hidden"" name="""     + VIEWSTATE + "\" id=\"" + VIEWSTATE + "\" value=\"" +
                Convert.ToBase64String((byte [])vmw.common.TypeUtils.ToByteArray(bytearrayoutputstream.toByteArray())) + @""" />
</div>";

            facesContext.getResponseWriter().write(s);
        }
コード例 #2
0
ファイル: Crypto.cs プロジェクト: maneskul/fernandao
        public string DecodeAndSaveFile(string retornoFilePath)
        {
            var key      = this.GetCryptKey();
            var fileName = Path.GetFileName(retornoFilePath);

            try
            {
                var wis = new br.com.bradesco.webta.security.crypto.WEBTAInputStream(
                    fileName,
                    Path.GetDirectoryName(retornoFilePath),
                    key);

                int    readBytes = 0;
                byte[] aux       = new byte[512];
                var    baos      = new java.io.ByteArrayOutputStream();
                while ((readBytes = wis.read(aux, 0, aux.Length)) > 0)
                {
                    baos.write(aux, 0, readBytes);
                }

                var outputFile = string.Concat(Path.Combine(Path.GetDirectoryName(retornoFilePath), Path.GetFileNameWithoutExtension(fileName)), ".out.RET");
                File.WriteAllText(outputFile, baos.toString());

                wis.close();

                return(outputFile);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Falha ao descriptografar o arquivo '{0}'.", fileName), ex);
            }
        }
コード例 #3
0
        /// <summary>
        /// Get a thumbnail of the document, if possible
        /// </summary>
        /// <param name="sizeX">The maximum X size of the thumbnail</param>
        /// <param name="sizeY">The maximum y size of the thumbnail</param>
        /// <param name="forceFullSize">True if the thumbnail should be exatly XxY pixels and False if the thumbnail
        /// should fit inside a XxY box but should maintain its aspect ratio</param>
        /// <returns>A JPEG byte thumbnail or null if the thumbnail can´t be generated</returns>
        public override byte[] GetThumbnail(int sizeX, int sizeY, bool forceFullSize)
        {
            // If we have no bytes then we can't do anything.
            if (Bytes == null || Bytes.Length == 0)
            {
                return(null);
            }

            try
            {
                org.pdfbox.pdfviewer.PageDrawer pagedrawer = new
                                                             org.pdfbox.pdfviewer.PageDrawer();

                java.io.ByteArrayInputStream byteStream = new java.io.ByteArrayInputStream(Bytes);
                PDDocument     doc   = PDDocument.load(byteStream);
                int            count = doc.getNumberOfPages();
                java.util.List pages = doc.getDocumentCatalog().getAllPages();
                if (pages.size() > 0)
                {
                    PDPage page = pagedrawer.getPage();
                    java.awt.image.BufferedImage  image = page.convertToImage();
                    java.io.ByteArrayOutputStream os    = new java.io.ByteArrayOutputStream();
                    ImageIO.write(image, "jpg", os);
                    byte[] data = os.toByteArray();
                    return(data);
                }
            }
            catch (Exception e)
            {
                log.Error("Failed to get the thumbnail from the PDF file " + Name, e);
            }

            return(null);
        }
コード例 #4
0
        public static byte[] toBytes(OpcPackage wordPkg)
        {
            SaveToZipFile saver = new SaveToZipFile(wordPkg);
            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
            saver.save(baos);

            return baos.toByteArray();
        }
コード例 #5
0
        public static byte[] toBytes(WordprocessingMLPackage wordPkg)
        {
            SaveToZipFile saver = new SaveToZipFile(wordPkg);

            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
            saver.save(baos);

            return(baos.toByteArray());
        }
コード例 #6
0
 public virtual void TestSerializePolyline()
 {
     try
     {
         java.io.ByteArrayOutputStream streamOut = new java.io.ByteArrayOutputStream();
         java.io.ObjectOutputStream    oo        = new java.io.ObjectOutputStream(streamOut);
         com.epl.geometry.Polyline     pt        = new com.epl.geometry.Polyline();
         pt.StartPath(10, 10);
         pt.LineTo(100, 100);
         pt.LineTo(200, 100);
         oo.WriteObject(pt);
         System.IO.BinaryWriter    streamIn = new System.IO.BinaryWriter(streamOut.ToByteArray());
         java.io.ObjectInputStream ii       = new java.io.ObjectInputStream(streamIn);
         com.epl.geometry.Polyline ptRes    = (com.epl.geometry.Polyline)ii.ReadObject();
         NUnit.Framework.Assert.IsTrue(ptRes.Equals(pt));
     }
     catch (System.Exception)
     {
         Fail("Polyline serialization failure");
     }
     //try
     //{
     //FileOutputStream streamOut = new FileOutputStream("c:/temp/savedPolyline1.txt");
     //ObjectOutputStream oo = new ObjectOutputStream(streamOut);
     //Polyline pt = new Polyline();
     //pt.startPath(10, 10);
     //pt.lineTo(100, 100);
     //pt.lineTo(200, 100);
     //oo.writeObject(pt);
     //}
     //catch(Exception ex)
     //{
     //fail("Polyline serialization failure");
     //}
     try
     {
         java.io.InputStream       s     = typeof(com.epl.geometry.TestSerialization).GetResourceAsStream("savedPolyline.txt");
         java.io.ObjectInputStream ii    = new java.io.ObjectInputStream(s);
         com.epl.geometry.Polyline ptRes = (com.epl.geometry.Polyline)ii.ReadObject();
         NUnit.Framework.Assert.IsTrue(ptRes != null);
     }
     catch (System.Exception)
     {
         Fail("Polyline serialization failure");
     }
     try
     {
         java.io.InputStream       s     = typeof(com.epl.geometry.TestSerialization).GetResourceAsStream("savedPolyline1.txt");
         java.io.ObjectInputStream ii    = new java.io.ObjectInputStream(s);
         com.epl.geometry.Polyline ptRes = (com.epl.geometry.Polyline)ii.ReadObject();
         NUnit.Framework.Assert.IsTrue(ptRes != null);
     }
     catch (System.Exception)
     {
         Fail("Polyline serialization failure");
     }
 }
コード例 #7
0
ファイル: RuleBase.cs プロジェクト: soboE2/SEP
 public void Save(Stream stream)
 {
     //FileOutputStream _javastream = new FileOutputStream(filePath);
     java.io.ByteArrayOutputStream byteStream = new java.io.ByteArrayOutputStream();
     java.io.ObjectOutput          objOut     = new DotnetObjectOutputStream(byteStream);
     ((ReteooRuleBase)this._javaRuleBase).writeExternal(objOut);
     stream.Write(byteStream.toByteArray(), 0, byteStream.toByteArray().Length);
     byteStream.close();
 }
コード例 #8
0
 public virtual void TestSerializeMultiPoint()
 {
     try
     {
         java.io.ByteArrayOutputStream streamOut = new java.io.ByteArrayOutputStream();
         java.io.ObjectOutputStream    oo        = new java.io.ObjectOutputStream(streamOut);
         com.epl.geometry.MultiPoint   pt        = new com.epl.geometry.MultiPoint();
         pt.Add(10, 30);
         pt.Add(120, 40);
         oo.WriteObject(pt);
         System.IO.BinaryWriter      streamIn = new System.IO.BinaryWriter(streamOut.ToByteArray());
         java.io.ObjectInputStream   ii       = new java.io.ObjectInputStream(streamIn);
         com.epl.geometry.MultiPoint ptRes    = (com.epl.geometry.MultiPoint)ii.ReadObject();
         NUnit.Framework.Assert.IsTrue(ptRes.Equals(pt));
     }
     catch (System.Exception)
     {
         Fail("MultiPoint serialization failure");
     }
     //try
     //{
     //FileOutputStream streamOut = new FileOutputStream("c:/temp/savedMultiPoint1.txt");
     //ObjectOutputStream oo = new ObjectOutputStream(streamOut);
     //MultiPoint pt = new MultiPoint();
     //pt.add(10, 30);
     //pt.add(120, 40);
     //oo.writeObject(pt);
     //}
     //catch(Exception ex)
     //{
     //fail("MultiPoint serialization failure");
     //}
     try
     {
         java.io.InputStream         s     = typeof(com.epl.geometry.TestSerialization).GetResourceAsStream("savedMultiPoint.txt");
         java.io.ObjectInputStream   ii    = new java.io.ObjectInputStream(s);
         com.epl.geometry.MultiPoint ptRes = (com.epl.geometry.MultiPoint)ii.ReadObject();
         NUnit.Framework.Assert.IsTrue(ptRes.GetPoint(1).GetY() == 40);
     }
     catch (System.Exception)
     {
         Fail("MultiPoint serialization failure");
     }
     try
     {
         java.io.InputStream         s     = typeof(com.epl.geometry.TestSerialization).GetResourceAsStream("savedMultiPoint1.txt");
         java.io.ObjectInputStream   ii    = new java.io.ObjectInputStream(s);
         com.epl.geometry.MultiPoint ptRes = (com.epl.geometry.MultiPoint)ii.ReadObject();
         NUnit.Framework.Assert.IsTrue(ptRes.GetPoint(1).GetY() == 40);
     }
     catch (System.Exception)
     {
         Fail("MultiPoint serialization failure");
     }
 }
コード例 #9
0
            internal OutputStreamRequestEntity(long length)
            {
                _contentLength = length;
                int tmp = (int)_contentLength;

                if (tmp <= 0)
                {
                    tmp = 4096;
                }
                _out = new java.io.ByteArrayOutputStream(tmp);
            }
コード例 #10
0
        /// <summary>Returns a byte[] containing the remainder of 'in'.</summary>
        /// <remarks>Returns a byte[] containing the remainder of 'in'.</remarks>
        /// <exception cref="System.IO.IOException"></exception>
        public static byte[] readFullyNoClose(java.io.InputStream @in)
        {
            java.io.ByteArrayOutputStream bytes = new java.io.ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int    count;

            while ((count = @in.read(buffer)) != -1)
            {
                bytes.write(buffer, 0, count);
            }
            return(bytes.toByteArray());
        }
コード例 #11
0
 public long getContentLength()
 {
     if (_out != null)
     {
         _buffer = _out.toByteArray();
     }
     if (_buffer != null)
     {
         _contentLength = _buffer.Length;
         _out           = null;
     }
     return(_contentLength);
 }
コード例 #12
0
 public virtual void TestSerializeEnvelope()
 {
     try
     {
         java.io.ByteArrayOutputStream streamOut = new java.io.ByteArrayOutputStream();
         java.io.ObjectOutputStream    oo        = new java.io.ObjectOutputStream(streamOut);
         com.epl.geometry.Envelope     pt        = new com.epl.geometry.Envelope(10, 10, 400, 300);
         oo.WriteObject(pt);
         System.IO.BinaryWriter    streamIn = new System.IO.BinaryWriter(streamOut.ToByteArray());
         java.io.ObjectInputStream ii       = new java.io.ObjectInputStream(streamIn);
         com.epl.geometry.Envelope ptRes    = (com.epl.geometry.Envelope)ii.ReadObject();
         NUnit.Framework.Assert.IsTrue(ptRes.Equals(pt));
     }
     catch (System.Exception)
     {
         Fail("Envelope serialization failure");
     }
     //try
     //{
     //FileOutputStream streamOut = new FileOutputStream("c:/temp/savedEnvelope1.txt");
     //ObjectOutputStream oo = new ObjectOutputStream(streamOut);
     //Envelope pt = new Envelope(10, 10, 400, 300);
     //oo.writeObject(pt);
     //}
     //catch(Exception ex)
     //{
     //fail("Envelope serialization failure");
     //}
     try
     {
         java.io.InputStream       s     = typeof(com.epl.geometry.TestSerialization).GetResourceAsStream("savedEnvelope.txt");
         java.io.ObjectInputStream ii    = new java.io.ObjectInputStream(s);
         com.epl.geometry.Envelope ptRes = (com.epl.geometry.Envelope)ii.ReadObject();
         NUnit.Framework.Assert.IsTrue(ptRes.GetXMax() == 400);
     }
     catch (System.Exception)
     {
         Fail("Envelope serialization failure");
     }
     try
     {
         java.io.InputStream       s     = typeof(com.epl.geometry.TestSerialization).GetResourceAsStream("savedEnvelope1.txt");
         java.io.ObjectInputStream ii    = new java.io.ObjectInputStream(s);
         com.epl.geometry.Envelope ptRes = (com.epl.geometry.Envelope)ii.ReadObject();
         NUnit.Framework.Assert.IsTrue(ptRes.GetXMax() == 400);
     }
     catch (System.Exception)
     {
         Fail("Envelope serialization failure");
     }
 }
コード例 #13
0
 public virtual void testSerializePolyline()
 {
     try
     {
         java.io.ByteArrayOutputStream   streamOut = new java.io.ByteArrayOutputStream();
         java.io.ObjectOutputStream      oo        = new java.io.ObjectOutputStream(streamOut);
         com.esri.core.geometry.Polyline pt        = new com.esri.core.geometry.Polyline();
         pt.startPath(10, 10);
         pt.lineTo(100, 100);
         pt.lineTo(200, 100);
         oo.writeObject(pt);
         java.io.ByteArrayInputStream streamIn = new java.io.ByteArrayInputStream(streamOut
                                                                                  .toByteArray());
         java.io.ObjectInputStream       ii    = new java.io.ObjectInputStream(streamIn);
         com.esri.core.geometry.Polyline ptRes = (com.esri.core.geometry.Polyline)ii.readObject
                                                     ();
         NUnit.Framework.Assert.IsTrue(ptRes.Equals(pt));
     }
     catch (System.Exception)
     {
         fail("Polyline serialization failure");
     }
     // try
     // {
     // FileOutputStream streamOut = new FileOutputStream(m_thisDirectory +
     // "savedPolyline.txt");
     // ObjectOutputStream oo = new ObjectOutputStream(streamOut);
     // Polyline pt = new Polyline();
     // pt.startPath(10, 10);
     // pt.lineTo(100, 100);
     // pt.lineTo(200, 100);
     // oo.writeObject(pt);
     // }
     // catch(Exception ex)
     // {
     // fail("Polyline serialization failure");
     // }
     try
     {
         java.io.InputStream s = Sharpen.Runtime.getClassForType(typeof(com.esri.core.geometry.TestSerialization
                                                                        )).getResourceAsStream("savedPolyline.txt");
         java.io.ObjectInputStream       ii    = new java.io.ObjectInputStream(s);
         com.esri.core.geometry.Polyline ptRes = (com.esri.core.geometry.Polyline)ii.readObject
                                                     ();
         NUnit.Framework.Assert.IsTrue(ptRes != null);
     }
     catch (System.Exception)
     {
         fail("Polyline serialization failure");
     }
 }
コード例 #14
0
 public virtual void testSerializeMultiPoint()
 {
     try
     {
         java.io.ByteArrayOutputStream     streamOut = new java.io.ByteArrayOutputStream();
         java.io.ObjectOutputStream        oo        = new java.io.ObjectOutputStream(streamOut);
         com.esri.core.geometry.MultiPoint pt        = new com.esri.core.geometry.MultiPoint();
         pt.add(10, 30);
         pt.add(120, 40);
         oo.writeObject(pt);
         java.io.ByteArrayInputStream streamIn = new java.io.ByteArrayInputStream(streamOut
                                                                                  .toByteArray());
         java.io.ObjectInputStream         ii    = new java.io.ObjectInputStream(streamIn);
         com.esri.core.geometry.MultiPoint ptRes = (com.esri.core.geometry.MultiPoint)ii.readObject
                                                       ();
         NUnit.Framework.Assert.IsTrue(ptRes.Equals(pt));
     }
     catch (System.Exception)
     {
         fail("MultiPoint serialization failure");
     }
     // try
     // {
     // FileOutputStream streamOut = new FileOutputStream(m_thisDirectory +
     // "savedMultiPoint.txt");
     // ObjectOutputStream oo = new ObjectOutputStream(streamOut);
     // MultiPoint pt = new MultiPoint();
     // pt.add(10, 30);
     // pt.add(120, 40);
     // oo.writeObject(pt);
     // }
     // catch(Exception ex)
     // {
     // fail("MultiPoint serialization failure");
     // }
     try
     {
         java.io.InputStream s = Sharpen.Runtime.getClassForType(typeof(com.esri.core.geometry.TestSerialization
                                                                        )).getResourceAsStream("savedMultiPoint.txt");
         java.io.ObjectInputStream         ii    = new java.io.ObjectInputStream(s);
         com.esri.core.geometry.MultiPoint ptRes = (com.esri.core.geometry.MultiPoint)ii.readObject
                                                       ();
         NUnit.Framework.Assert.IsTrue(ptRes.getPoint(1).getY() == 40);
     }
     catch (System.Exception)
     {
         fail("MultiPoint serialization failure");
     }
 }
コード例 #15
0
 public virtual void testSerializeEnvelope2D()
 {
     try
     {
         java.io.ByteArrayOutputStream     streamOut = new java.io.ByteArrayOutputStream();
         java.io.ObjectOutputStream        oo        = new java.io.ObjectOutputStream(streamOut);
         com.esri.core.geometry.Envelope2D env       = new com.esri.core.geometry.Envelope2D(1.213948734
                                                                                             , 2.213948734, 11.213948734, 12.213948734);
         oo.writeObject(env);
         java.io.ByteArrayInputStream streamIn = new java.io.ByteArrayInputStream(streamOut
                                                                                  .toByteArray());
         java.io.ObjectInputStream         ii     = new java.io.ObjectInputStream(streamIn);
         com.esri.core.geometry.Envelope2D envRes = (com.esri.core.geometry.Envelope2D)ii.
                                                    readObject();
         NUnit.Framework.Assert.IsTrue(envRes.Equals(env));
     }
     catch (System.Exception)
     {
         fail("Envelope2D serialization failure");
     }
     //		try
     //		{
     //			 FileOutputStream streamOut = new FileOutputStream(
     //			 "c:/temp/savedEnvelope2D.txt");
     //			 ObjectOutputStream oo = new ObjectOutputStream(streamOut);
     //			 Envelope2D e = new Envelope2D(177.123, 188.234, 999.122, 888.999);
     //			 oo.writeObject(e);
     //		 }
     //		 catch(Exception ex)
     //		 {
     //		   fail("Envelope2D serialization failure");
     //		 }
     try
     {
         java.io.InputStream s = Sharpen.Runtime.getClassForType(typeof(com.esri.core.geometry.TestSerialization
                                                                        )).getResourceAsStream("savedEnvelope2D.txt");
         java.io.ObjectInputStream         ii = new java.io.ObjectInputStream(s);
         com.esri.core.geometry.Envelope2D e  = (com.esri.core.geometry.Envelope2D)ii.readObject
                                                    ();
         NUnit.Framework.Assert.IsTrue(e != null);
         NUnit.Framework.Assert.IsTrue(e.Equals(new com.esri.core.geometry.Envelope2D(177.123
                                                                                      , 188.234, 999.122, 888.999)));
     }
     catch (System.Exception)
     {
         fail("Envelope2D serialization failure");
     }
 }
コード例 #16
0
ファイル: UriCodec.cs プロジェクト: zhouweiaccp/XobotOS
 /// <param name="convertPlus">true to convert '+' to ' '.</param>
 public static string decode(string s, bool convertPlus, java.nio.charset.Charset
                             charset)
 {
     if (s.IndexOf('%') == -1 && (!convertPlus || s.IndexOf('+') == -1))
     {
         return(s);
     }
     java.lang.StringBuilder       result = new java.lang.StringBuilder(s.Length);
     java.io.ByteArrayOutputStream @out   = new java.io.ByteArrayOutputStream();
     {
         for (int i = 0; i < s.Length;)
         {
             char c = s[i];
             if (c == '%')
             {
                 do
                 {
                     if (i + 2 >= s.Length)
                     {
                         throw new System.ArgumentException("Incomplete % sequence at: " + i);
                     }
                     int d1 = hexToInt(s[i + 1]);
                     int d2 = hexToInt(s[i + 2]);
                     if (d1 == -1 || d2 == -1)
                     {
                         throw new System.ArgumentException("Invalid % sequence " + Sharpen.StringHelper.Substring
                                                                (s, i, i + 3) + " at " + i);
                     }
                     @out.write(unchecked ((byte)((d1 << 4) + d2)));
                     i += 3;
                 }while (i < s.Length && s[i] == '%');
                 result.append(XobotOS.Runtime.Util.GetStringForBytes(@out.toByteArray(), charset)
                               );
                 @out.reset();
             }
             else
             {
                 if (convertPlus && c == '+')
                 {
                     c = ' ';
                 }
                 result.append(c);
                 i++;
             }
         }
     }
     return(result.ToString());
 }
コード例 #17
0
 public void writeRequest(java.io.OutputStream output)
 {
     if (_out != null)
     {
         _buffer = _out.toByteArray();
     }
     if (_buffer != null)
     {
         output.write(_buffer, 0, _buffer.Length);
         _out = null;
     }
     else
     {
         throw new ApplicationException();
     }
 }
コード例 #18
0
 public virtual void TestSerializeSR()
 {
     try
     {
         java.io.ByteArrayOutputStream     streamOut = new java.io.ByteArrayOutputStream();
         java.io.ObjectOutputStream        oo        = new java.io.ObjectOutputStream(streamOut);
         com.epl.geometry.SpatialReference sr        = com.epl.geometry.SpatialReference.Create(102100);
         oo.WriteObject(sr);
         System.IO.BinaryWriter            streamIn = new System.IO.BinaryWriter(streamOut.ToByteArray());
         java.io.ObjectInputStream         ii       = new java.io.ObjectInputStream(streamIn);
         com.epl.geometry.SpatialReference ptRes    = (com.epl.geometry.SpatialReference)ii.ReadObject();
         NUnit.Framework.Assert.IsTrue(ptRes.Equals(sr));
     }
     catch (System.Exception)
     {
         Fail("Spatial Reference serialization failure");
     }
 }
コード例 #19
0
        public void Write()
        {
            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();

            using (JavaOutputStreamWrapper testSubject = NewTestSubject(baos))
            {
                testSubject.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5);
                testSubject.Flush();

                byte[] expected = new byte[] { 1, 2, 3, 4, 5 };
                byte[] actual = baos.toByteArray();

                Assert.AreEqual(expected.Length, actual.Length);

                for (int i = 0; i < expected.Length; i++)
                {
                    Assert.AreEqual(expected[i], actual[i]);
                }
            }
        }
コード例 #20
0
        public void Write()
        {
            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();

            using (JavaOutputStreamWrapper testSubject = NewTestSubject(baos))
            {
                testSubject.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5);
                testSubject.Flush();

                byte[] expected = new byte[] { 1, 2, 3, 4, 5 };
                byte[] actual   = baos.toByteArray();

                Assert.AreEqual(expected.Length, actual.Length);

                for (int i = 0; i < expected.Length; i++)
                {
                    Assert.AreEqual(expected[i], actual[i]);
                }
            }
        }
コード例 #21
0
 public virtual void testSerializeSR()
 {
     try
     {
         java.io.ByteArrayOutputStream           streamOut = new java.io.ByteArrayOutputStream();
         java.io.ObjectOutputStream              oo        = new java.io.ObjectOutputStream(streamOut);
         com.esri.core.geometry.SpatialReference sr        = com.esri.core.geometry.SpatialReference
                                                             .create(102100);
         oo.writeObject(sr);
         java.io.ByteArrayInputStream streamIn = new java.io.ByteArrayInputStream(streamOut
                                                                                  .toByteArray());
         java.io.ObjectInputStream ii = new java.io.ObjectInputStream(streamIn);
         com.esri.core.geometry.SpatialReference ptRes = (com.esri.core.geometry.SpatialReference
                                                          )ii.readObject();
         NUnit.Framework.Assert.IsTrue(ptRes.Equals(sr));
     }
     catch (System.Exception)
     {
         fail("Spatial Reference serialization failure");
     }
 }
コード例 #22
0
 public virtual void TestSerializeLine()
 {
     try
     {
         java.io.ByteArrayOutputStream streamOut = new java.io.ByteArrayOutputStream();
         java.io.ObjectOutputStream    oo        = new java.io.ObjectOutputStream(streamOut);
         com.epl.geometry.Line         pt        = new com.epl.geometry.Line();
         pt.SetStart(new com.epl.geometry.Point(10, 30));
         pt.SetEnd(new com.epl.geometry.Point(120, 40));
         oo.WriteObject(pt);
         System.IO.BinaryWriter    streamIn = new System.IO.BinaryWriter(streamOut.ToByteArray());
         java.io.ObjectInputStream ii       = new java.io.ObjectInputStream(streamIn);
         com.epl.geometry.Line     ptRes    = (com.epl.geometry.Line)ii.ReadObject();
         NUnit.Framework.Assert.IsTrue(ptRes.Equals(pt));
     }
     catch (System.Exception ex)
     {
         // fail("Line serialization failure");
         NUnit.Framework.Assert.AreEqual(ex.Message, "Cannot serialize this geometry");
     }
 }
コード例 #23
0
		protected void SaveStateInClient (FacesContext facesContext, StateManager.SerializedView serializedView) {
			//UIViewRoot uiViewRoot = facesContext.getViewRoot ();
			////save state in response (client-side: full state; server-side: sequence)
			//RenderKit renderKit = RenderKitFactory.getRenderKit (facesContext, uiViewRoot.getRenderKitId ());
			//// not us.
			//renderKit.getResponseStateManager ().writeState (facesContext, serializedView);

			java.io.ByteArrayOutputStream bytearrayoutputstream = new java.io.ByteArrayOutputStream ();
			java.io.ObjectOutputStream objectoutputstream = new java.io.ObjectOutputStream (bytearrayoutputstream);

			//ignore tree structure
			//objectoutputstream.writeObject (serializedView.getStructure ());
			objectoutputstream.writeObject (serializedView.getState ());
			objectoutputstream.close ();
			bytearrayoutputstream.close ();

			string s = 
@"<div>
	<input type=""hidden"" name=""" + VIEWSTATE + "\" id=\"" + VIEWSTATE + "\" value=\"" +
				Convert.ToBase64String ((byte []) vmw.common.TypeUtils.ToByteArray (bytearrayoutputstream.toByteArray ())) + @""" />
</div>";
			facesContext.getResponseWriter ().write (s);
		}
コード例 #24
0
 /// <summary>Return the AudioFileFormat from the given InputStream.</summary>
 /// <remarks>Return the AudioFileFormat from the given InputStream. Implementation.</remarks>
 /// <param name="bitStream"></param>
 /// <param name="baos"></param>
 /// <param name="mediaLength"></param>
 /// <returns>
 /// an AudioInputStream object based on the audio file data contained
 /// in the input stream.
 /// </returns>
 /// <exception>
 /// UnsupportedAudioFileException
 /// if the File does not point to
 /// a valid audio file data recognized by the system.
 /// </exception>
 /// <exception>
 /// IOException
 /// if an I/O exception occurs.
 /// </exception>
 /// <exception cref="javax.sound.sampled.UnsupportedAudioFileException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 protected virtual javax.sound.sampled.AudioFileFormat getAudioFileFormat(java.io.InputStream
     bitStream, java.io.ByteArrayOutputStream baos, int mediaLength)
 {
     javax.sound.sampled.AudioFormat format;
     try
     {
         // If we can't read the format of this stream, we must restore stream to
         // beginning so other providers can attempt to read the stream.
         if (bitStream.markSupported())
         {
             // maximum number of bytes to determine the stream encoding:
             // Size of 1st Ogg Packet (Speex header) = OGG_HEADERSIZE + SPEEX_HEADERSIZE + 1
             // Size of 2nd Ogg Packet (Comment)      = OGG_HEADERSIZE + comment_size + 1
             // Size of 3rd Ogg Header (First data)   = OGG_HEADERSIZE + number_of_frames
             // where number_of_frames < 256 and comment_size < 256 (if within 1 frame)
             bitStream.mark(3 * OGG_HEADERSIZE + SPEEX_HEADERSIZE + 256 + 256 + 2);
         }
         int mode = -1;
         int sampleRate = 0;
         int channels = 0;
         int frameSize = javax.sound.sampled.AudioSystem.NOT_SPECIFIED;
         float frameRate = javax.sound.sampled.AudioSystem.NOT_SPECIFIED;
         byte[] header = new byte[128];
         int segments = 0;
         int bodybytes = 0;
         java.io.DataInputStream dis = new java.io.DataInputStream(bitStream);
         if (baos == null)
         {
             baos = new java.io.ByteArrayOutputStream(128);
         }
         int origchksum;
         int chksum;
         // read the OGG header
         dis.readFully(header, 0, OGG_HEADERSIZE);
         baos.write(header, 0, OGG_HEADERSIZE);
         origchksum = readInt(header, 22);
         header[22] = 0;
         header[23] = 0;
         header[24] = 0;
         header[25] = 0;
         chksum = org.xiph.speex.OggCrc.checksum(0, header, 0, OGG_HEADERSIZE);
         // make sure its a OGG header
         if (!OGGID.Equals(cspeex.StringUtil.getStringForBytes(header, 0, 4)))
         {
             throw new javax.sound.sampled.UnsupportedAudioFileException("missing ogg id!");
         }
         // how many segments are there?
         segments = header[SEGOFFSET] & unchecked((int)(0xFF));
         if (segments > 1)
         {
             throw new javax.sound.sampled.UnsupportedAudioFileException("Corrupt Speex Header: more than 1 segments"
                 );
         }
         dis.readFully(header, OGG_HEADERSIZE, segments);
         baos.write(header, OGG_HEADERSIZE, segments);
         chksum = org.xiph.speex.OggCrc.checksum(chksum, header, OGG_HEADERSIZE, segments);
         // get the number of bytes in the segment
         bodybytes = header[OGG_HEADERSIZE] & unchecked((int)(0xFF));
         if (bodybytes != SPEEX_HEADERSIZE)
         {
             throw new javax.sound.sampled.UnsupportedAudioFileException("Corrupt Speex Header: size="
                  + bodybytes);
         }
         // read the Speex header
         dis.readFully(header, OGG_HEADERSIZE + 1, bodybytes);
         baos.write(header, OGG_HEADERSIZE + 1, bodybytes);
         chksum = org.xiph.speex.OggCrc.checksum(chksum, header, OGG_HEADERSIZE + 1, bodybytes
             );
         // make sure its a Speex header
         if (!SPEEXID.Equals(cspeex.StringUtil.getStringForBytes(header, OGG_HEADERSIZE + 1,
             8)))
         {
             throw new javax.sound.sampled.UnsupportedAudioFileException("Corrupt Speex Header: missing Speex ID"
                 );
         }
         mode = readInt(header, OGG_HEADERSIZE + 1 + 40);
         sampleRate = readInt(header, OGG_HEADERSIZE + 1 + 36);
         channels = readInt(header, OGG_HEADERSIZE + 1 + 48);
         int nframes = readInt(header, OGG_HEADERSIZE + 1 + 64);
         bool vbr = readInt(header, OGG_HEADERSIZE + 1 + 60) == 1;
         // Checksum
         if (chksum != origchksum)
         {
             throw new System.IO.IOException("Ogg CheckSums do not match");
         }
         // Calculate frameSize
         if (!vbr)
         {
         }
         // Frames size is a constant so:
         // Read Comment Packet the Ogg Header of 1st data packet;
         // the array table_segment repeats the frame size over and over.
         // Calculate frameRate
         if (mode >= 0 && mode <= 2 && nframes > 0)
         {
             frameRate = ((float)sampleRate) / ((mode == 0 ? 160f : (mode == 1 ? 320f : 640f))
                  * ((float)nframes));
         }
         format = new javax.sound.sampled.AudioFormat(org.xiph.speex.spi.SpeexEncoding.SPEEX
             , (float)sampleRate, javax.sound.sampled.AudioSystem.NOT_SPECIFIED, channels, frameSize
             , frameRate, false);
     }
     catch (javax.sound.sampled.UnsupportedAudioFileException e)
     {
         // reset the stream for other providers
         if (bitStream.markSupported())
         {
             bitStream.reset();
         }
         // just rethrow this exception
         throw;
     }
     catch (System.IO.IOException ioe)
     {
         // reset the stream for other providers
         if (bitStream.markSupported())
         {
             bitStream.reset();
         }
         throw new javax.sound.sampled.UnsupportedAudioFileException(ioe.Message);
     }
     return new javax.sound.sampled.AudioFileFormat(org.xiph.speex.spi.SpeexFileFormatType
         .SPEEX, format, javax.sound.sampled.AudioSystem.NOT_SPECIFIED);
 }
コード例 #25
0
 /// <summary>Obtains an audio input stream from the input stream provided.</summary>
 /// <remarks>
 /// Obtains an audio input stream from the input stream provided.
 /// The stream must point to valid audio file data.
 /// </remarks>
 /// <param name="inputStream">
 /// the input stream from which the AudioInputStream should
 /// be constructed.
 /// </param>
 /// <param name="medialength"></param>
 /// <returns>
 /// an AudioInputStream object based on the audio file data contained
 /// in the input stream.
 /// </returns>
 /// <exception>
 /// UnsupportedAudioFileException
 /// if the File does not point to
 /// a valid audio file data recognized by the system.
 /// </exception>
 /// <exception>
 /// IOException
 /// if an I/O exception occurs.
 /// </exception>
 /// <exception cref="javax.sound.sampled.UnsupportedAudioFileException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 protected virtual javax.sound.sampled.AudioInputStream getAudioInputStream(java.io.InputStream
     inputStream, int medialength)
 {
     java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(128);
     javax.sound.sampled.AudioFileFormat audioFileFormat = getAudioFileFormat(inputStream
         , baos, medialength);
     java.io.ByteArrayInputStream bais = new java.io.ByteArrayInputStream(baos.toByteArray
         ());
     java.io.SequenceInputStream sequenceInputStream = new java.io.SequenceInputStream
         (bais, inputStream);
     return new javax.sound.sampled.AudioInputStream(sequenceInputStream, audioFileFormat
         .getFormat(), audioFileFormat.getFrameLength());
 }
コード例 #26
0
        // can we send a zip file?
        public static void Invoke(int index, Action<string> y, int frames = 4)
        {
            #region log
            var st = new Stopwatch();
            st.Start();
            Action<string> log =
                x =>
                {
                    var z = (st.Elapsed + " " + x);

                    Console.WriteLine(z);
                    y(z);
                };
            #endregion

            log("getting ready...");

            var DIRECTORY_DCIM = global::android.os.Environment.DIRECTORY_DCIM;

            var path = global::android.os.Environment.getExternalStoragePublicDirectory(DIRECTORY_DCIM).getAbsolutePath();
            path += "/Camera";

            //var n = DateTime.Now;
            //var f = new java.io.File(path + "/shot" + n.Ticks + ".jpg");

            var camera = default(android.hardware.Camera);
            var surface = default(SurfaceView);

            try
            {
                // PreviewCallbackWithBuffer { cc = 0, Length = 1048576 }
                // W/CameraService(   84): CameraService::connect X (pid 2117) rejected (existing client).

                log("android.hardware.Camera.open... " + new { index });

                camera = android.hardware.Camera.open(index);

                log("android.hardware.Camera.open... done ");

                var PreviewFormat = ImageFormat.UNKNOWN;

                #region setParameters
                var p = camera.getParameters();

                // The size of the buffer must match the values described above.
                // Gets the supported preview formats. NV21 is always supported.

                // http://developer.android.com/reference/android/hardware/Camera.Parameters.html#getSupportedPreviewFormats()

                #region SupportedPictureFormat

                foreach (int SupportedPictureFormat in p.getSupportedPictureFormats().AsEnumerable())
                {
                    Console.WriteLine(new { SupportedPictureFormat });
                }

                //p.getSupportedPictureFormats().With(
                //     pformats =>
                //     {
                //         for (int i = 0; i < pformats.size(); i++)
                //         {
                //             var SupportedPictureFormat = (int)pformats.get(i);

                //             Console.WriteLine(new { SupportedPictureFormat });
                //         }
                //     }
                // );
                #endregion



                #region SupportedPreviewFormat

                foreach (int SupportedPreviewFormat in p.getSupportedPreviewFormats().AsEnumerable())
                {

                    if (SupportedPreviewFormat == ImageFormat.NV21)
                        PreviewFormat = SupportedPreviewFormat;
                    else if (PreviewFormat == ImageFormat.UNKNOWN)
                        PreviewFormat = SupportedPreviewFormat;

                    log("" + new { SupportedPreviewFormat });

                    Console.WriteLine(new { SupportedPreviewFormat });
                }
                //p.getSupportedPreviewFormats().With(
                //    pformats =>
                //    {
                //        for (int i = 0; i < pformats.size(); i++)
                //        {
                //            var SupportedPreviewFormat = (int)pformats.get(i);


                //            if (SupportedPreviewFormat == ImageFormat.NV21)
                //                PreviewFormat = SupportedPreviewFormat;
                //            else if (PreviewFormat == ImageFormat.UNKNOWN)
                //                PreviewFormat = SupportedPreviewFormat;

                //            log("" + new { SupportedPreviewFormat });
                //        }
                //    }
                //);
                #endregion


                //p.setPictureFormat(ImageFormat.YV12);

                p.setPreviewFormat(PreviewFormat);


                //D/DOMX    (  127): ERROR: failed check:(eError == OMX_ErrorNone) || (eError == OMX_ErrorNoMore) - returning error: 0x80001005 - Error returned from OMX API in ducati
                //E/CameraHAL(  127): Error while configuring rotation 0x80001005
                // http://questiontrack.com/galaxy-nexus-specificaly-camera-startpreview-failed-993603.html
                // http://stackoverflow.com/questions/16839869/orientation-error-causing-crash

                ////p.setRotation(0);

                #region getSupportedPreviewSizes
                //var s = p.getSupportedPreviewSizes();

                var min = default(android.hardware.Camera.Size);

                //for (int i = 0; i < s.size(); i++)
                foreach (android.hardware.Camera.Size size in p.getSupportedPreviewSizes().AsEnumerable())
                {
                    //var size = (android.hardware.Camera.Size)s.get(i);

                    //                I/System.Console( 6058): before takePicture { f = /mnt/sdcard/Pictures/shot.jpg }
                    //I/System.Console( 6058): { size = android.hardware.Camera$Size@4fde180 }

                    var SupportedPreviewSize = new { size.width, size.height };
                    log("" + new { SupportedPreviewSize });

                    if (min == null)
                        min = size;
                    else if (min.width > size.width)
                        min = size;

                }


                #endregion
                p.setPreviewSize(min.width, min.height);

                //For formats besides YV12, the size of the buffer is determined by multiplying the
                // preview image width, height, and bytes per pixel. The width and height can be read 
                // from getPreviewSize(). Bytes per pixel can be computed from getBitsPerPixel(int) / 8, 
                // using the image format from getPreviewFormat().

                //p.setPictureSize(min.width, min.height);


                // I/System.Console( 2860): { width = 640, height = 480, bytesperpixel = 0, buffersize = 0 }
                // the number of bits per pixel of the given format or -1 if the format doesn't exist or is not supported.
                //var bytesperpixel = (ImageFormat.getBitsPerPixel(ImageFormat.NV21) / 8);

                // http://stackoverflow.com/questions/13703596/mediacodec-and-camera-colorspaces-dont-match
                // https://code.google.com/p/android/issues/detail?id=37655

                var bitsperpixel = (ImageFormat.getBitsPerPixel(PreviewFormat));
                var buffersize = min.width * min.height / 8 * bitsperpixel;

                // 12
                // http://www.fourcc.org/yuv.php

                //var buffersize = 460800;

                log("" + new { min.width, min.height, bitsperpixel, buffersize });


                #region setFocusMode
                var focusModes = p.getSupportedFocusModes();
                var NextFocus = android.hardware.Camera.Parameters.FOCUS_MODE_FIXED;

                for (int i = 0; i < focusModes.size(); i++)
                {
                    var focusMode = (string)focusModes.get(i);

                    if (focusMode == android.hardware.Camera.Parameters.FOCUS_MODE_INFINITY)
                        NextFocus = android.hardware.Camera.Parameters.FOCUS_MODE_INFINITY;

                    System.Console.WriteLine(new { focusMode });
                }

                p.setFocusMode(NextFocus);
                #endregion

                camera.setParameters(p);
                #endregion


                // preview layout size: 736/1216
                buffersize = 1843200;

                // E/Camera-JNI( 3148): Manually set buffer was too small! Expected 460800 bytes, but got 307200!
                camera.addCallbackBuffer(new sbyte[buffersize]);
                camera.addCallbackBuffer(new sbyte[buffersize]);
                camera.addCallbackBuffer(new sbyte[buffersize]);
                camera.addCallbackBuffer(new sbyte[buffersize]);
                camera.addCallbackBuffer(new sbyte[buffersize]);

                var a = new EventWaitHandle(false, EventResetMode.ManualReset);

                // Task.ContinueWith
                // await

                (ScriptCoreLib.Android.ThreadLocalContextReference.CurrentContext as Activity).StartNew(
                    aa =>
                    {
                        log("at runOnUiThread...");


                        // solve issue with callback not being called: release the camera and try again. It usually works.
                        //To solve issue with rotation 0x80001005: restart app / service

                        // http://stackoverflow.com/questions/13546788/camera-takepicture-not-working-on-my-jb-gb-froyo-phones
                        aa.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);


                        #region setErrorCallback
                        camera.setErrorCallback(
                           new XErrorCallback
                           {
                               yield = (err, c) =>
                               {
                                   log("" + new { err });
                               }

                           }
                       );
                        #endregion

                        surface = new SurfaceView(ScriptCoreLib.Android.ThreadLocalContextReference.CurrentContext);

                        var holder = surface.getHolder();

                        // http://developer.android.com/reference/android/view/SurfaceHolder.html#SURFACE_TYPE_PUSH_BUFFERS
                        var SURFACE_TYPE_PUSH_BUFFERS = 0x00000003;
                        holder.setType(SURFACE_TYPE_PUSH_BUFFERS);




                        log("setPreviewCallbackWithBuffer");

                        var cc = 0;

                        //E/CameraHardwareSec(   84): int android::CameraHardwareSec::previewThread(): mSkipFrame(3) > 0
                        //E/CameraHardwareSec(   84): int android::CameraHardwareSec::previewThread(): mSkipFrame(2) > 0
                        //E/CameraHardwareSec(   84): int android::CameraHardwareSec::previewThread(): mSkipFrame(1) > 0

                        // http://stackoverflow.com/questions/16878042/camera-not-working-in-google-nexus-tablet

                        #region camera.PreviewCallbackWithBuffer
                        camera.PreviewCallbackWithBuffer(
                            (rawdata, c) =>
                            {
                                if (surface == null)
                                {
                                    // W/CameraHardwareSec(   84): virtual android::status_t android::CameraHardwareSec::cancelPicture() : not supported, just returning NO_ERROR
                                    return;
                                }

                                //                                                                   10080.0ms PreviewCallbackWithBuffer enter { cc = 58, Length = 460800 }
                                //10119.0ms PreviewCallbackWithBuffer compressToJpeg done { cc = 58, Elapsed = 39.0ms }
                                //10174.0ms PreviewCallbackWithBuffer ToBase64String done { cc = 58, Elapsed = 94.0ms }

                                var xcc = cc;

                                log("PreviewCallbackWithBuffer enter " + new { xcc, rawdata.Length });

                                // failed to flush { Length = 14619 }
                                //new Thread(
                                //    delegate()
                                {
                                    if (surface == null)
                                    {
                                        // W/CameraHardwareSec(   84): virtual android::status_t android::CameraHardwareSec::cancelPicture() : not supported, just returning NO_ERROR
                                        return;
                                    }

                                    var cst = new Stopwatch();
                                    cst.Start();

                                    // http://stackoverflow.com/questions/3426614/android-converting-from-nv21-preview-format-on-nexus-one-to-jpeg
                                    // http://developer.android.com/reference/android/graphics/YuvImage.html

                                    //Caused by: java.lang.IllegalArgumentException: only support ImageFormat.NV21 and ImageFormat.YUY2 for now
                                    //at android.graphics.YuvImage.<init>(YuvImage.java:82)


                                    // https://code.google.com/p/android/issues/detail?id=823
                                    // https://code.google.com/p/android-source-browsing/source/browse/graphics/java/android/graphics/YuvImage.java?repo=platform--frameworks--base&name=android-cts-4.1_r1
                                    var yuv = new YuvImage(
                                        rawdata,
                                        PreviewFormat,
                                        min.width,
                                        min.height,
                                        null
                                    );

                                    var m = new java.io.ByteArrayOutputStream();

                                    yuv.compressToJpeg(
                                        new Rect(0, 0, min.width, min.height),
                                        20,
                                        m);

                                    var data = (byte[])(object)m.toByteArray();

                                    log("PreviewCallbackWithBuffer compressToJpeg done " + new { xcc, cst.Elapsed });


                                    Console.WriteLine("compressToJpeg "
                                        + new { data.Length }
                                    );

                                    var src = "data:image/jpg;base64," +
                                            Convert.ToBase64String(
                                                data
                                            );

                                    log("PreviewCallbackWithBuffer ToBase64String done " + new { xcc, cst.Elapsed });

                                    y(src);


                                    //PreviewCallbackWithBuffer { cc = 0, Length = 1048576 }

                                    if (surface == null)
                                    {
                                        // W/CameraHardwareSec(   84): virtual android::status_t android::CameraHardwareSec::cancelPicture() : not supported, just returning NO_ERROR
                                        return;
                                    }

                                    //camera.addCallbackBuffer();
                                    camera.addCallbackBuffer(new sbyte[buffersize]);

                                    log("PreviewCallbackWithBuffer exit " + new { xcc, cst.Elapsed });


                                    if (xcc == frames)
                                    {

                                        //dummy.setVisibility(View.GONE);
                                        //dummy = null;

                                        // Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

                                        aa.StartNew(
                                                delegate
                                                {
                                                    if (surface != null)
                                                    {
                                                        surface.setVisibility(View.GONE);
                                                        surface = null;

                                                    }

                                                    a.Set();
                                                }
                                        );
                                    }
                                }
                                //).Start();

                                cc++;


                            }
                        );
                        #endregion


                        #region holder.surfaceChanged
                        holder.surfaceChanged(
                            delegate
                            {
                                log("surfaceChanged?");
                            }
                        );
                        #endregion

                        #region holder.surfaceCreated
                        holder.surfaceCreated(
                            delegate
                            {
                                log("surfaceCreated!");

                                // http://stackoverflow.com/questions/12098298/android-camera-app-passed-null-surface
                                // http://stackoverflow.com/questions/16945524/app-passed-null-surface-while-taking-a-picture-without-a-surfaceview

                                //  app passed NULL surface
                                log("before setPreviewDisplay, delay");

                                Thread.Sleep(400);

                                // https://code.google.com/p/zxing/source/browse/trunk/android/src/com/google/zxing/client/android/camera/CameraManager.java
                                // http://stackoverflow.com/questions/16945524/app-passed-null-surface-while-taking-a-picture-without-a-surfaceview

                                // http://stackoverflow.com/questions/4852740/surfaceview-getholder-not-returning-surfaceholder

                                log("before setPreviewDisplay " + new { holder });
                                // inside surface changed?

                                //if (surface == 0)
                                //{
                                //    LOGE("app passed NULL surface");
                                //    return NO_INIT;
                                //}

                                // https://android.googlesource.com/platform/frameworks/native/+/a6938bab1f6fa76ae98ebbe44f4e534e05fa0993/libs/ui/Camera.cpp
                                camera.setTryPreviewDisplay(holder);
                                log("after setPreviewDisplay");


                                log("startPreview, delay");
                                Thread.Sleep(200);
                                log("startPreview");

                                camera.startPreview();
                                log("after startPreview");
                            }
                        );
                        #endregion


                        #region addContentView
                        //surface.setBackgroundColor(Color.argb(0x0F, 255, 0, 0));

                        var pp = new android.widget.LinearLayout.LayoutParams(
                            android.widget.LinearLayout.LayoutParams.FILL_PARENT,
                            android.widget.LinearLayout.LayoutParams.FILL_PARENT
                            );
                        //pp.setMargins(64, 64, 64, 64);

                        aa.addContentView(surface, pp);
                        #endregion





                    }
                );

                a.WaitOne();

                log("PreviewCallbackWithBuffer done");

            }
            catch (Exception ex)
            {
                log("error: " + new { ex.Message, ex.StackTrace });

                throw new Exception("", ex);
            }
            finally
            {
                log("finally");
                // using
                if (camera != null)
                {
                    camera.stopPreview();
                    camera.release();
                    camera = null;
                }


            }
        }
コード例 #27
0
ファイル: Streams.cs プロジェクト: hakeemsm/XobotOS
		/// <summary>Returns a byte[] containing the remainder of 'in'.</summary>
		/// <remarks>Returns a byte[] containing the remainder of 'in'.</remarks>
		/// <exception cref="System.IO.IOException"></exception>
		public static byte[] readFullyNoClose(java.io.InputStream @in)
		{
			java.io.ByteArrayOutputStream bytes = new java.io.ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int count;
			while ((count = @in.read(buffer)) != -1)
			{
				bytes.write(buffer, 0, count);
			}
			return bytes.toByteArray();
		}
コード例 #28
0
			public void writeRequest(java.io.OutputStream output)
			{
				if(_out != null)
					_buffer = _out.toByteArray();
				if(_buffer != null)
				{
					output.write(_buffer, 0, _buffer.Length);
					_out = null;
				}
				else throw new ApplicationException();
			}
コード例 #29
0
			public long getContentLength()
			{
				if(_out != null)
				{
					_buffer = _out.toByteArray();
				}
				if(_buffer != null)
				{
					_contentLength = _buffer.Length;
					_out = null;
				}
				return _contentLength;
			}
コード例 #30
0
			internal OutputStreamRequestEntity(long length)
			{
				_contentLength = length;
				int tmp = (int) _contentLength;

				if(tmp <=0)
					tmp = 4096;
				_out = new java.io.ByteArrayOutputStream(tmp);
			}
コード例 #31
0
ファイル: UriCodec.cs プロジェクト: hakeemsm/XobotOS
		/// <param name="convertPlus">true to convert '+' to ' '.</param>
		public static string decode(string s, bool convertPlus, java.nio.charset.Charset 
			charset)
		{
			if (s.IndexOf('%') == -1 && (!convertPlus || s.IndexOf('+') == -1))
			{
				return s;
			}
			java.lang.StringBuilder result = new java.lang.StringBuilder(s.Length);
			java.io.ByteArrayOutputStream @out = new java.io.ByteArrayOutputStream();
			{
				for (int i = 0; i < s.Length; )
				{
					char c = s[i];
					if (c == '%')
					{
						do
						{
							if (i + 2 >= s.Length)
							{
								throw new System.ArgumentException("Incomplete % sequence at: " + i);
							}
							int d1 = hexToInt(s[i + 1]);
							int d2 = hexToInt(s[i + 2]);
							if (d1 == -1 || d2 == -1)
							{
								throw new System.ArgumentException("Invalid % sequence " + Sharpen.StringHelper.Substring
									(s, i, i + 3) + " at " + i);
							}
							@out.write(unchecked((byte)((d1 << 4) + d2)));
							i += 3;
						}
						while (i < s.Length && s[i] == '%');
						result.append(XobotOS.Runtime.Util.GetStringForBytes(@out.toByteArray(), charset)
							);
						@out.reset();
					}
					else
					{
						if (convertPlus && c == '+')
						{
							c = ' ';
						}
						result.append(c);
						i++;
					}
				}
			}
			return result.ToString();
		}
コード例 #32
0
ファイル: blala.cs プロジェクト: fboas/OutlawzChecker
        public static string check(string proxy, string combo)
        {
            try
            {
                HttpRequest vlient = new HttpRequest();
                JArray      lol    =
                    JArray.Parse(
                        JObject.Parse(vlient.Get("http://apresolve.spotify.com/?type=accesspoint").ToString())[
                            "accesspoint"].ToString());
                TcpClient clinet = null;
                Random    random = new Random();

                string host = lol[random.Next(0, lol.Count)].ToString();

                if (proxy == "null")
                {
                    clinet = new TcpClient(host.Split(':')[0], int.Parse(host.Split(':')[1]));
                }
                else
                {
                    clinet = ProxyTcpClient(host.Split(':')[0], int.Parse(host.Split(':')[1]), proxy.Split(':')[0], int.Parse(proxy.Split(':')[1]));
                }
                //clinet = new TcpClient(host.Split(':')[0], int.Parse(host.Split(':')[1]));
                if (clinet == null)
                {
                    return("error");
                }

                clinet.ReceiveTimeout = 4000;
                clinet.SendTimeout    = 4000;
                com.JB.crypto.DiffieHellman keys = new com.JB.crypto.DiffieHellman(new java.util.Random());
                byte[]      clientHello          = com.JB.core.Session.clientHello(keys);
                Accumulator acc = new Accumulator();

                var a = clinet.GetStream();
                a.WriteByte(0x00);
                a.WriteByte(0x04);
                a.WriteByte(0x00);
                a.WriteByte(0x00);
                a.WriteByte(0x00);
                a.Flush();
                int    lenght = 2 + 4 + clientHello.Length;
                byte[] bytes  = BitConverter.GetBytes(lenght);
                a.WriteByte(bytes[0]);
                a.Write(clientHello, 0, clientHello.Length);
                a.Flush();
                Byte[] buffer = new byte[1000];
                int    len    = int.Parse(a.Read(buffer, 0, buffer.Length).ToString());
                byte[] tmp    = new byte[len];
                Array.Copy(buffer, tmp, len);

                tmp = tmp.Skip(4).ToArray();

                acc.writeByte(0x00);
                acc.writeByte(0x04);
                acc.writeInt(lenght);
                acc.write(clientHello);
                acc.writeInt(len);
                acc.write(tmp);
                acc.dump();

                com.spotify.Keyexchange.APResponseMessage apResponseMessage =
                    com.spotify.Keyexchange.APResponseMessage.parseFrom(tmp);
                byte[] sharedKey = com.JB.common.Utils.toByteArray(keys.computeSharedKey(apResponseMessage
                                                                                         .getChallenge().getLoginCryptoChallenge().getDiffieHellman().getGs().toByteArray()));

                java.security.KeyFactory factory   = java.security.KeyFactory.getInstance("RSA");
                java.security.PublicKey  publicKey = factory.generatePublic(
                    new java.security.spec.RSAPublicKeySpec(new java.math.BigInteger(1, serverKey),
                                                            java.math.BigInteger.valueOf(65537)));
                java.security.Signature sig = java.security.Signature.getInstance("SHA1withRSA");
                sig.initVerify(publicKey);
                sig.update(apResponseMessage.getChallenge().getLoginCryptoChallenge().getDiffieHellman().getGs()
                           .toByteArray());
                sig.verify(apResponseMessage.getChallenge().getLoginCryptoChallenge().getDiffieHellman()
                           .getGsSignature().toByteArray());

                java.io.ByteArrayOutputStream data = new java.io.ByteArrayOutputStream(100);

                javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
                mac.init(new javax.crypto.spec.SecretKeySpec(sharedKey, "HmacSHA1"));
                for (int i = 1; i < 6; i++)
                {
                    mac.update(acc.array());
                    mac.update(new byte[] { (byte)i });
                    data.write(mac.doFinal());
                    mac.reset();
                }

                byte[] dataArray = data.toByteArray();
                mac = javax.crypto.Mac.getInstance("HmacSHA1");
                mac.init(new javax.crypto.spec.SecretKeySpec(java.util.Arrays.copyOfRange(dataArray, 0, 0x14),
                                                             "HmacSHA1"));
                mac.update(acc.array());
                byte[] challenge = mac.doFinal();

                com.spotify.Keyexchange.ClientResponsePlaintext clientResponsePlaintext = com.spotify.Keyexchange
                                                                                          .ClientResponsePlaintext.newBuilder()
                                                                                          .setLoginCryptoResponse(com.spotify.Keyexchange.LoginCryptoResponseUnion.newBuilder()
                                                                                                                  .setDiffieHellman(com.spotify.Keyexchange.LoginCryptoDiffieHellmanResponse.newBuilder()
                                                                                                                                    .setHmac(com.google.protobuf.ByteString.copyFrom(challenge)).build())
                                                                                                                  .build())
                                                                                          .setPowResponse(com.spotify.Keyexchange.PoWResponseUnion.newBuilder().build())
                                                                                          .setCryptoResponse(com.spotify.Keyexchange.CryptoResponseUnion.newBuilder().build())
                                                                                          .build();

                byte[] clientResponsePlaintextBytes = clientResponsePlaintext.toByteArray();
                len = 4 + clientResponsePlaintextBytes.Length;
                a.WriteByte(0x00);
                a.WriteByte(0x00);
                a.WriteByte(0x00);
                byte[] bytesb = BitConverter.GetBytes(len);
                a.WriteByte(bytesb[0]);
                a.Write(clientResponsePlaintextBytes, 0, clientResponsePlaintextBytes.Length);
                a.Flush();

                com.spotify.Authentication.LoginCredentials loginCredentials = com.spotify.Authentication
                                                                               .LoginCredentials.newBuilder()
                                                                               .setUsername(combo.Split(':')[0])
                                                                               .setTyp(com.spotify.Authentication.AuthenticationType.AUTHENTICATION_USER_PASS)
                                                                               .setAuthData(com.google.protobuf.ByteString.copyFromUtf8(combo.Split(':')[1]))
                                                                               .build();

                com.spotify.Authentication.ClientResponseEncrypted clientResponseEncrypted = com.spotify.Authentication
                                                                                             .ClientResponseEncrypted.newBuilder()
                                                                                             .setLoginCredentials(loginCredentials)
                                                                                             .setSystemInfo(com.spotify.Authentication.SystemInfo.newBuilder()
                                                                                                            .setOs(com.spotify.Authentication.Os.OS_UNKNOWN)
                                                                                                            .setCpuFamily(com.spotify.Authentication.CpuFamily.CPU_UNKNOWN)
                                                                                                            .setSystemInformationString(com.JB.Version.systemInfoString())
                                                                                                            .setDeviceId(com.JB.common.Utils.randomHexString(new java.util.Random(), 30))
                                                                                                            .build())
                                                                                             .setVersionString(com.JB.Version.versionString())
                                                                                             .build();

                com.JB.crypto.Shannon sendCipher = new com.JB.crypto.Shannon();
                sendCipher.key(java.util.Arrays.copyOfRange(data.toByteArray(), 0x14, 0x34));
                AtomicInteger sendNonce = new AtomicInteger(0);

                com.JB.crypto.Shannon recvCipher = new com.JB.crypto.Shannon();
                recvCipher.key(java.util.Arrays.copyOfRange(data.toByteArray(), 0x34, 0x54));
                AtomicInteger recvNonce = new AtomicInteger(0);
                sendCipher.nonce(com.JB.common.Utils.toByteArray(sendNonce.getAndIncrement()));

                java.nio.ByteBuffer buffer2 =
                    java.nio.ByteBuffer.allocate(1 + 2 + clientResponseEncrypted.toByteArray().Length);
                buffer2.put(com.JB.crypto.Packet.Type.Login.val)
                .putShort((short)clientResponseEncrypted.toByteArray().Length)
                .put(clientResponseEncrypted.toByteArray());

                byte[] bytess = buffer2.array();
                sendCipher.encrypt(bytess);
                byte[] macc = new byte[4];
                sendCipher.finish(macc);
                a.Write(bytess, 0, bytess.Length);
                a.Write(macc, 0, macc.Length);
                a.Flush();
                recvCipher.nonce(com.JB.common.Utils.toByteArray(recvNonce.getAndIncrement()));

                byte[] headerBytes = new byte[3];
                a.Read(headerBytes, 0, 3);
                recvCipher.decrypt(headerBytes);

                short  payloadLength = (short)((headerBytes[1] << 8) | (headerBytes[2] & 0xFF));
                byte[] payloadBytes  = new byte[payloadLength];
                a.Read(payloadBytes, 0, payloadBytes.Length);
                recvCipher.decrypt(payloadBytes);

                byte[] maccc = new byte[4];
                a.Read(maccc, 0, maccc.Length);
                if (headerBytes[0] == 172)
                {
                    com.spotify.Authentication.APWelcome apWelcome = com.spotify.Authentication.APWelcome.parseFrom(payloadBytes);

                    int    i    = 0;
                    string lel  = "";
                    string lel2 = "";
                    while (true)
                    {
                        recvCipher.nonce(com.JB.common.Utils.toByteArray(recvNonce.getAndIncrement()));

                        headerBytes = new byte[3];
                        a.Read(headerBytes, 0, 3);
                        recvCipher.decrypt(headerBytes);

                        payloadLength = (short)((headerBytes[1] << 8) | (headerBytes[2] & 0xFF));
                        payloadBytes  = new byte[payloadLength];
                        a.Read(payloadBytes, 0, payloadBytes.Length);
                        Thread.Sleep(10);
                        recvCipher.decrypt(payloadBytes);
                        maccc = new byte[4];
                        a.Read(maccc, 0, maccc.Length);

                        //File.WriteAllBytes(headerBytes[0]+".txt",payloadBytes);
                        if (headerBytes[0] == 27)
                        {
                            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                            lel2 = enc.GetString(payloadBytes);
                            i++;
                        }
                        if (headerBytes[0] == 80)
                        {
                            Console.WriteLine(com.JB.core.Session.parse(payloadBytes).get("financial-product").ToString());
                            lel = com.JB.core.Session.parse(payloadBytes).get("financial-product").ToString();
                            i++;
                        }

                        if (i >= 2)
                        {
                            return(lel + "-lol-" + apWelcome + "-lol-" + lel2);
                        }
                    }
                }
                else if (headerBytes[0] == 173)
                {
                    return("invalid");
                }
            }
            catch (Exception ex)
            {
                return("error");
            }

            return("error");
        }
コード例 #33
0
ファイル: RuleBase.cs プロジェクト: happy280684/droolsdotnet
 public void Save(Stream stream)
 {
     //FileOutputStream _javastream = new FileOutputStream(filePath);
     java.io.ByteArrayOutputStream byteStream = new java.io.ByteArrayOutputStream();
     java.io.ObjectOutput objOut = new DotnetObjectOutputStream(byteStream);
     ((ReteooRuleBase)this._javaRuleBase).writeExternal(objOut);
     stream.Write(byteStream.toByteArray(), 0, byteStream.toByteArray().Length);
     byteStream.close();
 }