internal override void LoadMusic(SoundMusic music)
        {
            loadTime.Restart();
            try
            {
                using (var javaFileStream = new FileInputStream(music.FileName))
                    mediaPlayer.SetDataSource(javaFileStream.FD, music.StartPosition, music.Length);

                mediaPlayer.PrepareAsync();

                CurrentMusic = music;
            }
            catch (IOException)
            {
                // this can happen namely if too many files are already opened (should not throw an exception)
                Logger.Warning("The audio file '{0}' could not be opened", music.FileName);
            }
            catch (SecurityException)
            {
                throw new InvalidOperationException("The sound file is not accessible anymore.");
            }
            catch (IllegalArgumentException e)
            {
                throw new AudioSystemInternalException("Error during the SetDataSouce: "+e);
            }
        }
示例#2
0
		public override void OnWrite (PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, Android.Print.PrintDocumentAdapter.WriteResultCallback callback)
		{
			InputStream input = null;
			OutputStream output = null;

			try {


				input = new FileInputStream (PathToDoc);
				output = new FileOutputStream (destination.FileDescriptor);

				byte[] buf = new byte[1024];
				int bytesRead;

				while ((bytesRead = input.Read (buf)) > 0) {
					output.Write (buf, 0, bytesRead);
				}

				callback.OnWriteFinished (new PageRange[]{ PageRange.AllPages });

			} catch (System.IO.FileNotFoundException ee) {
				Insights.Report (ee);
			} catch (Exception e) {
				Insights.Report (e);
			} finally {
				try {
					input.Close ();
					output.Close ();
				} catch (Java.IO.IOException e) {
					e.PrintStackTrace ();
				}
			}
		}
示例#3
0
文件: Load.cs 项目: orico/shogun
 public static string[] load_dna(string filename)
 {
     List<string> list = new List<string>();
     string[] result = null;
     try
     {
         FileInputStream fstream = new FileInputStream(filename);
         DataInputStream @in = new DataInputStream(fstream);
         BufferedReader buffer = new BufferedReader(new InputStreamReader(@in));
         string line;
         while((line = buffer.readLine()) != null)
         {
             list.Add(line);
         }
         @in.close();
         result = new string[list.Count];
         for (int i = 0; i < list.Count; i++)
         {
             result[i] = (string)list[i];
         }
     }
     catch(java.io.IOException e)
     {
         Console.WriteLine("Unable to create matrix from " + filename + ": " + e.Message);
         Environment.Exit(-1);
     }
     return result;
 }
示例#4
0
        public void Play(string filePath)
        {
            try
            {
                if (player == null)
                {
                    player = new MediaPlayer();
                }
                else
                {
                    player.Reset();
                }

                // This method works better than setting the file path in SetDataSource. Don't know why.
                var file = new File(filePath);
                var fis = new FileInputStream(file);

                player.SetDataSource(fis.FD);

                //player.SetDataSource(filePath);
                player.Prepare();
                player.Start();
            }
            catch (Exception ex)
            {
                System.Console.Out.WriteLine(ex.StackTrace);
            }
        }
示例#5
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 int findDuration(string filename)
 {
     MediaPlayer wav = new MediaPlayer();
     FileInputStream fs = new FileInputStream(filename);
     FileDescriptor fd = fs.FD;
     wav.SetDataSource(fd);
     wav.Prepare();
     int length = wav.Duration;
     wav.Reset();
     wav.Release();
     return length;
 }
示例#7
0
 public int videoDuration(string filename)
 {
     MediaPlayer video = new MediaPlayer();
     FileInputStream fs = new FileInputStream(filename);
     FileDescriptor fd = fs.FD;
     video.SetDataSource(fd);
     video.Prepare();
     int length = video.Duration;
     video.Reset();
     video.Release();
     return length;
 }
 public static object load(string fname)
 {
     object r = null;
     try
     {
         FileInputStream fs = new FileInputStream(fname);
         ObjectInputStream @in = new ObjectInputStream(fs);
         r = @in.readObject();
         @in.close();
         return r;
     }
     catch(Exception ex)
     {
         ex.printStackTrace();
     }
     return r;
 }
        //Compare audio files
        private static float compareAudio(string filename1, string filename2)
        {
            //string resStr = "";
            float result = 0;
            //float score = 0;

            InputStream isOne = new FileInputStream(filename1);
            InputStream isTwo = new FileInputStream(filename2);

            Wave wavFile1 = new Wave(isOne);
            Wave wavFile2 = new Wave(isTwo);

            FingerprintSimilarity sim;

            sim    = wavFile1.getFingerprintSimilarity(wavFile2);
            result = sim.getSimilarity() * 100;
            return(result);
        }
示例#10
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode != Result.Ok)
            {
                return;
            }
            byte[] bytes;

            using (var stream = new FileInputStream(arquivoImagem))
            {
                bytes = new byte[arquivoImagem.Length()];
                stream.Read(bytes);
            }

            MessagingCenter.Send(bytes, "FotoTirada");
        }
示例#11
0
        /**
         * 将图片转换成Base64编码
         * @param imgFile 待处理图片
         * @return
         */
        public static String GetImgStr(String imgFile)
        {
            //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
            InputStream inFile = null;

            byte[] data = null;
            //读取图片字节数组
            try
            {
                inFile = new FileInputStream(imgFile);
                data   = new byte[inFile.Available()];
                inFile.Read(data);
                inFile.Close();
            }
            catch
            { }
            return("data:image/jpeg;base64," + Convert.ToBase64String(data));
        }
示例#12
0
 public static FileDescriptor GetMediaFileDescriptor(Context context, byte[] byteArray)
 {
     try
     {
         // create temp file that will hold byte array
         Java.IO.File tempMp3 = Java.IO.File.CreateTempFile("demo", "mp4", context.CacheDir);
         tempMp3.DeleteOnExit();
         FileOutputStream fos = new FileOutputStream(tempMp3);
         fos.Write(byteArray);
         fos.Close();
         FileInputStream fis = new FileInputStream(tempMp3);
         return(fis.FD);
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
            /// <exception cref="System.IO.IOException"/>
            internal static string CheckFullFile(Path file, FilePath localFile)
            {
                StringBuilder b = new StringBuilder("checkFullFile: ").Append(file.GetName()).Append
                                      (" vs ").Append(localFile);

                byte[] bytes = new byte[CheckLength(file, localFile)];
                b.Append(", length=").Append(bytes.Length);
                FileInputStream @in = new FileInputStream(localFile);

                for (int n = 0; n < bytes.Length;)
                {
                    n += @in.Read(bytes, n, bytes.Length - n);
                }
                @in.Close();
                AppendTestUtil.CheckFullFile(dfs, file, bytes.Length, bytes, "File content mismatch: "
                                             + b, false);
                return(b.ToString());
            }
示例#14
0
            public virtual Object Run()
            {
                FileInputStream fis = null;

                try
                {
                    fis = new FileInputStream(SystemCustomCursorPropertiesFile);
                    SystemCustomCursorProperties.Load(fis);
                }
                finally
                {
                    if (fis != null)
                    {
                        fis.Close();
                    }
                }
                return(null);
            }
 public TraditionalSimplifiedCharacterMap(string path)
 {
     // TODO: gzipped maps might be faster
     try
     {
         FileInputStream   fis = new FileInputStream(path);
         InputStreamReader isr = new InputStreamReader(fis, "utf-8");
         BufferedReader    br  = new BufferedReader(isr);
         Init(br);
         br.Close();
         isr.Close();
         fis.Close();
     }
     catch (IOException e)
     {
         throw new RuntimeIOException(e);
     }
 }
示例#16
0
文件: FaultSkin.cs 项目: Veggie13/ipf
        public static FaultSkin readFromFileSlow(String fileName)
        {
            throw new NotImplementedException();
#if false
            try
            {
                FileInputStream   fis  = new FileInputStream(fileName);
                ObjectInputStream ois  = new ObjectInputStream(fis);
                FaultSkin         skin = (FaultSkin)ois.readObject();
                ois.close();
                return(skin);
            }
            catch (Exception e)
            {
                throw new RuntimeException(e);
            }
#endif
        }
示例#17
0
        public override void OnWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback)
        {
            InputStream  input  = null;
            OutputStream output = null;

            try
            {
                File file = new File(_filePath);
                input  = new FileInputStream(file);
                output = new FileOutputStream(destination.FileDescriptor);

                byte[] buffer = new byte[8 * 1024];
                int    length;
                while ((length = input.Read(buffer)) >= 0 && !cancellationSignal.IsCanceled)
                {
                    output.Write(buffer, 0, length);
                }

                if (cancellationSignal.IsCanceled)
                {
                    callback.OnWriteCancelled();
                }
                else
                {
                    callback.OnWriteFinished(new PageRange[] { PageRange.AllPages });
                }
            }
            catch (Exception e)
            {
                callback.OnWriteFailed(e.Message);
            }
            finally
            {
                try
                {
                    input.Close();
                    output.Close();
                }
                catch (IOException e)
                {
                    Log.Error("WalkOut", e.Message);
                }
            }
        }
示例#18
0
        private void StopRecording()
        {
            timer.Stop();
            timer.Visibility = ViewStates.Invisible;
            //--------------------------------------------------
            isVideoStarted = false;
            recorder.Stop();
            recorder.Release();
            camera.Lock();
            camera.StopPreview();
            camera.Release();


            FileInputStream inputStream = null;

            inputStream = new FileInputStream(path);
            byte[] bytes;
            byte[] buffer = new byte[8192];
            int    bytesRead;


            ByteArrayOutputStream output = new ByteArrayOutputStream();

            try
            {
                while ((bytesRead = inputStream.Read(buffer)) != -1)
                {
                    output.Write(buffer, 0, bytesRead);
                }
            }
            catch (Java.Lang.Exception exception)
            {
                //  e.PrintStackTrace();
            }
            bytes = output.ToByteArray();
            string attachedFile = Base64.EncodeToString(bytes, Base64.Default);

            captureButton.RemoveFromParent();

            //on the CameraPage you can get base64 and video path
            MessagingCenter.Send <string, string>("VideoBase64Ready", "VideoIsReady", attachedFile);

            MessagingCenter.Send <string, string>("VideoPathReady", "VideoPathReady", path);
        }
示例#19
0
        public override void OnWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback)
        {
            InputStream  input  = null;
            OutputStream output = null;

            try
            {
                //Create FileInputStream object from the given file
                input = new FileInputStream(FileToPrint);
                //Create FileOutputStream object from the destination FileDescriptor instance
                output = new FileOutputStream(destination.FileDescriptor);

                byte[] buf = new byte[1024];
                int    bytesRead;

                while ((bytesRead = input.Read(buf)) > 0)
                {
                    //Write the contents of the given file to the print destination
                    output.Write(buf, 0, bytesRead);
                }

                callback.OnWriteFinished(new PageRange[] { PageRange.AllPages });
            }
            catch (FileNotFoundException ee)
            {
                //Catch exception
            }
            catch (Exception e)
            {
                //Catch exception
            }
            finally
            {
                try
                {
                    input.Close();
                    output.Close();
                }
                catch (IOException e)
                {
                    e.PrintStackTrace();
                }
            }
        }
示例#20
0
        private static void AddEntries(ZipFile file, string[] newFiles)
        {
            string          fileName     = file.getName();
            string          tempFileName = Path.GetTempFileName();
            ZipOutputStream destination  = new ZipOutputStream(new FileOutputStream(tempFileName));

            try
            {
                CopyEntries(file, destination);
                if (newFiles != null)
                {
                    foreach (string f in newFiles)
                    {
                        ZipEntry z = new ZipEntry(f.Remove(0, Path.GetPathRoot(f).Length));
                        z.setMethod(ZipEntry.DEFLATED);
                        destination.putNextEntry(z);
                        try
                        {
                            FileInputStream s = new FileInputStream(f);
                            try
                            {
                                CopyStream(s, destination);
                            }
                            finally
                            {
                                s.close();
                            }
                        }
                        finally
                        {
                            destination.closeEntry();
                        }
                    }
                }
            }
            finally
            {
                destination.close();
            }
            file.close();

            System.IO.File.Copy(tempFileName, fileName, true);
            System.IO.File.Delete(tempFileName);
        }
示例#21
0
        private void InstallSilently(Context context, Android.Net.Uri apkUri)
        {
            try
            {
                Log.Debug("TESTPUSHLINK", "Init Silent Install. apkUri is " + apkUri.Path + " apkUri host is " + apkUri.Host);
                var inputStream      = new FileInputStream(new File(context.FilesDir, apkUri.Path));
                var packageInstaller = context.PackageManager.PackageInstaller;
                var installParams    = new PackageInstaller.SessionParams(PackageInstallMode.FullInstall);
                installParams.SetAppPackageName(context.PackageName);
                var sessionId = packageInstaller.CreateSession(installParams);
                var session   = packageInstaller.OpenSession(sessionId);
                var outStream = session.OpenWrite("COSU", 0, -1);
                var buffer    = new byte[65536];
                int c;

                // HERE THIS LOOP HANGS FOREVER
                while ((c = inputStream.Read(buffer)) != -1)
                {
                    outStream.Write(buffer, 0, c);
                    // Log.Debug("PUSHLINK", "writing..");
                }

                // NEVER COMES OUT
                Log.Debug("TESTPUSHLINK", "Silent Install DONE!! ");

                session.Fsync(outStream);
                inputStream.Close();
                outStream.Close();

                var pendingIntent =
                    PendingIntent.GetBroadcast(context, sessionId, new Intent("dummy.intent.not.used"), 0);
                session.Commit(pendingIntent.IntentSender);
            }
            catch (IOException e)
            {
                Log.Error("TESTPUSHLINK", "Silent Install failed to silent -r install. EX: " + e.GetStackTrace());

                throw new RuntimeException(e);
            }
            catch (Exception e)
            {
                Log.Error("TESTPUSHLINK", "Silent Install failed to silent -r install. EX: " + e.StackTrace);
            }
        }
示例#22
0
        public virtual void TestStandardFormat_LargeObject_CorruptZLibStream()
        {
            int type = Constants.OBJ_BLOB;

            byte[]   data = GetRng().NextBytes(streamThreshold + 5);
            ObjectId id   = new ObjectInserter.Formatter().IdFor(type, data);

            byte[] gz = CompressStandardFormat(type, data);
            gz[gz.Length - 1] = 0;
            gz[gz.Length - 2] = 0;
            Write(id, gz);
            ObjectLoader ol;

            {
                FileInputStream fs = new FileInputStream(Path(id));
                try
                {
                    ol = UnpackedObject.Open(fs, Path(id), id, wc);
                }
                finally
                {
                    fs.Close();
                }
            }
            try
            {
                byte[]      tmp = new byte[data.Length];
                InputStream @in = ol.OpenStream();
                try
                {
                    IOUtil.ReadFully(@in, tmp, 0, tmp.Length);
                }
                finally
                {
                    @in.Close();
                }
                NUnit.Framework.Assert.Fail("Did not throw CorruptObjectException");
            }
            catch (CorruptObjectException coe)
            {
                NUnit.Framework.Assert.AreEqual(MessageFormat.Format(JGitText.Get().objectIsCorrupt
                                                                     , id.Name, JGitText.Get().corruptObjectBadStream), coe.Message);
            }
        }
            /// <exception cref="System.IO.IOException"></exception>
            internal Entry(GitIndex _enclosing, byte[] key, FilePath f, int stage, byte[] newContent
                           )
            {
                this._enclosing = _enclosing;
                this.ctime      = f.LastModified() * 1000000L;
                this.mtime      = this.ctime;
                // we use same here
                this.dev = -1;
                this.ino = -1;
                if (this._enclosing.Config_filemode() && this._enclosing.File_canExecute(f))
                {
                    this.mode = FileMode.EXECUTABLE_FILE.GetBits();
                }
                else
                {
                    this.mode = FileMode.REGULAR_FILE.GetBits();
                }
                this.uid  = -1;
                this.gid  = -1;
                this.size = newContent.Length;
                ObjectInserter inserter = this._enclosing.db.NewObjectInserter();

                try
                {
                    InputStream @in = new FileInputStream(f);
                    try
                    {
                        this.sha1 = inserter.Insert(Constants.OBJ_BLOB, newContent);
                    }
                    finally
                    {
                        @in.Close();
                    }
                    inserter.Flush();
                }
                finally
                {
                    inserter.Release();
                }
                this.name  = key;
                this.flags = (short)((stage << 12) | this.name.Length);
                // TODO: fix flags
                this.stages = (1 >> this.GetStage());
            }
        /// <exception cref="System.IO.IOException"/>
        public static string Slurp(FilePath f)
        {
            int len = (int)f.Length();

            byte[]          buf      = new byte[len];
            FileInputStream @in      = new FileInputStream(f);
            string          contents = null;

            try
            {
                @in.Read(buf, 0, len);
                contents = Sharpen.Runtime.GetStringForBytes(buf, "UTF-8");
            }
            finally
            {
                @in.Close();
            }
            return(contents);
        }
示例#25
0
        /// <summary>Compute the hash of the specified file</summary>
        /// <param name="args">name of file to compute hash of.</param>
        /// <exception cref="System.IO.IOException"/>
        public static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                System.Console.Error.WriteLine("Usage: JenkinsHash filename");
                System.Environment.Exit(-1);
            }
            FileInputStream @in = new FileInputStream(args[0]);

            byte[]      bytes = new byte[512];
            int         value = 0;
            JenkinsHash hash  = new JenkinsHash();

            for (int length = @in.Read(bytes); length > 0; length = @in.Read(bytes))
            {
                value = hash.Hash(bytes, length, value);
            }
            System.Console.Out.WriteLine(Math.Abs(value));
        }
示例#26
0
        /// <exception cref="System.IO.FileNotFoundException"/>
        /// <exception cref="System.IO.IOException"/>
        private static void WriteFileToPutRequest(Configuration conf, HttpURLConnection connection
                                                  , FilePath imageFile, Canceler canceler)
        {
            connection.SetRequestProperty(ContentType, "application/octet-stream");
            connection.SetRequestProperty(ContentTransferEncoding, "binary");
            OutputStream    output = connection.GetOutputStream();
            FileInputStream input  = new FileInputStream(imageFile);

            try
            {
                CopyFileToStream(output, imageFile, input, ImageServlet.GetThrottler(conf), canceler
                                 );
            }
            finally
            {
                IOUtils.CloseStream(input);
                IOUtils.CloseStream(output);
            }
        }
示例#27
0
 public override void Configure(JobConf jconf)
 {
     conf = jconf;
     try
     {
         // read the cached files (unzipped, unjarred and text)
         // and put it into a single file TEST_ROOT_DIR/test.txt
         string     TestRootDir = jconf.Get("test.build.data", "/tmp");
         Path       file        = new Path("file:///", TestRootDir);
         FileSystem fs          = FileSystem.GetLocal(conf);
         if (!fs.Mkdirs(file))
         {
             throw new IOException("Mkdirs failed to create " + file.ToString());
         }
         Path fileOut = new Path(file, "test.txt");
         fs.Delete(fileOut, true);
         DataOutputStream @out     = fs.Create(fileOut);
         string[]         symlinks = new string[6];
         symlinks[0] = ".";
         symlinks[1] = "testjar";
         symlinks[2] = "testzip";
         symlinks[3] = "testtgz";
         symlinks[4] = "testtargz";
         symlinks[5] = "testtar";
         for (int i = 0; i < symlinks.Length; i++)
         {
             // read out the files from these archives
             FilePath        f      = new FilePath(symlinks[i]);
             FilePath        txt    = new FilePath(f, "test.txt");
             FileInputStream fin    = new FileInputStream(txt);
             BufferedReader  reader = new BufferedReader(new InputStreamReader(fin));
             string          str    = reader.ReadLine();
             reader.Close();
             @out.WriteBytes(str);
             @out.WriteBytes("\n");
         }
         @out.Close();
     }
     catch (IOException ie)
     {
         System.Console.Out.WriteLine(StringUtils.StringifyException(ie));
     }
 }
示例#28
0
        private static byte[] readFileToByteArray(Java.IO.File file)
        {
            FileInputStream fis = null;

            // Creating a byte array using the length of the file
            // file.length returns long which is cast to int
            byte[] bArray = new byte[(int)file.Length()];
            try
            {
                fis = new FileInputStream(file);
                fis.Read(bArray);
                fis.Close();
            }
            catch (Java.IO.IOException ioExp)
            {
                ioExp.PrintStackTrace();
            }
            return(bArray);
        }
示例#29
0
            /// <exception cref="System.IO.IOException"/>
            protected internal override void ProcessArguments(List <PathData> args)
            {
                if (!dst.exists)
                {
                    dst.fs.Create(dst.path, false).Close();
                }
                InputStream        @is = null;
                FSDataOutputStream fos = dst.fs.Append(dst.path);

                try
                {
                    if (readStdin)
                    {
                        if (args.Count == 0)
                        {
                            IOUtils.CopyBytes(Runtime.@in, fos, DefaultIoLength);
                        }
                        else
                        {
                            throw new IOException("stdin (-) must be the sole input argument when present");
                        }
                    }
                    // Read in each input file and write to the target.
                    foreach (PathData source in args)
                    {
                        @is = new FileInputStream(source.ToFile());
                        IOUtils.CopyBytes(@is, fos, DefaultIoLength);
                        IOUtils.CloseStream(@is);
                        @is = null;
                    }
                }
                finally
                {
                    if (@is != null)
                    {
                        IOUtils.CloseStream(@is);
                    }
                    if (fos != null)
                    {
                        IOUtils.CloseStream(fos);
                    }
                }
            }
示例#30
0
        private void addEntry(ZipOutputStream zipStream, String root, File file)
        {
            if (file.isHidden())
            {
                return;
            }
            var name     = root + file.getName();
            var zipEntry = new ZipEntry(name);

            zipStream.putNextEntry(zipEntry);
            var buffer      = new byte[4096];
            var inputStream = new FileInputStream(file);
            int read;

            while ((read = inputStream.read(buffer)) != -1)
            {
                zipStream.write(buffer, 0, read);
            }
        }
示例#31
0
 private T DeSerialize <T>(T item)
 {
     try
     {
         XmlSerializer   deserialize = new XmlSerializer(typeof(T));
         File            file        = new File(baseModel.Path);
         byte[]          output      = new byte[file.Length()];
         FileInputStream reader      = new FileInputStream(file);
         reader.Read(output);
         System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(output);
         System.IO.TextReader   stream       = new System.IO.StreamReader(memoryStream);
         item = (T)deserialize.Deserialize(stream);
         stream.Close();
         memoryStream.Close();
     }
     catch (Exception)
     { }
     return(item);
 }
示例#32
0
        public virtual void Test2()
        {
            FilePath packFile = JGitTestUtil.GetTestResourceFile("pack-df2982f284bbabb6bdb59ee3fcc6eb0983e20371.pack"
                                                                 );
            InputStream @is = new FileInputStream(packFile);

            try
            {
                IndexPack pack = new IndexPack(db, @is, new FilePath(trash, "tmp_pack2"));
                pack.Index(new TextProgressMonitor());
                PackFile file = new PackFile(new FilePath(trash, "tmp_pack2.idx"), new FilePath(trash
                                                                                                , "tmp_pack2.pack"));
                NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("02ba32d3649e510002c21651936b7077aa75ffa9"
                                                                                 )));
                NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("0966a434eb1a025db6b71485ab63a3bfbea520b6"
                                                                                 )));
                NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("09efc7e59a839528ac7bda9fa020dc9101278680"
                                                                                 )));
                NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("0a3d7772488b6b106fb62813c4d6d627918d9181"
                                                                                 )));
                NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("1004d0d7ac26fbf63050a234c9b88a46075719d3"
                                                                                 )));
                NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("10da5895682013006950e7da534b705252b03be6"
                                                                                 )));
                NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("1203b03dc816ccbb67773f28b3c19318654b0bc8"
                                                                                 )));
                NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("15fae9e651043de0fd1deef588aa3fbf5a7a41c6"
                                                                                 )));
                NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("16f9ec009e5568c435f473ba3a1df732d49ce8c3"
                                                                                 )));
                NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("1fd7d579fb6ae3fe942dc09c2c783443d04cf21e"
                                                                                 )));
                NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("20a8ade77639491ea0bd667bf95de8abf3a434c8"
                                                                                 )));
                NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("2675188fd86978d5bc4d7211698b2118ae3bf658"
                                                                                 )));
            }
            finally
            {
                // and lots more...
                @is.Close();
            }
        }
示例#33
0
        public static PsdHeaderDirectory ProcessBytes([NotNull] string file)
        {
            Com.Drew.Metadata.Metadata metadata = new Com.Drew.Metadata.Metadata();
            InputStream stream = new FileInputStream(new FilePath(file));

            try
            {
                new PsdReader().Extract(new Com.Drew.Lang.StreamReader(stream), metadata);
            }
            catch (Exception e)
            {
                stream.Close();
                throw;
            }
            PsdHeaderDirectory directory = metadata.GetFirstDirectoryOfType <PsdHeaderDirectory>();

            NUnit.Framework.Assert.IsNotNull(directory);
            return(directory);
        }
示例#34
0
        public SerialPort(File device, int baudrate, int flags) : base()
        {
            /* Check access permission */
            if (!device.CanRead() || !device.CanWrite())
            {
                try
                {
                    /* Missing read/write permission, trying to chmod the file */
                    Java.Lang.Process su;
                    su = Runtime.GetRuntime().Exec("/system/bin/su");
                    string cmd = "chmod 666 " + device.AbsolutePath + "\n"
                                 + "exit\n";
                    byte[] cmdbytes = System.Text.Encoding.ASCII.GetBytes(cmd);
                    su.OutputStream.Write(cmdbytes, 0, cmdbytes.Length);
                    if ((su.WaitFor() != 0) || !device.CanRead() ||
                        !device.CanWrite())
                    {
                        throw new SecurityException();
                    }
                }
                catch (Java.Lang.Exception e)
                {
                    e.PrintStackTrace();
                    throw new SecurityException();
                }
            }
            IntPtr IntPtrClass = JNIEnv.FindClass(this.GetType());

#if MyAlter
            mFd = GetFileDescriptor(device.AbsolutePath, baudrate, flags, out serialPortHandle);
#else
            mFd = open(Java.Interop.JniEnvironment.EnvironmentPointer, IntPtrClass, device.AbsolutePath, baudrate, flags);
#endif
            if (mFd == null)
            {
                Log.Error(TAG, "native open returns null");
                throw new IOException();
            }
            mFileInputStream  = new FileInputStream(mFd);
            mFileOutputStream = new FileOutputStream(mFd);
            flag = true;
        }
示例#35
0
 /// <summary>Updates the index after a content merge has happened.</summary>
 /// <remarks>
 /// Updates the index after a content merge has happened. If no conflict has
 /// occurred this includes persisting the merged content to the object
 /// database. In case of conflicts this method takes care to write the
 /// correct stages to the index.
 /// </remarks>
 /// <param name="base"></param>
 /// <param name="ours"></param>
 /// <param name="theirs"></param>
 /// <param name="result"></param>
 /// <param name="of"></param>
 /// <exception cref="System.IO.FileNotFoundException">System.IO.FileNotFoundException
 ///     </exception>
 /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
 private void UpdateIndex(CanonicalTreeParser @base, CanonicalTreeParser ours, CanonicalTreeParser
                          theirs, MergeResult <RawText> result, FilePath of)
 {
     if (result.ContainsConflicts())
     {
         // a conflict occurred, the file will contain conflict markers
         // the index will be populated with the three stages and only the
         // workdir (if used) contains the halfways merged content
         Add(tw.RawPath, @base, DirCacheEntry.STAGE_1, 0, 0);
         Add(tw.RawPath, ours, DirCacheEntry.STAGE_2, 0, 0);
         Add(tw.RawPath, theirs, DirCacheEntry.STAGE_3, 0, 0);
         mergeResults.Put(tw.PathString, result.Upcast());
     }
     else
     {
         // no conflict occurred, the file will contain fully merged content.
         // the index will be populated with the new merged version
         DirCacheEntry dce     = new DirCacheEntry(tw.PathString);
         int           newMode = MergeFileModes(tw.GetRawMode(0), tw.GetRawMode(1), tw.GetRawMode(2)
                                                );
         // set the mode for the new content. Fall back to REGULAR_FILE if
         // you can't merge modes of OURS and THEIRS
         dce.FileMode = (newMode == FileMode.MISSING.GetBits()) ? FileMode.REGULAR_FILE :
                        FileMode.FromBits(newMode);
         dce.LastModified = of.LastModified();
         dce.SetLength((int)of.Length());
         InputStream @is = new FileInputStream(of);
         try
         {
             dce.SetObjectId(GetObjectInserter().Insert(Constants.OBJ_BLOB, of.Length(), @is));
         }
         finally
         {
             @is.Close();
             if (inCore)
             {
                 FileUtils.Delete(of);
             }
         }
         builder.Add(dce);
     }
 }
            /// <exception cref="System.IO.IOException"/>
            internal void Load(FilePath file)
            {
                long start = Time.MonotonicNow();

                imgDigest = MD5FileUtils.ComputeMd5ForFile(file);
                RandomAccessFile raFile = new RandomAccessFile(file, "r");
                FileInputStream  fin    = new FileInputStream(file);

                try
                {
                    LoadInternal(raFile, fin);
                    long end = Time.MonotonicNow();
                    Log.Info("Loaded FSImage in " + (end - start) / 1000 + " seconds.");
                }
                finally
                {
                    fin.Close();
                    raFile.Close();
                }
            }
        public void PlayAudio(byte[] audioRecording, string fileExtension)
        {
            var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var file = new File(documents);
            var tempAudioFile = File.CreateTempFile(Guid.NewGuid().ToString(), fileExtension, file);
            tempAudioFile.DeleteOnExit();

            var stream = new FileOutputStream(tempAudioFile);
            stream.Write(audioRecording);
            stream.Close();

            // Tried passing path directly, but kept getting 
            // "Prepare failed.: status=0x1"
            // so using file descriptor instead
            var fileStream = new FileInputStream(tempAudioFile);
            _mediaPlayer.Reset();
            _mediaPlayer.SetDataSource(fileStream.FD);
            _mediaPlayer.Prepare();
            _mediaPlayer.Start();
        }
示例#38
0
        //Compares both audio files
        private static float compareAudio(string filename1, string filename2)
        {
            //string resStr = "";
            float result = 0;
            //float score = 0;

            InputStream isOne = new FileInputStream(filename1);
            InputStream isTwo = new FileInputStream(filename2);

            Wave wavFile1 = new Wave(isOne);
            Wave wavFile2 = new Wave(isTwo);

            FingerprintSimilarity sim;

            sim = wavFile1.getFingerprintSimilarity(wavFile2);
            //Note: for this part, I had intentionally made it like this for now, so that I could test the functions
            //I'm already working on a better version for cancelling noise.
            result = (sim.getSimilarity() * 100) + 0;
            return(result);
        }
示例#39
0
        /// <exception cref="System.IO.IOException"></exception>
        public override void WriteTo(OutputStream outstream)
        {
            Args.NotNull(outstream, "Output stream");
            InputStream instream = new FileInputStream(this.file);

            try
            {
                byte[] tmp = new byte[OutputBufferSize];
                int    l;
                while ((l = instream.Read(tmp)) != -1)
                {
                    outstream.Write(tmp, 0, l);
                }
                outstream.Flush();
            }
            finally
            {
                instream.Close();
            }
        }
示例#40
0
文件: File.cs 项目: nguyenkien/api
 /// <summary>
 /// Read a file with given path and return a byte-array with it's entire contents.
 /// </summary>
 public static byte[] ReadAllBytes(string path)
 {
     if (path == null)
         throw new ArgumentNullException("path");
     var file = new JFile(path);
     if (!file.Exists() || !file.IsFile())
         throw new FileNotFoundException(path);
     if (!file.CanRead())
         throw new UnauthorizedAccessException(path);
     var stream = new FileInputStream(file);
     try
     {
         var array = new byte[file.Length()];
         stream.Read(array, 0, array.Length);
         return array;
     }
     finally
     {
         stream.Close();
     }
 }
示例#41
0
 /**
  * Load the JMeter properties file; if not found, then
  * default to "org/apache/jmeter/jmeter.properties" from the classpath
  *
  * c.f. loadProperties
  *
  */
 public static void loadJMeterProperties(String file)
 {
     Properties p = new Properties(System.getProperties());
     InputStream ins = null;
     try
     {
         File f = new File(file);
         ins = new FileInputStream(f);
         p.load(ins);
     }
     catch (IOException e)
     {
         try
         {
             ins = ClassLoader.getSystemResourceAsStream("org/apache/jmeter/jmeter.properties"); // $NON-NLS-1$
             if (ins == null)
             {
                 //throw new RuntimeException("Could not read JMeter properties file");
             }
             p.load(ins);
         }
         catch (IOException ex)
         {
             // JMeter.fail("Could not read internal resource. " +
             // "Archive is broken.");
         }
     }
     finally
     {
         JOrphanUtils.closeQuietly(ins);
     }
     appProperties = p;
 }
示例#42
0
文件: AstCache.cs 项目: uxmal/pytocs
        // package-private for testing
        Module deserialize(string sourcePath)
        {
#if NEVER
        string cachePath = getCachePath(sourcePath);
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream(cachePath);
            ois = new ObjectInputStream(fis);
            return (Module) ois.readObject();
        } catch (Exception e) {
            return null;
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                } else if (fis != null) {
                    fis.close();
                }
            } catch (Exception e) {

            }
        }
    }
示例#43
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            // Create your application here
            SetContentView(Resource.Layout.History);
            listView = FindViewById<ListView>(Resource.Id.listView1);
            db = new MoodDatabase(this);

            Button BackHome = FindViewById<Button> (Resource.Id.button1);
            BackHome.Click += delegate {
                //create an intent to go to the next screen
                Intent intent = new Intent(this, typeof(Home));
                intent.SetFlags(ActivityFlags.ClearTop); //remove the history and go back to home screen
                StartActivity(intent);
            };

            Button DeleteButton = FindViewById<Button> (Resource.Id.button2);
            DeleteButton.Click += delegate {
                //create an intent to go to the next screen
                db.WritableDatabase.ExecSQL("DROP TABLE IF EXISTS MoodData");
                db.WritableDatabase.ExecSQL(MoodDatabase.create_table_sql);
                //restart this activity in order to update the view
                Intent intent = new Intent(this, typeof(History));
                intent.SetFlags(ActivityFlags.ClearTop); //remove the history and go back to home screen
                StartActivity(intent);
            };

            //query database and link to the listview
            cursor = db.ReadableDatabase.RawQuery("SELECT * FROM MoodData ORDER BY _id DESC", null); // cursor query
            //why this command is deprecated and what should be used instead: http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanager-background.html
            //http://www.vogella.com/tutorials/AndroidSQLite/article.html
            //http://www.codeproject.com/Articles/792883/Using-Sqlite-in-a-Xamarin-Android-Application-Deve
            StartManagingCursor(cursor);

            // which columns map to which layout controls
            //string[] fromColumns = new string[] {"date", "time", "mood", "people", "what", "location"};
            string[] fromColumns = new string[] {"date", "mood"};
            int[] toControlIDs = new int[] {Android.Resource.Id.Text1, Android.Resource.Id.Text2};

            // use a SimpleCursorAdapter, could use our own Layout for the view: https://thinkandroid.wordpress.com/2010/01/09/simplecursoradapters-and-listviews/
            listView.Adapter = new SimpleCursorAdapter (this, Android.Resource.Layout.SimpleListItem2, cursor, fromColumns, toControlIDs);
            listView.ItemClick += OnListItemClick;

            //EXPORT BUTTON TO WRITE SQLITE DB FILE TO SD CARD
            Button ExportButton = FindViewById<Button> (Resource.Id.button3);
            ExportButton.Click += delegate {
                File sd = GetExternalFilesDir(null);
                File backupDB = new File(sd, "MoodData.db"); //this is where we're going to export to
                //this is the database file
                File data = GetDatabasePath("MoodData.db");
                //Android.Widget.Toast.MakeText(this, data.AbsolutePath, Android.Widget.ToastLength.Short).Show();

                OutputStream OS = new FileOutputStream(backupDB);
                InputStream IS = new FileInputStream(data);
                //the actual copying action
                byte[] dataByte = new byte[IS.Available()];
                IS.Read(dataByte);
                OS.Write(dataByte);
                IS.Close();
                OS.Close();

                //http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir%28java.lang.String%29
                //http://www.techrepublic.com/blog/software-engineer/export-sqlite-data-from-your-android-device/
            };
        }
示例#44
0
		public async void Decompress( )
		{
			var openFileDialog = new OpenFileDialog
			{
				Filter = $"Quantized huffman-encoded file|*.{Properties.Resources.HuffmanCodeExt}|" +
						 $"Quantized LZ77-encoded file|*.{Properties.Resources.Lz77Ext}|" +
						 $"Quantized arithmetic-encoded file|*.{Properties.Resources.ArithmeticCodeExt}",
				ValidateNames = true
			};

			if ( openFileDialog.ShowDialog( ) != true )
				return;

			try
			{
				using ( var input = new FileInputStream( openFileDialog.FileName ) )
				{
					var dialog = new SaveFileDialog
					{
						DefaultExt = "csv",
						Filter = "Text file|*.csv",
						AddExtension = true
					};

					if ( dialog.ShowDialog( ) != true )
						return;

					var path = dialog.FileName;

					var ext = Path.GetExtension( openFileDialog.FileName );

					ICompressor compressor;

					if ( ext == Properties.Resources.ArithmeticCodeExt )
					{ compressor = new ArithmeticCodingCompressor( ); }
					else if ( ext == Properties.Resources.Lz77Ext )
					{ compressor = new LZ77HuffmanCompressor( DefaultWidth ); }
					else
					{ compressor = new HuffmanCompressor( ); }

					var grid = await Task<IGrid>.Factory.StartNew( ( ) => compressor.Decompress( input ) );
					var writer = new CsvGridWriter( ';' );

					await Task.Factory.StartNew( ( ) => writer.Write( path, grid ) );

					MessageBox.Show( "Done.", "Info", MessageBoxButton.OK, MessageBoxImage.Information );
				}
			}
			catch ( Exception e )
			{
				MessageBox.Show( e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error );
			}
		}
        /**
         * Helps identify the source file
         */
        private static String GetFileMD5(File f)
        {
            MessageDigest m;
            try
            {
                m = MessageDigest.GetInstance("MD5");
            }
            catch (NoSuchAlgorithmException e)
            {
                throw new RuntimeException(e);
            }

            byte[] buf = new byte[2048];
            try
            {
                InputStream is1 = new FileInputStream(f);
                while (true)
                {
                    int bytesRead = is1.Read(buf);
                    if (bytesRead < 1)
                    {
                        break;
                    }
                    m.update(buf, 0, bytesRead);
                }
                is1.Close();
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }

            return "0x" + new Bigint(1, m.digest()).ToString(16);
        }
示例#46
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static void copyFile(java.io.File src, java.io.File dst) throws java.io.IOException
	  private static void copyFile(File src, File dst)
	  {
		InputStream @in = new FileInputStream(src);
		OutputStream @out = new FileOutputStream(dst);
		int len;
		while ((len = @in.read(copyBuffer)) > 0)
		{
		  @out.write(copyBuffer, 0, len);
		}
		@in.close();
		@out.close();
	  }
示例#47
0
 public static Properties loadProperties() 
 {
     Properties nameMap = new Properties();
     FileInputStream fis = null;
     try 
     {
         fis = new FileInputStream(JMeterUtils.getJMeterHome()
                      + JMeterUtils.getPropDefault(SAVESERVICE_PROPERTIES, SAVESERVICE_PROPERTIES_FILE));
         nameMap.load(fis);
     } 
     finally
     {
         JOrphanUtils.closeQuietly(fis);
     }
     return nameMap;
 }
示例#48
0
		public void put(String src, String dst,
			SftpProgressMonitor monitor, int mode)
		{
			//throws SftpException{
			src=localAbsolutePath(src);
			dst=remoteAbsolutePath(dst);

			//System.err.println("src: "+src+", "+dst);
			try
			{
				Vector v=glob_remote(dst);
				int vsize=v.size();
				if(vsize!=1)
				{
					if(vsize==0)
					{
						if(isPattern(dst))
							throw new SftpException(SSH_FX_FAILURE, dst);
						else
							dst=Util.unquote(dst);
					}
					throw new SftpException(SSH_FX_FAILURE, v.toString());
				}
				else
				{
					dst=(String)(v.elementAt(0));
				}

				//System.err.println("dst: "+dst);

				bool _isRemoteDir=isRemoteDir(dst);

				v=glob_local(src);
				//System.err.println("glob_local: "+v+" dst="+dst);
				vsize=v.size();

				StringBuffer dstsb=null;
				if(_isRemoteDir)
				{
					if(!dst.endsWith("/"))
					{
						dst+="/";
					}
					dstsb=new StringBuffer(dst);
				}
				else if(vsize>1)
				{
					throw new SftpException(SSH_FX_FAILURE, "Copying multiple files, but destination is missing or a file.");
				}

				for(int j=0; j<vsize; j++)
				{
					String _src=(String)(v.elementAt(j));
					String _dst=null;
					if(_isRemoteDir)
					{
						int i=_src.lastIndexOf(file_separatorc);
						if(i==-1) dstsb.append(_src);
						else dstsb.append(_src.substring(i + 1));
						_dst=dstsb.toString();
						dstsb.delete(dst.length(), _dst.length());
					}
					else
					{
						_dst=dst;
					}
					//System.err.println("_dst "+_dst);

					long size_of_dst=0;
					if(mode==RESUME)
					{
						try
						{
							SftpATTRS attr=_stat(_dst);
							size_of_dst=attr.getSize();
						}
						catch(Exception eee)
						{
							//System.err.println(eee);
						}
						long size_of_src=new File(_src).length();
						if(size_of_src<size_of_dst)
						{
							throw new SftpException(SSH_FX_FAILURE, "failed to resume for "+_dst);
						}
						if(size_of_src==size_of_dst)
						{
							return;
						}
					}

					if(monitor!=null)
					{
						monitor.init(SftpProgressMonitor.PUT, _src, _dst,
						             (new File(_src)).length());
						if(mode==RESUME)
						{
							monitor.count(size_of_dst);
						}
					}
					FileInputStream fis=null;
					try
					{
						fis=new FileInputStream(_src);
						_put(fis, _dst, monitor, mode);
					}
					finally
					{
						if(fis!=null) 
						{
							//	    try{
							fis.close();
							//	    }catch(Exception ee){};
						}
					}
				}
			}
			catch(Exception e)
			{
				if(e is SftpException) throw (SftpException)e;
				throw new SftpException(SSH_FX_FAILURE, e.toString());
			}
		}
        public Task<string> GetSoundFromGalleryAsync()
        {
            return AsyncHelper.CreateAsyncFromCallback<string>(resultCallback =>
            {
                Intent intent = new Intent();
                intent.SetType("audio/*");
                intent.SetAction(Intent.ActionGetContent);
                var trad = DependencyService.Container.Resolve<ILocalizationService>();
                ActivityService.StartActivityForResult(Intent.CreateChooser(intent, trad.GetString("SoundChoice_PickerTitle", "Text")), (result, data) =>
                {
                    string path = null;
                    if (result == Result.Ok)
                    {
                        Uri selectedSound = data.Data;
                        ParcelFileDescriptor parcelFileDescriptor = ActivityService.CurrentActivity.ContentResolver.OpenFileDescriptor(selectedSound, "r");
                        FileDescriptor fileDescriptor = parcelFileDescriptor.FileDescriptor;
                        FileInputStream inputStream = new FileInputStream(fileDescriptor);
                        path = StorageService.GenerateFilename(StorageType.Sound, "3gpp");
                        File outputFile = new File(path);
	                    InputStream inStream = inputStream;
                        OutputStream outStream = new FileOutputStream(outputFile);

                        byte[] buffer = new byte[1024];

                        int length;
                        //copy the file content in bytes 
                        while ((length = inStream.Read(buffer)) > 0)
                        {
                            outStream.Write(buffer, 0, length);
                        }
                        inStream.Close();
                        outStream.Close();
                    }
                    resultCallback(path);
                });
            });
        }
示例#50
0
 private void SendStoredMessages()
 {
     if (HasInternetConnection)
       {
     try
     {
       using (File dir = Context.GetDir("RaygunIO", FileCreationMode.Private))
       {
     File[] files = dir.ListFiles();
     foreach (File file in files)
     {
       if (file.Name.StartsWith("RaygunErrorMessage"))
       {
         using (FileInputStream stream = new FileInputStream(file))
         {
           using (InputStreamInvoker isi = new InputStreamInvoker(stream))
           {
             using (InputStreamReader streamReader = new Java.IO.InputStreamReader(isi))
             {
               using (BufferedReader bufferedReader = new BufferedReader(streamReader))
               {
                 StringBuilder stringBuilder = new StringBuilder();
                 string line;
                 while ((line = bufferedReader.ReadLine()) != null)
                 {
                   stringBuilder.Append(line);
                 }
                 bool success = SendMessage(stringBuilder.ToString());
                 // If just one message fails to send, then don't delete the message, and don't attempt sending anymore until later.
                 if (!success)
                 {
                   return;
                 }
                 System.Diagnostics.Debug.WriteLine("Sent " + file.Name);
               }
             }
           }
         }
         file.Delete();
       }
     }
     if (dir.List().Length == 0)
     {
       if (files.Length > 0)
       {
         System.Diagnostics.Debug.WriteLine("Successfully sent all pending messages");
       }
       dir.Delete();
     }
       }
     }
     catch (Exception ex)
     {
       System.Diagnostics.Debug.WriteLine(string.Format("Error sending stored messages to Raygun.io {0}", ex.Message));
     }
       }
 }
示例#51
0
 /**
  * This method loads a property file that may reside in the user space, or
  * in the classpath
  *
  * @param file
  *            the file to load
  * @param defaultProps a set of default properties
  * @return the Properties from the file; if it could not be processed, the defaultProps are returned.
  */
 public static Properties loadProperties(String file, Properties defaultProps)
 {
     Properties p = new Properties(defaultProps);
     InputStream ins = null;
     try
     {
         File f = new File(file);
         ins = new FileInputStream(f);
         p.load(ins);
     }
     catch (IOException e)
     {
         //try
         //{
         //    sealed URL resource = NetMeterUtils.class.getClassLoader().getResource(file);
         //    if (resource == null)
         //    {
         //        //log.warn("Cannot find " + file);
         //        return defaultProps;
         //    }
         //    ins = resource.openStream();
         //    if (ins == null)
         //    {
         //        log.warn("Cannot open " + file);
         //        return defaultProps;
         //    }
         //    p.load(ins);
         //}
         //catch (IOException ex)
         //{
         //    log.warn("Error reading " + file + " " + ex.toString());
         //    return defaultProps;
         //}
     }
     finally
     {
         JOrphanUtils.closeQuietly(ins);
     }
     return p;
 }
示例#52
0
文件: History.cs 项目: fsoyka/RUOK
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            // Create your application here
            SetContentView(Resource.Layout.History);
            db = new MoodDatabase(this);

            Button MoodTime = FindViewById<Button> (Resource.Id.buttonMoodTime);
            MoodTime.Click += delegate {
                //create an intent to go to the next screen
                Intent intent = new Intent(this, typeof(MoodTime));
                StartActivity(intent);
            };

            Button MoodPeople = FindViewById<Button> (Resource.Id.buttonMoodPeople);
            MoodPeople.Click += delegate {
                //create an intent to go to the next screen
                Intent intent = new Intent(this, typeof(MoodPeople));
                StartActivity(intent);
            };

            Button ExDB = FindViewById<Button> (Resource.Id.buttonExDB);
            ExDB.Click += delegate {
                //delete current DB and fill it with an example dataset
                db.WritableDatabase.ExecSQL("DROP TABLE IF EXISTS MoodData");
                db.WritableDatabase.ExecSQL(MoodDatabase.create_table_sql);
                //we want histograms that show bad mood when you are alone and good mood when you are with people
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '07:30', 3, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '09:30', 3, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '11:30', 7, 2, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '16:30', 1, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('29.09.15', '20:30', 6, 2, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '07:30', 3, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '09:30', 2, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '11:30', 7, 2, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '16:30', 1, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('30.09.15', '20:30', 6, 2, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '09:30', 2, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '11:30', 7, 2, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '13:30', 1, 0, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '16:30', 8, 2, 1, 1, 1023)");
                db.WritableDatabase.ExecSQL("INSERT INTO MoodData (date, time, mood, people, what, location, QuestionFlags) VALUES ('01.10.15', '18:30', 3, 0, 1, 1, 1023)");
                //Feedback message
                Toast toast = Toast.MakeText (this, GetString (Resource.String.Done), ToastLength.Short);
                toast.SetGravity (GravityFlags.Center, 0, 0);
                toast.Show ();
            };

            Button BackHome = FindViewById<Button> (Resource.Id.button1);
            BackHome.Click += delegate {
                //create an intent to go to the next screen
                Intent intent = new Intent(this, typeof(Home));
                intent.SetFlags(ActivityFlags.ClearTop); //remove the history and go back to home screen
                StartActivity(intent);
            };

            Button DeleteButton = FindViewById<Button> (Resource.Id.button2);
            DeleteButton.Click += delegate {
                //create an intent to go to the next screen
                db.WritableDatabase.ExecSQL("DROP TABLE IF EXISTS MoodData");
                db.WritableDatabase.ExecSQL(MoodDatabase.create_table_sql);

                //Feedback message
                Toast toast = Toast.MakeText (this, GetString (Resource.String.Done), ToastLength.Short);
                toast.SetGravity (GravityFlags.Center, 0, 0);
                toast.Show ();

                //restart this activity in order to update the view
                Intent intent = new Intent(this, typeof(History));
                intent.SetFlags(ActivityFlags.ClearTop); //remove the history
                StartActivity(intent);
            };

            //EXPORT BUTTON TO WRITE SQLITE DB FILE TO SD CARD
            Button ExportButton = FindViewById<Button> (Resource.Id.button3);
            ExportButton.Click += delegate {

                //This is for exporting the db file
                File sd = GetExternalFilesDir(null);
                File backupDB = new File(sd, "MoodData.db"); //this is where we're going to export to
                //this is the database file
                File data = GetDatabasePath("MoodData.db");
                //Android.Widget.Toast.MakeText(this, data.AbsolutePath, Android.Widget.ToastLength.Short).Show();
                OutputStream OS = new FileOutputStream(backupDB);
                InputStream IS = new FileInputStream(data);
                //the actual copying action
                byte[] dataByte = new byte[IS.Available()];
                IS.Read(dataByte);
                OS.Write(dataByte);
                IS.Close();
                OS.Close();

                //Now try to export everything as a csv file
                Android.Database.ICursor cursor;
                cursor = db.ReadableDatabase.RawQuery("SELECT * FROM MoodData ORDER BY _id DESC", null); // cursor query
                //only write a file if there are entries in the DB
                if (cursor.Count > 0) {
                    backupDB = new File(sd, "MoodData.csv"); //this is where we're going to export to
                    OS = new FileOutputStream(backupDB);
                    //write a header in the beginning
                    string header = "date; time; mood; people; what; location; pos1; pos2; pos3; pos4; pos5; neg1; neg2; neg3; neg4; neg5\n";
                    byte[] bytes = new byte[header.Length * sizeof(char)];
                    System.Buffer.BlockCopy(header.ToCharArray(), 0, bytes, 0, bytes.Length);
                    OS.Write(bytes);

                    for (int ii = 0; ii < cursor.Count; ii++) { //go through all rows
                        cursor.MoveToPosition (ii);
                        //now go through all columns
                        for (int kk = 1; kk < cursor.ColumnCount-1; kk++) { //skip the first column since it is just the ID and the last since it's the question flags
                            //[date] TEXT NOT NULL, [time] TEXT NOT NULL, [mood] INT NOT NULL, [people] INT NOT NULL, [what] INT NOT NULL, [location] INT NOT NULL, [pos1] INT, [pos2] INT , [pos3] INT, [pos4] INT, [pos5] INT, [neg1] INT, [neg2] INT , [neg3] INT, [neg4] INT, [neg5] INT, [QuestionFlags] INT NOT NULL)";
                            //the first two columns are strings, the rest is int
                            string tempStr;
                            if (kk < 3) {
                                tempStr = cursor.GetString(kk);
                            }
                            else {
                                int tempInt = cursor.GetInt(kk);
                                tempStr = tempInt.ToString();
                            }
                            if (kk == cursor.ColumnCount-2) //if last column, advance to next line
                                tempStr += "\n";
                            else
                                tempStr += "; ";
                            //convert to byte and write
                            bytes = new byte[tempStr.Length * sizeof(char)];
                            System.Buffer.BlockCopy(tempStr.ToCharArray(), 0, bytes, 0, bytes.Length);
                            OS.Write(bytes);
                        }
                    }

                    OS.Close();

                    //Encrypt File
                    var zipTemp = new ZIPHelper();
                    zipTemp.Save(sd.AbsolutePath);
                    System.Console.WriteLine("Path: " + sd.AbsolutePath );

                    //send via email
                    var email = new Intent(Intent.ActionSend);
                    email.SetType("text/plain");
                    //email.PutExtra(Android.Content.Intent.ExtraEmail, new string[]{"*****@*****.**"});
                    email.PutExtra(Android.Content.Intent.ExtraSubject, "R-U-OK Export");
                    email.PutExtra(Android.Content.Intent.ExtraText, "Beschreibung der Datenbank Einträge :\n[mood] Stimmung 0-8, -1 wenn die Erinnerung verpasst wurde\n[people] keiner-viele, 0-2 \n[what] Freizeit-Arbeit, 0-2 \n[location] Unterwegs/Daheim, 0-1 \n[pos1-5] und [neg1-5] sind die Affekt Fragen, bewertet zwischen 1-9. Einträge mit 0 sind nicht gefragt worden. Die Frage sind folgende:\nPos1: Wie fröhlich fühlen Sie sich?\nPos2: Wie optimistisch sind Sie?\nPos3: Wie zufrieden sind Sie?\nPos4: Wie entspannt sind Sie?\nPos5: 5te Frage fehlt noch\nNeg1: Wie traurig sind Sie?\nNeg2: Wie ängstlich sind Sie?\nNeg3: Wie einsam sind Sie?\nNeg4: Wie unruhig sind Sie?\nNeg5: Wie ärgerlich sind Sie?\n" );
                    //email.PutExtra(Android.Content.Intent.ExtraStream, Android.Net.Uri.Parse("file://" + backupDB.AbsolutePath));
                    email.PutExtra(Android.Content.Intent.ExtraStream, Android.Net.Uri.Parse("file://" + sd.AbsolutePath + "//MoodData.zip"));
                    //System.Console.WriteLine(backupDB.AbsolutePath);
                    StartActivity(Intent.CreateChooser(email, "Send email..."));
                }

                //Feedback message
                Toast toast = Toast.MakeText (this, GetString (Resource.String.Done), ToastLength.Short);
                toast.SetGravity (GravityFlags.Center, 0, 0);
                toast.Show ();

                //http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir%28java.lang.String%29
                //http://www.techrepublic.com/blog/software-engineer/export-sqlite-data-from-your-android-device/
            };
        }
示例#53
0
        public void put(String src, String dst, SftpProgressMonitor monitor, int mode)
        {
            src = localAbsolutePath(src);
            dst = remoteAbsolutePath(dst);

            try
            {
                ArrayList v = glob_remote(dst);
                int vsize = v.Count;
                if (vsize != 1)
                {
                    if (vsize == 0)
                    {
                        if (isPattern(dst))
                            throw new SftpException(SSH_FX_FAILURE, dst);
                        else
                            dst = Util.unquote(dst);
                    }
                    throw new SftpException(SSH_FX_FAILURE, v.ToString());
                }
                else
                {
                    dst = (String)(v[0]);
                }

                bool _isRemoteDir = isRemoteDir(dst);

                v = glob_local(src);
                vsize = v.Count;

                StringBuilder dstsb = null;
                if (_isRemoteDir)
                {
                    if (!dst.EndsWith("/"))
                    {
                        dst += "/";
                    }

                    dstsb = new StringBuilder(dst);
                }
                else if (vsize > 1)
                {
                    throw new SftpException(SSH_FX_FAILURE, "Copying multiple files, but destination is missing or a file.");
                }

                for (int j = 0; j < vsize; j++)
                {
                    String _src = (String)(v[j]);
                    String _dst = null;
                    if (_isRemoteDir)
                    {
                        int i = _src.LastIndexOf(file_separatorc);
                        if (i == -1) dstsb.Append(_src);
                        else dstsb.Append(_src.Substring(i + 1));
                        _dst = dstsb.ToString();
                        dstsb.Remove(dst.Length, _dst.Length);
                    }
                    else
                    {
                        _dst = dst;
                    }

                    long size_of_dst = 0;
                    if (mode == RESUME)
                    {
                        try
                        {
                            SftpATTRS attr = GetPathAttributes(_dst);
                            size_of_dst = attr.getSize();
                        }
                        catch (Exception) { }

                        long size_of_src = new File(_src).Length();
                        if (size_of_src < size_of_dst)
                        {
                            throw new SftpException(SSH_FX_FAILURE, "failed to resume for " + _dst);
                        }
                        if (size_of_src == size_of_dst)
                        {
                            return;
                        }
                    }

                    if (monitor != null)
                    {
                        monitor.init(SftpProgressMonitor.PUT, _src, _dst, (new File(_src)).Length());
                        if (mode == RESUME)
                        {
                            monitor.count(size_of_dst);
                        }
                    }
                    FileInputStream fis = null;
                    try
                    {
                        fis = new FileInputStream(_src);
                        _put(fis, _dst, monitor, mode);
                    }
                    finally
                    {
                        if (fis != null)
                        {
                            fis.close();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (e is SftpException) throw (SftpException)e;
                throw new SftpException(SSH_FX_FAILURE, e.Message);
            }
        }