internal static List <HocrPageModel> GetPageWordDetails(PDDocument document) { List <HocrPageModel> hocrPageModels; try { PDFHocr pDFHocr = new PDFHocr(); pDFHocr.setSortByPosition(true); pDFHocr.setStartPage(0); pDFHocr.setEndPage(document.getNumberOfPages()); Writer outputStreamWriter = new OutputStreamWriter(new ByteArrayOutputStream()); PDFHelper.DisplayTrialPopupIfNecessary(); if (PDFHelper.AddStamp) { pDFHocr.setEndPage(3); } pDFHocr.writeText(document, outputStreamWriter); if ((pDFHocr.lineList == null ? false : pDFHocr.lineList.Count > 0)) { HocrPageModel hocrPageModel = new HocrPageModel(); hocrPageModel.Lines.AddRange(pDFHocr.SortLineList(pDFHocr.lineList)); pDFHocr.pageList.Add(hocrPageModel); pDFHocr.lineList.Clear(); } hocrPageModels = pDFHocr.pageList; } catch (Exception exception) { hocrPageModels = null; } return(hocrPageModels); }
/// <exception cref="System.Exception"/> public virtual void TestComplexNameWithRegex() { OutputStream os = GetFileSystem().Create(new Path(GetInputDir(), "text.txt")); TextWriter wr = new OutputStreamWriter(os); wr.Write("b a\n"); wr.Close(); JobConf conf = CreateJobConf(); conf.SetJobName("name \\Evalue]"); conf.SetInputFormat(typeof(TextInputFormat)); conf.SetOutputKeyClass(typeof(LongWritable)); conf.SetOutputValueClass(typeof(Text)); conf.SetMapperClass(typeof(IdentityMapper)); FileInputFormat.SetInputPaths(conf, GetInputDir()); FileOutputFormat.SetOutputPath(conf, GetOutputDir()); JobClient.RunJob(conf); Path[] outputFiles = FileUtil.Stat2Paths(GetFileSystem().ListStatus(GetOutputDir( ), new Utils.OutputFileUtils.OutputFilesFilter())); NUnit.Framework.Assert.AreEqual(1, outputFiles.Length); InputStream @is = GetFileSystem().Open(outputFiles[0]); BufferedReader reader = new BufferedReader(new InputStreamReader(@is)); NUnit.Framework.Assert.AreEqual("0\tb a", reader.ReadLine()); NUnit.Framework.Assert.IsNull(reader.ReadLine()); reader.Close(); }
public virtual RewriterResults rewrite(sRequest request, sResponse original, MutableContent content) { ByteArrayOutputStream baos = new ByteArrayOutputStream((content.getContent().Length * 110) / 100); OutputStreamWriter output = new OutputStreamWriter(baos); String mimeType = original.getHeader("Content-Type"); if (request.RewriteMimeType != null) { mimeType = request.RewriteMimeType; } GadgetSpec spec = null; if (request.Gadget != null) { spec = _specFactory.getGadgetSpec(request.Gadget.toJavaUri(), false); } if (rewrite(spec, request.getUri(), content, mimeType, output)) { content.setContent(Encoding.Default.GetString(baos.toByteArray())); return(RewriterResults.cacheableIndefinitely()); } return(null); }
/// <exception cref="System.Exception"/> private void MrRun() { FileSystem fs = FileSystem.Get(GetJobConf()); Path inputDir = new Path("input"); fs.Mkdirs(inputDir); TextWriter writer = new OutputStreamWriter(fs.Create(new Path(inputDir, "data.txt" ))); writer.Write("hello"); writer.Close(); Path outputDir = new Path("output", "output"); JobConf jobConf = new JobConf(GetJobConf()); jobConf.SetInt("mapred.map.tasks", 1); jobConf.SetInt("mapred.map.max.attempts", 1); jobConf.SetInt("mapred.reduce.max.attempts", 1); jobConf.Set("mapred.input.dir", inputDir.ToString()); jobConf.Set("mapred.output.dir", outputDir.ToString()); JobClient jobClient = new JobClient(jobConf); RunningJob runJob = jobClient.SubmitJob(jobConf); runJob.WaitForCompletion(); NUnit.Framework.Assert.IsTrue(runJob.IsComplete()); NUnit.Framework.Assert.IsTrue(runJob.IsSuccessful()); }
public String testFreemarker() { Assembly _assembly; _assembly = Assembly.GetExecutingAssembly(); //Console.WriteLine(_assembly. try{ Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(new File("template")); //cfg.setDirectoryForTemplateLoading(new File("")); cfg.setObjectWrapper(new DefaultObjectWrapper()); Template temp = cfg.getTemplate("c.ftl"); Map root = new HashMap(); root.put("codeGen", this); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Writer output = new OutputStreamWriter(outputStream); temp.process(root, output); output.flush(); //System.Console.WriteLine(outputStream.toString()); return(outputStream.toString()); } catch (IOException exception) { } catch (TemplateException exception) { } return(""); }
public Writer writer(bool append, Java.Lang.String encoding) { OutputStreamWriter writer = new OutputStreamWriter(); writer._init_(write(append), encoding); return(writer); }
/// <summary> /// Convert a string into an input stream. /// @throws UnsupportedEncodingException if the encoding is not supported /// </summary> /// <param name="content">the string</param> /// <param name="encoding">the encoding to use when converting the string to a stream</param> /// <returns>the resulting input stream</returns> public static InputStream ToInputStream(String content, String encoding) { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(content.Length * 2); OutputStreamWriter writer = new OutputStreamWriter(byteArrayOutputStream, encoding); writer.write(content); writer.flush(); byte[] byteArray = byteArrayOutputStream.toByteArray(); return(new ByteArrayInputStream(byteArray)); } /* catch (UnsupportedEncodingException e) { * throw e; * }*/ catch (IOException e) { // Theoretically impossible since all the "IO" is in memory but it's a // checked exception so we have to catch it. throw new IllegalStateException("Exception when converting a string to an input stream: '" + e + "'", e); } catch (Exception e) { throw; } }
/// <exception cref="System.IO.IOException"/> private void WriteSrcFile(Path srcFilePath, string fileName, string data) { OutputStreamWriter osw = GetOutputStreamWriter(srcFilePath, fileName); osw.Write(data); osw.Close(); }
/// <summary>Write the current dfsUsed to the cache file.</summary> internal virtual void SaveDfsUsed() { FilePath outFile = new FilePath(currentDir, DuCacheFile); if (outFile.Exists() && !outFile.Delete()) { FsDatasetImpl.Log.Warn("Failed to delete old dfsUsed file in " + outFile.GetParent ()); } try { long used = GetDfsUsed(); using (TextWriter @out = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8" )) { // mtime is written last, so that truncated writes won't be valid. @out.Write(System.Convert.ToString(used) + " " + System.Convert.ToString(Time.Now ())); @out.Flush(); } } catch (IOException ioe) { // If write failed, the volume might be bad. Since the cache file is // not critical, log the error and continue. FsDatasetImpl.Log.Warn("Failed to write dfsUsed to " + outFile, ioe); } }
void send(InputStream fis, string contenttype = "application/octet-stream") { string header = "HTTP/1.1 200 OK\n"; header += "Content-type: "; header += contenttype; header += "\n"; //header += "Content-Length: " + fis.available() + "\n" + header += "\n"; try { var w = new OutputStreamWriter(output); w.write(header); w.flush(); sbyte[] buffer = new sbyte[1024]; int bytes = 0; bytes = fis.read(buffer); while (bytes != -1) { output.write(buffer, 0, bytes); bytes = fis.read(buffer); } } catch { } }
// TODO: when this method throws an exception (for whatever reason) // a waiting client might hang. There should be some graceful // handling of that. /// <exception cref="System.IO.IOException"/> public virtual void HandleDependencies(string arg, OutputStream outStream, string commandArgs) { Tree tree = Parse(arg, false); if (tree == null) { return; } // TODO: this might throw an exception if the parser doesn't support dependencies. Handle that cleaner? GrammaticalStructure gs = parser.GetTLPParams().GetGrammaticalStructure(tree, parser.TreebankLanguagePack().PunctuationWordRejectFilter(), parser.GetTLPParams().TypedDependencyHeadFinder()); ICollection <TypedDependency> deps = null; switch (commandArgs.ToUpper()) { case "COLLAPSED_TREE": { deps = gs.TypedDependenciesCollapsedTree(); break; } default: { throw new NotSupportedException("Dependencies type not implemented: " + commandArgs); } } OutputStreamWriter osw = new OutputStreamWriter(outStream, "utf-8"); foreach (TypedDependency dep in deps) { osw.Write(dep.ToString()); osw.Write("\n"); } osw.Flush(); }
/// <exception cref="System.Exception"/> private string RunJob() { OutputStream os = GetFileSystem().Create(new Path(GetInputDir(), "text.txt")); TextWriter wr = new OutputStreamWriter(os); wr.Write("hello1\n"); wr.Write("hello2\n"); wr.Write("hello3\n"); wr.Close(); JobConf conf = CreateJobConf(); conf.SetJobName("mr"); conf.SetJobPriority(JobPriority.High); conf.SetInputFormat(typeof(TextInputFormat)); conf.SetMapOutputKeyClass(typeof(LongWritable)); conf.SetMapOutputValueClass(typeof(Text)); conf.SetOutputFormat(typeof(TextOutputFormat)); conf.SetOutputKeyClass(typeof(LongWritable)); conf.SetOutputValueClass(typeof(Text)); conf.SetMapperClass(typeof(IdentityMapper)); conf.SetReducerClass(typeof(IdentityReducer)); FileInputFormat.SetInputPaths(conf, GetInputDir()); FileOutputFormat.SetOutputPath(conf, GetOutputDir()); return(JobClient.RunJob(conf).GetID().ToString()); }
/// <exception cref="System.Exception"/> public virtual void TestFormat() { JobConf job = new JobConf(); Path file = new Path(workDir, "test.txt"); int seed = new Random().Next(); Random random = new Random(seed); localFs.Delete(workDir, true); FileInputFormat.SetInputPaths(job, workDir); int numLinesPerMap = 5; job.SetInt("mapreduce.input.lineinputformat.linespermap", numLinesPerMap); // for a variety of lengths for (int length = 0; length < MaxLength; length += random.Next(MaxLength / 10) + 1) { // create a file with length entries TextWriter writer = new OutputStreamWriter(localFs.Create(file)); try { for (int i = 0; i < length; i++) { writer.Write(Sharpen.Extensions.ToString(i)); writer.Write("\n"); } } finally { writer.Close(); } CheckFormat(job, numLinesPerMap); } }
/// <exception cref="System.IO.IOException"/> private static void WriteJson(IDictionary map, OutputStream os) { TextWriter writer = new OutputStreamWriter(os, Charsets.Utf8); ObjectMapper jsonMapper = new ObjectMapper(); jsonMapper.WriterWithDefaultPrettyPrinter().WriteValue(writer, map); }
public static void CreateButton(OutputStreamWriter writer, string path, string name) { writer.Write("<button onclick=\"window.open(\'" + path + "\', \'_self\');\">"); writer.Write(name); writer.Write("</button>"); writer.Write("<br>"); }
/// <summary> /// Convert a string into an input stream. /// @throws UnsupportedEncodingException if the encoding is not supported /// </summary> /// <param name="content">the string</param> /// <param name="encoding">the encoding to use when converting the string to a stream</param> /// <returns>the resulting input stream</returns> public static InputStream ToInputStream(String content, String encoding) { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(content.Length * 2); OutputStreamWriter writer = new OutputStreamWriter(byteArrayOutputStream, encoding); writer.write(content); writer.flush(); byte[] byteArray = byteArrayOutputStream.toByteArray(); return new ByteArrayInputStream(byteArray); } /* catch (UnsupportedEncodingException e) { throw e; }*/ catch (IOException e) { // Theoretically impossible since all the "IO" is in memory but it's a // checked exception so we have to catch it. throw new IllegalStateException("Exception when converting a string to an input stream: '" + e + "'", e); } catch (Exception e) { throw; } }
/// <summary> /// Create a processor that writes to the file named and may or may not /// also output to the screen, as specified. /// </summary> /// <param name="filename">Name of file to write output to</param> /// <param name="printToScreen">Mirror output to screen?</param> /// <exception cref="System.IO.IOException"/> public TextWriterImageVisitor(string filename, bool printToScreen) : base() { this.printToScreen = printToScreen; fw = new OutputStreamWriter(new FileOutputStream(filename), Charsets.Utf8); okToWrite = true; }
//метод записи файла private void WriteFile(DriveId folderBackUpId, string filename, IDriveApiDriveContentsResult content) { try { byte[] bytes = System.IO.File.ReadAllBytes(pathToDb); string file = Convert.ToBase64String(bytes); using (var writer = new OutputStreamWriter(content.DriveContents.OutputStream)) { writer.Write(file); writer.Close(); } MetadataChangeSet changeSet = new MetadataChangeSet.Builder() .SetTitle(filename) .SetMimeType("application/octet-stream") .Build(); IDriveFolder driveFolder = null; //получаем папку по ID driveFolder = driveFolder ?? folderBackUpId.AsDriveFolder(); //если папка не ноль то создаем файл if (driveFolder != null) { var s = driveFolder.CreateFile(_googleApiClient, changeSet, content.DriveContents); CreateAlertDialog("", successMessage); } } catch (Exception er) { CreateAlertDialog("", errorMessage + er.Message); } }
public static async Task WriteFile(Context context, Uri uri, string data) { await Task.Run(async delegate { Stream output = null; OutputStreamWriter outputWriter = null; BufferedWriter bufferedWriter = null; try { output = context.ContentResolver.OpenOutputStream(uri); outputWriter = new OutputStreamWriter(output); bufferedWriter = new BufferedWriter(outputWriter); await bufferedWriter.WriteAsync(data); await bufferedWriter.FlushAsync(); } finally { bufferedWriter?.Close(); outputWriter?.Close(); output?.Close(); } }); }
/// <summary>Returs a Tree from the server connected to at host:port.</summary> /// <exception cref="System.IO.IOException"/> public virtual Tree GetTree(string query) { Socket socket = new Socket(host, port); TextWriter @out = new OutputStreamWriter(socket.GetOutputStream(), "utf-8"); @out.Write("tree " + query + "\n"); @out.Flush(); ObjectInputStream ois = new ObjectInputStream(socket.GetInputStream()); object o; try { o = ois.ReadObject(); } catch (TypeLoadException e) { throw new Exception(e); } if (!(o is Tree)) { throw new ArgumentException("Expected a tree"); } Tree tree = (Tree)o; socket.Close(); return(tree); }
/// <summary>Creates a new <see cref="OutgoingRequestFrame"/> for an operation with a single non-struct /// parameter.</summary> /// <typeparam name="T">The type of the operation's parameter.</typeparam> /// <param name="proxy">A proxy to the target Ice object. This method uses the communicator, identity, facet, /// encoding and context of this proxy to create the request frame.</param> /// <param name="operation">The operation to invoke on the target Ice object.</param> /// <param name="idempotent">True when operation is idempotent, otherwise false.</param> /// <param name="compress">True if the request should be compressed, false otherwise.</param> /// <param name="format">The format to use when writing class instances in case <c>args</c> contains class /// instances.</param> /// <param name="context">An optional explicit context. When non null, it overrides both the context of the /// proxy and the communicator's current context (if any).</param> /// <param name="args">The argument(s) to write into the frame.</param> /// <param name="writer">The <see cref="OutputStreamWriter{T}"/> that writes the arguments into the frame. /// </param> /// <returns>A new OutgoingRequestFrame.</returns> public static OutgoingRequestFrame WithArgs <T>( IObjectPrx proxy, string operation, bool idempotent, bool compress, FormatType format, IReadOnlyDictionary <string, string>?context, T args, OutputStreamWriter <T> writer) { var request = new OutgoingRequestFrame(proxy, operation, idempotent, compress, context); var ostr = new OutputStream(proxy.Protocol.GetEncoding(), request.Data, request.PayloadStart, request.Encoding, format); writer(ostr, args); request.PayloadEnd = ostr.Finish(); if (compress && proxy.Encoding == Encoding.V20) { request.CompressPayload(); } return(request); }
// Create a file containing fixed length records with random data /// <exception cref="System.IO.IOException"/> private AList <string> CreateFile(Path targetFile, CompressionCodec codec, int recordLen , int numRecords) { AList <string> recordList = new AList <string>(numRecords); OutputStream ostream = localFs.Create(targetFile); if (codec != null) { ostream = codec.CreateOutputStream(ostream); } TextWriter writer = new OutputStreamWriter(ostream); try { StringBuilder sb = new StringBuilder(); for (int i = 0; i < numRecords; i++) { for (int j = 0; j < recordLen; j++) { sb.Append(chars[charRand.Next(chars.Length)]); } string recordData = sb.ToString(); recordList.AddItem(recordData); writer.Write(recordData); sb.Length = 0; } } finally { writer.Close(); } return(recordList); }
public Writer writer(bool append) { OutputStreamWriter writer = new OutputStreamWriter(); writer._init_(write(append)); return(writer); }
public _Thread_152(long length, OutputStreamWriter osw, int ch, CountDownLatch latch ) { this.length = length; this.osw = osw; this.ch = ch; this.latch = latch; }
private static string SaveBackupInfo(Context context, BackupInfo backupInfo) { OutputStreamWriter streamWriter = new OutputStreamWriter(context.OpenFileOutput("backup.json", FileCreationMode.Private)); streamWriter.Write(JsonConvert.SerializeObject(backupInfo)); streamWriter.Close(); return(context.FilesDir + "/" + "backup.json"); }
/// <exception cref="System.IO.IOException"></exception> private void Config(string data) { OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(configFile), "UTF-8"); fw.Write(data); fw.Close(); }
/// <exception cref="System.IO.IOException"/> public virtual void Save(string filepath) { using (OutputStreamWriter fout = new OutputStreamWriter(new FileOutputStream(filepath ), Sharpen.Extensions.GetEncoding("UTF-8"))) { fout.Write(GenerateGraphViz()); } }
/// <summary>Generate and write the bundle to the output stream.</summary> /// <remarks> /// Generate and write the bundle to the output stream. /// <p> /// This method can only be called once per BundleWriter instance. /// </remarks> /// <param name="monitor">progress monitor to report bundle writing status to.</param> /// <param name="os"> /// the stream the bundle is written to. The stream should be /// buffered by the caller. The caller is responsible for closing /// the stream. /// </param> /// <exception cref="System.IO.IOException"> /// an error occurred reading a local object's data to include in /// the bundle, or writing compressed object data to the output /// stream. /// </exception> public virtual void WriteBundle(ProgressMonitor monitor, OutputStream os) { PackConfig pc = packConfig; if (pc == null) { pc = new PackConfig(db); } PackWriter packWriter = new PackWriter(pc, db.NewObjectReader()); try { HashSet <ObjectId> inc = new HashSet <ObjectId>(); HashSet <ObjectId> exc = new HashSet <ObjectId>(); Sharpen.Collections.AddAll(inc, include.Values); foreach (RevCommit r in assume) { exc.AddItem(r.Id); } packWriter.SetDeltaBaseAsOffset(true); packWriter.SetThin(exc.Count > 0); packWriter.SetReuseValidatingObjects(false); if (exc.Count == 0) { packWriter.SetTagTargets(tagTargets); } packWriter.PreparePack(monitor, inc, exc); TextWriter w = new OutputStreamWriter(os, Constants.CHARSET); w.Write(NGit.Transport.TransportBundleConstants.V2_BUNDLE_SIGNATURE); w.Write('\n'); char[] tmp = new char[Constants.OBJECT_ID_STRING_LENGTH]; foreach (RevCommit a in assume) { w.Write('-'); a.CopyTo(tmp, w); if (a.RawBuffer != null) { w.Write(' '); w.Write(a.GetShortMessage()); } w.Write('\n'); } foreach (KeyValuePair <string, ObjectId> e in include.EntrySet()) { e.Value.CopyTo(tmp, w); w.Write(' '); w.Write(e.Key); w.Write('\n'); } w.Write('\n'); w.Flush(); packWriter.WritePack(monitor, monitor, os); } finally { packWriter.Release(); } }
/// <summary>Writes the input test file</summary> /// <param name="conf"/> /// <exception cref="System.IO.IOException"/> public virtual void CreateInputFile(Configuration conf) { FileSystem localFs = FileSystem.GetLocal(conf); Path file = new Path(inputDir, "test.txt"); TextWriter writer = new OutputStreamWriter(localFs.Create(file)); writer.Write("abc\ndef\t\nghi\njkl"); writer.Close(); }
/// <exception cref="System.IO.IOException"/> protected internal virtual Path CreateFile(string fileName) { Path file = new Path(workDir, fileName); TextWriter writer = new OutputStreamWriter(localFs.Create(file)); writer.Write(string.Empty); writer.Close(); return(localFs.MakeQualified(file)); }
/// <summary>Tell the server to exit</summary> /// <exception cref="System.IO.IOException"/> public virtual void SendQuit() { Socket socket = new Socket(host, port); TextWriter @out = new OutputStreamWriter(socket.GetOutputStream(), "utf-8"); @out.Write("quit\n"); @out.Flush(); socket.Close(); }
public void WriteToFile(string fileName, string text) { try { File file = new File(context.FilesDir.AbsolutePath, fileName); if (file.Exists()) { file.Delete(); } var outputStreamWriter = new OutputStreamWriter(context.OpenFileOutput(fileName, FileCreationMode.Private)); outputStreamWriter.Write(text); outputStreamWriter.Close(); } catch (IOException e) { Log.Debug("Exception", "File write failed: " + e.ToString()); } }
// actually pushes a note to sdcard, with optional subdirectory (e.g. backup) private static int doPushNote(Note note) { Note rnote = new Note(); try { File path = new File(Tomdroid.NOTES_PATH); if (!path.Exists()) path.Mkdir(); TLog.i(TAG, "Path {0} Exists: {1}", path, path.Exists()); // Check a second time, if not the most likely cause is the volume doesn't exist if(!path.Exists()) { TLog.w(TAG, "Couldn't create {0}", path); return NO_SD_CARD; } path = new File(Tomdroid.NOTES_PATH + "/"+note.getGuid() + ".note"); note.createDate = note.getLastChangeDate().Format3339(false); note.cursorPos = 0; note.width = 0; note.height = 0; note.X = -1; note.Y = -1; if (path.Exists()) { // update existing note // Try reading the file first string contents = ""; try { char[] buffer = new char[0x1000]; contents = readFile(path,buffer); } catch (IOException e) { e.PrintStackTrace(); TLog.w(TAG, "Something went wrong trying to read the note"); return PARSING_FAILED; } try { // Parsing // XML // Get a SAXParser from the SAXPArserFactory SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); // Get the XMLReader of the SAXParser we created XMLReader xr = sp.getXMLReader(); // Create a new ContentHandler, send it this note to fill and apply it to the XML-Reader NoteHandler xmlHandler = new NoteHandler(rnote); xr.setContentHandler(xmlHandler); // Create the proper input source StringReader sr = new StringReader(contents); InputSource inputSource = new InputSource(sr); TLog.d(TAG, "parsing note. filename: {0}", path.Name()); xr.parse(inputSource); // TODO wrap and throw a new exception here } catch (Exception e) { e.PrintStackTrace(); if(e as TimeFormatException) TLog.e(TAG, "Problem parsing the note's date and time"); return PARSING_FAILED; } note.createDate = rnote.createDate; note.cursorPos = rnote.cursorPos; note.width = rnote.width; note.height = rnote.height; note.X = rnote.X; note.Y = rnote.Y; note.setTags(rnote.getTags()); } string xmlOutput = note.getXmlFileString(); path.CreateNewFile(); FileOutputStream fOut = new FileOutputStream(path); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.Append(xmlOutput); myOutWriter.Close(); fOut.Close(); } catch (Exception e) { TLog.e(TAG, "push to sd card didn't work"); return NOTE_PUSH_ERROR; } return NOTE_PUSHED; }
private static void writeXmlHeader(OutputStreamWriter writer) throws IOException {
// -------------------------------------------------------------------------------- // // Interface functions // // -------------------------------------------------------------------------------- public override void writeHeader(VCFHeader header) { // make sure the header is sorted correctly header = new VCFHeader(header.MetaDataInSortedOrder, header.GenotypeSampleNames); // create the config offsets map if (header.ContigLines.Count == 0) { if (ALLOW_MISSING_CONTIG_LINES) { if (GeneralUtils.DEBUG_MODE_ENABLED) { Console.Error.WriteLine("No contig dictionary found in header, falling back to reference sequence dictionary"); } createContigDictionary(VCFUtils.makeContigHeaderLines(RefDict, null)); } else { throw new IllegalStateException("Cannot write BCF2 file with missing contig lines"); } } else { createContigDictionary(header.ContigLines); } // set up the map from dictionary string values -> offset //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final ArrayList<String> dict = org.broadinstitute.variant.bcf2.BCF2Utils.makeDictionary(header); List<string> dict = BCF2Utils.makeDictionary(header); for (int i = 0; i < dict.Count; i++) { stringDictionaryMap[dict[i]] = i; } sampleNames = header.GenotypeSampleNames.ToArray(); // setup the field encodings fieldManager.setup(header, encoder, stringDictionaryMap); try { // write out the header into a byte stream, get it's length, and write everything to the file //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final ByteArrayOutputStream capture = new ByteArrayOutputStream(); ByteArrayOutputStream capture = new ByteArrayOutputStream(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final OutputStreamWriter writer = new OutputStreamWriter(capture); OutputStreamWriter writer = new OutputStreamWriter(capture); this.header = VCFWriter.writeHeader(header, writer, doNotWriteGenotypes, VCFWriter.VersionLine, "BCF2 stream"); writer.append('\0'); // the header is null terminated by a byte writer.close(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final byte[] headerBytes = capture.toByteArray(); sbyte[] headerBytes = capture.toByteArray(); (new BCFVersion(MAJOR_VERSION, MINOR_VERSION)).write(outputStream); BCF2Type.INT32.write(headerBytes.Length, outputStream); outputStream.write(headerBytes); } catch (IOException e) { throw new Exception("BCF2 stream: Got IOException while trying to write BCF2 header", e); } }
// private Handler noteContentHandler = new Handler() { // // public override void handleMessage(Message msg) { // // //parsed ok - show // if(msg.what == NoteContentBuilder.PARSE_OK) { // if(sendAsFile) // sendNoteAsFile(); // else // sendNoteAsText(); // // //parsed not ok - error // } else if(msg.what == NoteContentBuilder.PARSE_ERROR) { // activity.ShowDialog(Tomdroid.DIALOG_PARSE_ERROR); // // } // } // }; private void sendNoteAsFile() { note.cursorPos = 0; note.width = 0; note.height = 0; note.X = -1; note.Y = -1; string xmlOutput = note.GetXmlFilestring(); FileOutputStream outFile = null; Android.Net.Uri noteUri = null; try { clearFilesDir(); outFile = activity.OpenFileOutput(note.getGuid()+".note", FileCreationMode.WorldReadable); OutputStreamWriter osw = new OutputStreamWriter(outFile); osw.Write(xmlOutput); osw.Flush(); osw.Close(); File noteFile = activity.GetFileStreamPath(note.getGuid()+".note"); noteUri = Android.Net.Uri.FromFile(noteFile); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.PrintStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.PrintStackTrace(); } if(noteUri == null) { TLog.e(TAG, "Unable to create note to send"); return; } // Create a new Intent to send messages Intent sendIntent = new Intent(Intent.ActionSend); // Add attributes to the intent sendIntent.PutExtra(Intent.ExtraStream, noteUri); sendIntent.Type = "text/plain"; activity.StartActivity(Intent.CreateChooser(sendIntent, note.getTitle())); return; }