Beispiel #1
0
        public static void writeStringToFile(string value, string filePath, bool deleteFile)
        {
            BufferedOutputStream outputStream = null;

            try
            {
                File file = new File(filePath);
                if (file.exists() && deleteFile)
                {
                    file.delete();
                }

                outputStream = new BufferedOutputStream(new FileStream(file, true));
                outputStream.write(value.GetBytes());
                outputStream.flush();
            }
            catch (Exception e)
            {
                throw new PerfTestException("Could not write report to file", e);
            }
            finally
            {
                IoUtil.closeSilently(outputStream);
            }
        }
Beispiel #2
0
        private static string getData()
        {
            StringBuffer response = null;
            URL          obj      = new URL("http://192.168.1.17/easyserver/WebService.php");

            switch (mFunction)
            {
            case "setUser":
                data = "function=" + URLEncoder.Encode(mFunction, "UTF-8")
                       + "&name=" + URLEncoder.Encode(mName, "UTF-8")
                       + "&age=" + URLEncoder.Encode(mAge, "UTF-8");
                break;

            case "getUser":
                data = "function=" + URLEncoder.Encode(mFunction, "UTF-8");
                break;
            }
            //creación del objeto de conexión
            HttpURLConnection con = (HttpURLConnection)obj.OpenConnection();

            //Agregando la cabecera
            //Enviamos la petición por post
            con.RequestMethod = "POST";
            con.DoOutput      = true;
            con.DoInput       = true;
            con.SetRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //Envio de datos
            //obtener el tamaño de los datos
            con.SetFixedLengthStreamingMode(data.Length);

            /*
             * OutputStream clase abstracta que es la superclase de todas las clases que
             * representan la salida de un flujo de bytes. Un flujo de salida acepta bytes de salida.
             * BufferOutputStream es la clase que implementa un flujo de salida con buffer
             */

            OutputStream ouT = new BufferedOutputStream(con.OutputStream);

            byte[] array = Encoding.ASCII.GetBytes(data);
            ouT.Write(array);
            ouT.Flush();
            ouT.Close();

            /*
             * Obteniendo datos
             * BufferedRead Lee texto de una corriente de caracteres de entrada,
             * Un InputStreamReader es un puente de flujos de streams de caracteres: se lee los
             * bytes y los decodifica en caracteres
             */
            BufferedReader iN = new BufferedReader(new InputStreamReader(con.InputStream));
            string         inputLine;

            response = new StringBuffer();
            while ((inputLine = iN.ReadLine()) != null)
            {
                response.Append(inputLine);
            }
            iN.Close();
            return(response.ToString());
        }
Beispiel #3
0
        /// <summary>
        /// 解压文件
        /// </summary>
        /// <param name="inputZip"></param>
        /// <param name="destinationDirectory"></param>
        public static void UnzipFile(string inputZip, string destinationDirectory)
        {
            int           buffer         = 2048;
            List <string> zipFiles       = new List <string>();
            File          sourceZipFile  = new File(inputZip);
            File          unzipDirectory = new File(destinationDirectory);

            CreateDir(unzipDirectory.AbsolutePath);

            ZipFile zipFile;

            zipFile = new ZipFile(sourceZipFile, ZipFile.OpenRead);
            IEnumeration zipFileEntries = zipFile.Entries();

            while (zipFileEntries.HasMoreElements)
            {
                ZipEntry entry        = (ZipEntry)zipFileEntries.NextElement();
                string   currentEntry = entry.Name;
                File     destFile     = new File(unzipDirectory, currentEntry);

                if (currentEntry.EndsWith(Constant.SUFFIX_ZIP))
                {
                    zipFiles.Add(destFile.AbsolutePath);
                }

                File destinationParent = destFile.ParentFile;
                CreateDir(destinationParent.AbsolutePath);

                if (!entry.IsDirectory)
                {
                    if (destFile != null && destFile.Exists())
                    {
                        continue;
                    }

                    BufferedInputStream inputStream = new BufferedInputStream(zipFile.GetInputStream(entry));
                    int currentByte;
                    // buffer for writing file
                    byte[] data = new byte[buffer];

                    var fos = new System.IO.FileStream(destFile.AbsolutePath, System.IO.FileMode.OpenOrCreate);
                    BufferedOutputStream dest = new BufferedOutputStream(fos, buffer);

                    while ((currentByte = inputStream.Read(data, 0, buffer)) != -1)
                    {
                        dest.Write(data, 0, currentByte);
                    }
                    dest.Flush();
                    dest.Close();
                    inputStream.Close();
                }
            }
            zipFile.Close();

            foreach (var zipName in zipFiles)
            {
                UnzipFile(zipName, destinationDirectory + File.SeparatorChar
                          + zipName.Substring(0, zipName.LastIndexOf(Constant.SUFFIX_ZIP)));
            }
        }
Beispiel #4
0
        private Object Post(string parameters)
        {
            try
            {
                conn = (HttpURLConnection)url.OpenConnection();
                conn.RequestMethod = "POST";
                conn.DoOutput      = true;
                conn.DoInput       = true;
                conn.Connect();

                Android.Util.Log.Debug("SendToServer", "parametros " + parameters);

                byte[] bytes = Encoding.ASCII.GetBytes(parameters);

                OutputStream outputStream = new BufferedOutputStream(conn.OutputStream);
                outputStream.Write(bytes);
                outputStream.Flush();
                outputStream.Close();

                InputStream inputStream = new BufferedInputStream(conn.InputStream);

                return(ReadString(inputStream));
            }
            catch (IOException e)
            {
                Android.Util.Log.Debug("SendToServer", "Problems to send data to server!! " + e.Message);
                return(false);
            }
            finally
            {
                conn.Disconnect();
            }
        }
Beispiel #5
0
        /// <exception cref="System.IO.IOException"></exception>
        private static void Write(FilePath[] files, PackWriter pw)
        {
            long begin            = files[0].GetParentFile().LastModified();
            NullProgressMonitor m = NullProgressMonitor.INSTANCE;
            OutputStream        @out;

            @out = new BufferedOutputStream(new FileOutputStream(files[0]));
            try
            {
                pw.WritePack(m, m, @out);
            }
            finally
            {
                @out.Close();
            }
            @out = new BufferedOutputStream(new FileOutputStream(files[1]));
            try
            {
                pw.WriteIndex(@out);
            }
            finally
            {
                @out.Close();
            }
            Touch(begin, files[0].GetParentFile());
        }
        public override double Evaluate(double[] x)
        {
            double score;

            // initialized below
            SetValues(x);
            if (GetCmd() != null)
            {
                EvaluateCmd(GetCmd());
                score = InterpretCmdOutput();
            }
            else
            {
                try
                {
                    // TODO: Classify in memory instead of writing to tmp file
                    File f = File.CreateTempFile("CRFClassifierEvaluator", "txt");
                    f.DeleteOnExit();
                    OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(f));
                    PrintWriter  pw           = IOUtils.EncodedOutputStreamPrintWriter(outputStream, null, true);
                    classifier.ClassifyAndWriteAnswers(data, featurizedData, pw, classifier.MakeReaderAndWriter());
                    outputStream.Close();
                    BufferedReader           br    = new BufferedReader(new FileReader(f));
                    MultiClassChunkEvalStats stats = new MultiClassChunkEvalStats("O");
                    score = stats.Score(br, "\t");
                    log.Info(stats.GetConllEvalString());
                    f.Delete();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex);
                }
            }
            return(score);
        }
Beispiel #7
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void write(String fileName) throws java.io.IOException
        public virtual void write(string fileName)
        {
            System.IO.FileStream fileOutputStream     = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            GZIPOutputStream     gzipOutputStream     = new GZIPOutputStream(fileOutputStream);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(gzipOutputStream);
            StateOutputStream    stream = new StateOutputStream(bufferedOutputStream);

            if (log.InfoEnabled)
            {
                Console.WriteLine(string.Format("Writing state to file '{0}'", fileName));
            }

            try
            {
                write(stream);
            }
            finally
            {
                stream.close();
            }

            //if (log.DebugEnabled)
            {
                Console.WriteLine(string.Format("Done writing state to file '{0}'", fileName));
            }
        }
            /**
             * Writes the chunks to a file as a contiguous stream. Useful for debugging.
             */
            public void saveToFile(string path)
            {
                System.IO.FileStream fos = null;
                BufferedOutputStream bos = null;

                try {
                    fos = new System.IO.FileStream(path, System.IO.FileMode.Create);
                    bos = new BufferedOutputStream(fos);
                    fos = null;                         // closing bos will also close fos

                    int numChunks = NumChunks;
                    for (int i = 0; i < numChunks; i++)
                    {
                        byte[] chunk = _chunks[i];
                        bos.Write(chunk);
                    }
                } catch (System.IO.IOException) {
                    //throw new RuntimeException(ioe);
                } finally {
                    try {
                        if (bos != null)
                        {
                            bos.Close();
                        }
                        if (fos != null)
                        {
                            fos.Close();
                        }
                    } catch (System.IO.IOException) {
                        //throw new RuntimeException(ioe);
                    }
                }
            }
Beispiel #9
0
 public static void saveDecFile(byte[] encodedBytes, String path, string fileName)
 {
     try
     {
         System.IO.File.Copy(path, "/storage/emulated/0/movies/" + fileName);
         Java.IO.File         file = new Java.IO.File(path);
         System.IO.FileStream fs   = new System.IO.FileStream("/storage/emulated/0/movies/" + fileName, FileMode.Open);
         BufferedOutputStream bos  = new BufferedOutputStream(fs);
         bos.Write(encodedBytes);
         bos.Flush();
         bos.Close();
     }
     catch (Java.IO.FileNotFoundException e)
     {
         e.PrintStackTrace();
     }
     catch (Java.IO.IOException e)
     {
         e.PrintStackTrace();
     }
     catch (Exception e)
     {
         //  e.PrintStackTrace();
     }
 }
        public OutputStream write(bool append, int bufferSize)
        {
            BufferedOutputStream writer = new BufferedOutputStream();

            writer._init_(write(append), bufferSize);
            return(writer);
        }
Beispiel #11
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static void copyfile(String source, String destination) throws org.maltparser.core.exception.MaltChainedException
        public static void copyfile(string source, string destination)
        {
            try
            {
                sbyte[]              readBuffer = new sbyte[BUFFER];
                BufferedInputStream  bis        = new BufferedInputStream(new FileStream(source, FileMode.Open, FileAccess.Read));
                BufferedOutputStream bos        = new BufferedOutputStream(new FileStream(destination, FileMode.Create, FileAccess.Write), BUFFER);
                int n = 0;
                while ((n = bis.read(readBuffer, 0, BUFFER)) != -1)
                {
                    bos.write(readBuffer, 0, n);
                }
                bos.flush();
                bos.close();
                bis.close();
            }
            catch (FileNotFoundException e)
            {
                throw new MaltChainedException("The destination file '" + destination + "' cannot be created when coping the file. ", e);
            }
            catch (IOException e)
            {
                throw new MaltChainedException("The source file '" + source + "' cannot be copied to destination '" + destination + "'. ", e);
            }
        }
Beispiel #12
0
        /// <exception cref="System.IO.IOException"></exception>
        protected virtual void Copy(Socket4Adapter sock, IOutputStream rawout, int length
                                    , bool update)
        {
            var @out      = new BufferedOutputStream(rawout);
            var buffer    = new byte[BlobImpl.CopybufferLength];
            var totalread = 0;

            while (totalread < length)
            {
                var stilltoread = length - totalread;
                var readsize    = (stilltoread < buffer.Length ? stilltoread : buffer.Length);
                var curread     = sock.Read(buffer, 0, readsize);
                if (curread < 0)
                {
                    throw new IOException();
                }
                @out.Write(buffer, 0, curread);
                totalread += curread;
                if (update)
                {
                    _currentByte += curread;
                }
            }
            @out.Flush();
            @out.Close();
        }
Beispiel #13
0
        public void UnZip(string zipFileLocation, string destinationRootFolder, string zipRootToRemove)
        {
            try
            {
                var zipFile        = new ZipFile(zipFileLocation);
                var zipFileEntries = zipFile.entries();

                while (zipFileEntries.hasMoreElements())
                {
                    var zipEntry = (ZipEntry)zipFileEntries.nextElement();

                    var name = zipEntry.getName().Replace(zipRootToRemove, "").Replace("/", "\\").TrimStart('/').TrimStart('\\');
                    var p    = this.fileSystem.Path.Combine(destinationRootFolder, name);

                    if (zipEntry.isDirectory())
                    {
                        if (!this.fileSystem.Directory.Exists(p))
                        {
                            this.fileSystem.Directory.CreateDirectory(p);
                        }
                        ;
                    }
                    else
                    {
                        using (var bis = new BufferedInputStream(zipFile.getInputStream(zipEntry)))
                        {
                            var buffer = new byte[2048];
                            var count  = buffer.GetLength(0);
                            using (var fos = new FileOutputStream(p))
                            {
                                using (var bos = new BufferedOutputStream(fos, count))
                                {
                                    int size;
                                    while ((size = bis.read(buffer, 0, count)) != -1)
                                    {
                                        bos.write(buffer, 0, size);
                                    }

                                    bos.flush();
                                    bos.close();
                                }
                            }

                            bis.close();
                        }
                    }
                }

                zipFile.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (Exception e)
            {
                var t = e.ToString();
            }
        }
        /// <exception cref="System.IO.FileNotFoundException"></exception>
        private void OpenTempFile()
        {
            string   uuid     = Misc.TDCreateUUID();
            string   filename = string.Format("{0}.blobtmp", uuid);
            FilePath tempDir  = store.TempDir();

            tempFile  = new FilePath(tempDir, filename);
            outStream = new BufferedOutputStream(new FileOutputStream(tempFile));
        }
Beispiel #15
0
 public XmlBuffer(int maxBufferSize)
 {
     if (maxBufferSize < 0)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError((Exception) new ArgumentOutOfRangeException("maxBufferSize", (object)maxBufferSize, SR.GetString("ValueMustBeNonNegative")));
     }
     this.stream   = (BufferedOutputStream) new BufferManagerOutputStream("XmlBufferQuotaExceeded", Math.Min(512, maxBufferSize), maxBufferSize, BufferManager.CreateBufferManager(0L, int.MaxValue));
     this.sections = new List <XmlBuffer.Section>(1);
 }
        public void Correct_Read()
        {
            var arr       = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            var mem       = new MemoryStream(arr);
            var bufreader = new BufferedOutputStream(mem);
            var buf       = new byte[arr.Length];

            bufreader.Read(buf, 0, buf.Length);
            Assert.Equal(arr, buf);
        }
        public XmlBuffer(int maxBufferSize)
        {
            if (maxBufferSize < 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxBufferSize", maxBufferSize, System.ServiceModel.SR.GetString("ValueMustBeNonNegative")));
            }
            int initialSize = Math.Min(0x200, maxBufferSize);

            this.stream   = new BufferManagerOutputStream("XmlBufferQuotaExceeded", initialSize, maxBufferSize, BufferManager.CreateBufferManager(0L, 0x7fffffff));
            this.sections = new List <Section>(1);
        }
Beispiel #18
0
        public virtual void AES256IGEDecrypt(string sourceFile, string destFile, byte[] iv, byte[] key)
        {
            int           num1;
            File          file   = new File(sourceFile);
            File          file2  = new File(destFile);
            AESFastEngine engine = new AESFastEngine();

            engine.init(false, new KeyParameter(key));
            byte[] buffer  = CryptoUtils.substring(iv, 0x10, 0x10);
            byte[] buffer2 = CryptoUtils.substring(iv, 0, 0x10);
            BufferedInputStream.__ <clinit>();
            BufferedInputStream  stream  = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream stream2 = new BufferedOutputStream(new FileOutputStream(file2));

            byte[] buffer3 = new byte[0x10];
Label_0060:
            num1 = stream.read(buffer3);
            if (num1 <= 0)
            {
                stream2.flush();
                stream2.close();
                stream.close();
            }
            else
            {
                byte[] @in   = new byte[0x10];
                int    index = 0;
                while (true)
                {
                    if (index >= 0x10)
                    {
                        break;
                    }
                    @in[index] = (byte)((sbyte)(buffer3[index] ^ buffer[index]));
                    index++;
                }
                engine.processBlock(@in, 0, @in, 0);
                index = 0;
                while (true)
                {
                    if (index >= 0x10)
                    {
                        break;
                    }
                    @in[index] = (byte)((sbyte)(@in[index] ^ buffer2[index]));
                    index++;
                }
                buffer2 = buffer3;
                buffer  = @in;
                buffer3 = new byte[0x10];
                stream2.write(@in);
                goto Label_0060;
            }
        }
Beispiel #19
0
        public virtual void saveModel(string filename)
        {
            FileOutputStream     fileOutputStream     = new FileOutputStream(filename);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            ObjectOutputStream   objectOutputStream   = new ObjectOutputStream(bufferedOutputStream);

            this.writeFst(objectOutputStream);
            objectOutputStream.flush();
            objectOutputStream.close();
            bufferedOutputStream.close();
            fileOutputStream.close();
        }
Beispiel #20
0
        public void Close()
        {
            if (_bufferState != BufferState.Created)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidStateException());
            }

            _bufferState = BufferState.Reading;
            _buffer      = _stream.ToArray(out int bufferSize);
            _writer      = null;
            _stream      = null;
        }
Beispiel #21
0
        public XmlBuffer(int maxBufferSize)
        {
            if (maxBufferSize < 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxBufferSize", maxBufferSize,
                                                                                                          SR.GetString(SR.ValueMustBeNonNegative)));
            }
            int initialBufferSize = Math.Min(512, maxBufferSize);

            stream = new BufferManagerOutputStream(SR.XmlBufferQuotaExceeded, initialBufferSize, maxBufferSize,
                                                   BufferManager.CreateBufferManager(0, int.MaxValue));
            sections = new List <Section>(1);
        }
Beispiel #22
0
        public void Close()
        {
            if (this.bufferState != XmlBuffer.BufferState.Created)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(this.CreateInvalidStateException());
            }
            this.bufferState = XmlBuffer.BufferState.Reading;
            int bufferSize;

            this.buffer = this.stream.ToArray(out bufferSize);
            this.writer = (XmlDictionaryWriter)null;
            this.stream = (BufferedOutputStream)null;
        }
        public void Read_EOF_Well()
        {
            var arr       = new byte[5000];
            var mem       = new MemoryStream(arr);
            var bufreader = new BufferedOutputStream(mem);

            var buf = new byte[5000];

            bufreader.Read(buf, 0, buf.Length);
            var n = bufreader.Read(buf, 0, buf.Length);

            Assert.Equal(0, n);
        }
Beispiel #24
0
 /// <summary>
 /// Get SASL wrapped OutputStream if SASL QoP requires wrapping,
 /// otherwise return original stream.
 /// </summary>
 /// <remarks>
 /// Get SASL wrapped OutputStream if SASL QoP requires wrapping,
 /// otherwise return original stream.  Can be called only after
 /// saslConnect() has been called.
 /// </remarks>
 /// <param name="in">- InputStream used to make the connection</param>
 /// <returns>InputStream that may be using SASL unwrap</returns>
 /// <exception cref="System.IO.IOException"/>
 public virtual OutputStream GetOutputStream(OutputStream @out)
 {
     if (UseWrap())
     {
         // the client and server negotiate a maximum buffer size that can be
         // wrapped
         string maxBuf = (string)saslClient.GetNegotiatedProperty(Javax.Security.Sasl.Sasl
                                                                  .RawSendSize);
         @out = new BufferedOutputStream(new SaslRpcClient.WrappedOutputStream(this, @out)
                                         , System.Convert.ToInt32(maxBuf));
     }
     return(@out);
 }
        public void Close()
        {
            int num;

            if (this.bufferState != BufferState.Created)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(this.CreateInvalidStateException());
            }
            this.bufferState = BufferState.Reading;
            this.buffer      = this.stream.ToArray(out num);
            this.writer      = null;
            this.stream      = null;
        }
Beispiel #26
0
 /// <exception cref="System.IO.IOException"/>
 private static void WriteToIndexFile(string logLocation, bool isCleanup)
 {
     lock (typeof(TaskLog))
     {
         // To ensure atomicity of updates to index file, write to temporary index
         // file first and then rename.
         FilePath             tmpIndexFile = GetTmpIndexFile(currentTaskid, isCleanup);
         BufferedOutputStream bos          = null;
         DataOutputStream     dos          = null;
         try
         {
             bos = new BufferedOutputStream(SecureIOUtils.CreateForWrite(tmpIndexFile, 0x1a4));
             dos = new DataOutputStream(bos);
             //the format of the index file is
             //LOG_DIR: <the dir where the task logs are really stored>
             //STDOUT: <start-offset in the stdout file> <length>
             //STDERR: <start-offset in the stderr file> <length>
             //SYSLOG: <start-offset in the syslog file> <length>
             dos.WriteBytes(TaskLog.LogFileDetail.Location + logLocation + "\n" + TaskLog.LogName
                            .Stdout.ToString() + ":");
             dos.WriteBytes(System.Convert.ToString(prevOutLength) + " ");
             dos.WriteBytes(System.Convert.ToString(new FilePath(logLocation, TaskLog.LogName.
                                                                 Stdout.ToString()).Length() - prevOutLength) + "\n" + TaskLog.LogName.Stderr + ":"
                            );
             dos.WriteBytes(System.Convert.ToString(prevErrLength) + " ");
             dos.WriteBytes(System.Convert.ToString(new FilePath(logLocation, TaskLog.LogName.
                                                                 Stderr.ToString()).Length() - prevErrLength) + "\n" + TaskLog.LogName.Syslog.ToString
                                () + ":");
             dos.WriteBytes(System.Convert.ToString(prevLogLength) + " ");
             dos.WriteBytes(System.Convert.ToString(new FilePath(logLocation, TaskLog.LogName.
                                                                 Syslog.ToString()).Length() - prevLogLength) + "\n");
             dos.Close();
             dos = null;
             bos.Close();
             bos = null;
         }
         finally
         {
             IOUtils.Cleanup(Log, dos, bos);
         }
         FilePath indexFile        = GetIndexFile(currentTaskid, isCleanup);
         Path     indexFilePath    = new Path(indexFile.GetAbsolutePath());
         Path     tmpIndexFilePath = new Path(tmpIndexFile.GetAbsolutePath());
         if (localFS == null)
         {
             // set localFS once
             localFS = FileSystem.GetLocal(new Configuration());
         }
         localFS.Rename(tmpIndexFilePath, indexFilePath);
     }
 }
Beispiel #27
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private void open(java.io.File fname, boolean append) throws java.io.IOException
        private void Open(File fname, bool append)
        {
            int len = 0;

            if (append)
            {
                len = (int)fname.Length();
            }
            FileOutputStream     fout = new FileOutputStream(fname.ToString(), append);
            BufferedOutputStream bout = new BufferedOutputStream(fout);

            Meter        = new MeteredStream(this, bout, len);
            OutputStream = Meter;
        }
Beispiel #28
0
        /// <summary>
        /// Stores the data in {@code config} into {@code file} in a standard java
        /// <seealso cref="Properties"/> format. </summary>
        /// <param name="config"> the data to store in the properties file. </param>
        /// <param name="file"> the file to store the properties in. </param>
        /// <exception cref="IOException"> IO error. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static void store(java.util.Map<String, String> config, java.io.File file) throws java.io.IOException
        public static void Store(IDictionary <string, string> config, File file)
        {
            Stream stream = null;

            try
            {
                stream = new BufferedOutputStream(new FileStream(file, FileMode.Create, FileAccess.Write));
                Store(config, stream);
            }
            finally
            {
                CloseIfNotNull(stream);
            }
        }
            /// <summary>Write output to files.</summary>
            /// <exception cref="System.IO.IOException"/>
            /// <exception cref="System.Exception"/>
            protected override void Cleanup(Reducer.Context context)
            {
                Configuration conf = context.GetConfiguration();
                Path          dir  = new Path(conf.Get(WorkingDirProperty));
                FileSystem    fs   = dir.GetFileSystem(conf);

                {
                    // write hex output
                    Path         hexfile = new Path(conf.Get(HexFileProperty));
                    OutputStream @out    = new BufferedOutputStream(fs.Create(hexfile));
                    try
                    {
                        foreach (byte b in hex)
                        {
                            @out.Write(b);
                        }
                    }
                    finally
                    {
                        @out.Close();
                    }
                }
                // If the starting digit is 1,
                // the hex value can be converted to decimal value.
                if (conf.GetInt(DigitStartProperty, 1) == 1)
                {
                    Path outfile = new Path(dir, "pi.txt");
                    Log.Info("Writing text output to " + outfile);
                    OutputStream outputstream = fs.Create(outfile);
                    try
                    {
                        PrintWriter @out = new PrintWriter(new OutputStreamWriter(outputstream, Charsets.
                                                                                  Utf8), true);
                        // write hex text
                        Print(@out, hex.GetEnumerator(), "Pi = 0x3.", "%02X", 5, 5);
                        @out.WriteLine("Total number of hexadecimal digits is " + 2 * hex.Count + ".");
                        // write decimal text
                        BaileyBorweinPlouffe.Fraction dec = new BaileyBorweinPlouffe.Fraction(hex);
                        int decDigits = 2 * hex.Count;
                        // TODO: this is conservative.
                        Print(@out, new _IEnumerator_168(decDigits, dec), "Pi = 3.", "%d", 10, 5);
                        @out.WriteLine("Total number of decimal digits is " + decDigits + ".");
                    }
                    finally
                    {
                        outputstream.Close();
                    }
                }
            }
Beispiel #30
0
 /// <summary>Write the word vectors to a file.</summary>
 /// <param name="file">The file to write to.</param>
 /// <exception cref="System.IO.IOException">Thrown if the file could not be written to.</exception>
 public virtual void Serialize(string file)
 {
     using (OutputStream output = new BufferedOutputStream(new FileOutputStream(new File(file))))
     {
         if (file.EndsWith(".gz"))
         {
             using (GZIPOutputStream gzip = new GZIPOutputStream(output))
             {
                 Serialize(gzip);
             }
         }
         else
         {
             Serialize(output);
         }
     }
 }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public MessageList paymentRequest(DirectPaymentRequest directPaymentRequest, EasypayConfig config) throws java.net.MalformedURLException
		public virtual MessageList paymentRequest(DirectPaymentRequest directPaymentRequest, EasypayConfig config)
		{

			URL url = new URL("https://" + config.Host);
			string httpRequestMethod = "POST";
			string contentHash = "xxx";
			string contentType = "??";
			string date = "";
			string path = "";

			HttpURLConnection urlConnection = null;
			try
			{
				urlConnection = (HttpURLConnection) url.openConnection();

				urlConnection.RequestMethod = httpRequestMethod;
				urlConnection.setRequestProperty("Content-Type", contentType);
				// urlConnection.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));

				urlConnection.UseCaches = false;
				urlConnection.DoInput = true;
				urlConnection.DoOutput = true;

				System.IO.Stream @out = new BufferedOutputStream(urlConnection.OutputStream);
				// writeStream(out);

				System.IO.Stream @in = new BufferedInputStream(urlConnection.InputStream);
				// readStream(in);


			}
			catch (IOException e)
			{
				Console.WriteLine(e.ToString());
				Console.Write(e.StackTrace);
			}
			finally
			{
				if (urlConnection != null)
				{
					urlConnection.disconnect();
				}
			}
			return new MessageList();
		}