Inheritance: InputStream
 private static void readPreferences()
 {
   FileInputStream fileInputStream = (FileInputStream) null;
   try
   {
     FileInputStream.__\u003Cclinit\u003E();
     fileInputStream = new FileInputStream(BaseTestRunner.getPreferencesFile());
     Properties.__\u003Cclinit\u003E();
     BaseTestRunner.setPreferences(new Properties(BaseTestRunner.getPreferences()));
     BaseTestRunner.getPreferences().load((InputStream) fileInputStream);
     return;
   }
   catch (IOException ex)
   {
   }
   try
   {
     if (fileInputStream == null)
       return;
     ((InputStream) fileInputStream).close();
   }
   catch (IOException ex)
   {
   }
 }
		ProjectManager(Activator activator, IProject project) {
			this.activator = activator;
			this.Project = project;
			this.Properties = new ProjectProperties();
			
			var propertiesFile = project.getFile(".stabproperties");
			if (!this.Properties.load(propertiesFile)) {
				try {
					var libsFolder = project.getFolder("libs");
					if (!libsFolder.exists()) {
						libsFolder.create(true, true, null);
					}
					var runtimeLib = Environment.getLibraryPath("stabrt.jar");
					using (var stream = new FileInputStream(runtimeLib)) {
						var stabrtFile = libsFolder.getFile("stabrt.jar");
						if (stabrtFile.exists()) {
							stabrtFile.setContents(stream, IResource.FORCE, null);
						} else {
							stabrtFile.create(stream, true, null);
						}
						this.Properties.Libraries = Query.singleton(new ProjectLibrary(stabrtFile.getProjectRelativePath().toPortableString()));
						this.Properties.OutputPath = "bin";
					}
				} catch (Exception e) {
					Environment.logException(e);
				}
				this.Properties.save(propertiesFile);
			}
		}
Beispiel #3
0
 private static void AddEntries(java.util.zip.ZipFile file, string rootDirectory, string[] newFiles, bool flattenHierarchy)
 {
     string destFileName = file.getName();
     string tempFileName = Path.GetTempFileName();
     ZipOutputStream destination = new ZipOutputStream(new FileOutputStream(tempFileName));
     try
     {
         CopyEntries(file, destination);
         if (newFiles != null)
         {
             foreach (string str3 in newFiles)
             {
                 string directoryName;
                 if (flattenHierarchy)
                 {
                     directoryName = Path.GetDirectoryName(str3);
                 }
                 else if (rootDirectory == null)
                 {
                     directoryName = Path.GetPathRoot(str3);
                 }
                 else
                 {
                     directoryName = rootDirectory;
                 }
                 directoryName = directoryName + @"\";
                 ZipEntry ze = new ZipEntry(str3.Remove(0, directoryName.Length));
                 ze.setMethod(8);
                 destination.putNextEntry(ze);
                 try
                 {
                     FileInputStream source = new FileInputStream(str3);
                     try
                     {
                         CopyStream(source, destination);
                     }
                     finally
                     {
                         source.close();
                     }
                 }
                 finally
                 {
                     destination.closeEntry();
                 }
             }
         }
     }
     finally
     {
         destination.close();
     }
     file.close();
     System.IO.File.Copy(tempFileName, destFileName, true);
     System.IO.File.Delete(tempFileName);
 }
 public static byte[] getBytesFromFileJava(string filePath)
 {
     FileInputStream fis = new FileInputStream (new java.io.File (filePath));
     BufferedInputStream bis = new BufferedInputStream(fis);
     int numByte = bis.available();
     byte[] buff = new byte[numByte];
     bis.read(buff, 0, numByte);
     bis.close ();
     fis.close ();
     return buff;
 }
        //Compares both audio files
        private static float compareAudio(String recordWAV, String refWAV)
        {
            InputStream fileA = new FileInputStream(recordWAV);
            InputStream fileB = new FileInputStream(refWAV);

            Wave wavFile1 = new Wave(fileA);
            Wave wavFile2 = new Wave(fileB);

            Byte[] sus = wavFile1.getFingerprint();
            Byte[] samp = wavFile2.getFingerprint();

            FingerprintSimilarityComputer fpc = new FingerprintSimilarityComputer(samp, sus);
            FingerprintSimilarity sim = fpc.getFingerprintsSimilarity();

            return (float)(sim.getScore() * 100.0f);
        }
Beispiel #6
0
        public void TestTikaAutodetect()
        {
            Tika tika = new Tika();
            File xpsFile = new File("samples\\test1.xps");
		    if (!xpsFile.isFile())
			    throw new Exception(xpsFile.getName() + " does not exists.");

            using (InputStream inputStream = new FileInputStream(xpsFile))
            {
                Metadata metadata = new Metadata();

                string mimeType = tika.detect(inputStream, metadata);
                Assert.AreEqual("application/x-tika-ooxml", mimeType);

                inputStream.close();
            }
        }
Beispiel #7
0
 public TextExtractionResult Extract(string filePath)
 {
     try
     {
         var inputStream = new FileInputStream(filePath);
         return Extract(metadata =>
         {
             var result = TikaInputStream.get(inputStream);
             metadata.add("FilePath", filePath);
             return result;
         });
     }
     catch (Exception ex)
     {
         throw new TextExtractionException("Extraction of text from the file '{0}' failed.".ToFormat(filePath), ex);
     }
 }
        //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;
        }
Beispiel #9
0
        private static string GetContent(string fileName)
        {
            using (InputStream stream = new FileInputStream(new File(fileName)))
            {
                AutoDetectParser parser = new AutoDetectParser();
                BodyContentHandler handler = new BodyContentHandler();
                Metadata metadata = new Metadata();

                var xpsParser = new XpsParser();

                parser.setParsers(new java.util.HashMap { { MediaType.application("vnd.ms-xpsdocument"), xpsParser } });
                parser.setParsers(new java.util.HashMap { { MediaType.application("x-tika-ooxml"), xpsParser } });

                parser.parse(stream, handler, metadata);

                return handler.toString();
            }
        }
        public string Parse(string fileName)
        {
            //Load in file. Using java.io because pdfbox is ported from java.
            var pdfFile = new FileInputStream(fileName);

            //Load file into the pdf parser
            var pdfParser = new PDFParser(pdfFile);

            //Parse the document, so that we can get it for the COSDocument
            pdfParser.parse();

            /*
            COSDocument is the in-memory representation of the PDF.
            see https://pdfbox.apache.org/docs/1.8.4/javadocs/org/apache/pdfbox/cos/COSDocument.html
            */
            var cosDocument = pdfParser.getDocument();

            var pdDocument = new PDDocument(cosDocument);

            //Instantiate text stripper.
            var pdfTextStripper = new PDFTextStripper();

            /* Needed for only stripping specific pages

            pdfTextStripper.setStartPage(0);
            pdfTextStripper.setEndPage(pdDocument.getNumberOfPages());

            */

            //Needed so that we can close the pdDocument before returning from this method
            var strippedText = pdfTextStripper.getText(pdDocument);

            //This closes all storage and delete the tmp files.
            pdDocument.close();
            cosDocument.close();

            return strippedText;
        }
Beispiel #11
0
    protected override void ThreadFunction()
    {
        //TestProblem p = new TestProblem ();
        //Type t = typeof(TestProblem);
        //Debug.Log (t.AssemblyQualifiedName);
        try
        {
            Debug.Log("ECJ job started");
            FileInputStream input = new FileInputStream(new File("erc.params"));
            state = Evolve.initialize(new ParameterDatabase(
            input), 0);
            state.setup(state, null);

            // Make sure problem has the model in so when it gets cloned it can be used.
            ((UnityProblem)state.evaluator.p_problem).model = unityModel;

            state.run(EvolutionState.C_STARTED_FRESH);
            Debug.Log("ECJ job finished. " + state);
        } catch (Exception e)
        {
            Debug.Log ("ERROR in ecjJob: " + e.ToString ());
            throw e;
        }
    }
Beispiel #12
0
 private bool Method2(int arg)
 {
     if (arg == 0)
     {
         int count = 10;
     }
     FileInputStream stream = new FileInputStream("Test");
     int count_Renamed1 = Float.floatToIntBits(10f);
     byte[] buffer = new byte[count_Renamed1];
     stream.read(buffer);
     java.lang.reflect.Field f = null;
     return Modifier.isTransient(f.getModifiers());
 }
 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);
     }
 }
 private static SentenceDetectorME PrepareSentenceDetector()
 {
     var sentModelStream = new FileInputStream(SentenceModelPath); //load the sentence model into a stream
     var sentModel = new SentenceModel(sentModelStream); // load the model
     return new SentenceDetectorME(sentModel); //create sentence detector
 }
 private static TokenizerME PrepareTokenizer()
 {
     var tokenInputStream = new FileInputStream(TokenModelPath); //load the token model into a stream
     var tokenModel = new TokenizerModel(tokenInputStream); //load the token model
     return new TokenizerME(tokenModel); //create the tokenizer
 }
 private SentenceDetectorME PrepareSentenceDetector()
 {
     //TODO[danielcamargo]: we need to find/train the model in spanish
     var sentModelStream =
         new FileInputStream(string.Format(@"Models\{0}-sent.bin", _language == "es" ? "pt" : _language));
     var sentModel = new SentenceModel(sentModelStream);
     sentModelStream.close();
     return new SentenceDetectorME(sentModel);
 }
Beispiel #17
0
 public Chunk loadChunk(World world, int i, int j)
 {
     File file = chunkFileForXZ(i, j);
     if (file != null && file.exists())
     {
         try
         {
             var fileinputstream = new FileInputStream(file);
             NBTTagCompound nbttagcompound = CompressedStreamTools.func_770_a(fileinputstream);
             if (!nbttagcompound.hasKey("Level"))
             {
                 [email protected](
                     (new StringBuilder()).append("Chunk file at ").append(i).append(",").append(j).append(
                         " is missing level data, skipping").toString());
                 return null;
             }
             if (!nbttagcompound.getCompoundTag("Level").hasKey("Blocks"))
             {
                 [email protected](
                     (new StringBuilder()).append("Chunk file at ").append(i).append(",").append(j).append(
                         " is missing block data, skipping").toString());
                 return null;
             }
             Chunk chunk = loadChunkIntoWorldFromCompound(world, nbttagcompound.getCompoundTag("Level"));
             if (!chunk.isAtLocation(i, j))
             {
                 [email protected](
                     (new StringBuilder()).append("Chunk file at ").append(i).append(",").append(j).append(
                         " is in the wrong location; relocating. (Expected ").append(i).append(", ").append(j).
                         append(", got ").append(chunk.xPosition).append(", ").append(chunk.zPosition).append(")")
                         .toString());
                 nbttagcompound.setInteger("xPos", i);
                 nbttagcompound.setInteger("zPos", j);
                 chunk = loadChunkIntoWorldFromCompound(world, nbttagcompound.getCompoundTag("Level"));
             }
             return chunk;
         }
         catch (Exception exception)
         {
             exception.printStackTrace();
         }
     }
     return null;
 }
        //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;
        }
Beispiel #19
0
        public string grabPossiblePunSentences(string currentSentence)
        {
            try
            {
                java.io.InputStream modelIn = new java.io.FileInputStream(@"C:\en-token.bin");
                TokenizerModel model = new TokenizerModel(modelIn);

                Tokenizer tokenizer = new TokenizerME(model);

                string[] words = tokenizer.tokenize(currentSentence);
                List<string> possibleSentences = new List<string>();

                Homonyms homonyms = new Homonyms();

                for (int i = 0; i < words.Length; i++)
                {
                    System.Console.WriteLine();
                    Homonym homonym = homonyms.findWordInList(words[i]);

                    if (homonym.homonyms == null)
                    {

                    }

                    else
                    {
                        string possibleSentence = "";
                        for (int r = 0; r < words.Length; r++)
                        {
                            if (words[i].Equals(words[r]))
                            {
                                Random random = new Random();
                                int randomNumber = random.Next(homonym.homonyms.Length);
                                possibleSentence += " " + homonym.homonyms[randomNumber];
                            }

                            else
                            {
                                possibleSentence += " " + words[r];
                            }
                        }
                        possibleSentences.Add(possibleSentence);
                    }
                }
                currentSentence = choosePossiblePunSentence(currentSentence, possibleSentences);
            }

            catch (Exception e)
            {

            }

            return currentSentence;
        }
Beispiel #20
0
        public void giveDefinitionAndHomonym(string currentSentence)
        {
            try
            {
                java.io.InputStream modelIn = new java.io.FileInputStream(@"C:\en-token.bin");
                TokenizerModel model = new TokenizerModel(modelIn);

                Tokenizer tokenizer = new TokenizerME(model);

                string[] words = tokenizer.tokenize(currentSentence);

                Homonyms homonyms = new Homonyms();

                for (int i = 0; i < words.Length; i++)
                {
                    System.Console.WriteLine();
                    Homonym homonym = homonyms.findWordInList(words[i]);

                    if (homonym.homonyms == null)
                    {
                        System.Console.WriteLine("No homonyms found for: " + words[i]);
                    }

                    else
                    {
                        List<string> selectedHomonyms = homonym.selectedHomonyms();

                        System.Console.WriteLine("Homonyms are: " + words[i]);
                        foreach (string selectedWord in selectedHomonyms)
                        {
                            System.Console.Write(selectedWord + ",");
                        }
                    }

                    System.Console.WriteLine();
                    System.Console.WriteLine("Definition for: " + words[i]);
                    using (WebClient client = new WebClient())
                    {
                        string line = client.DownloadString("http://api.wordnik.com/v4/word.json/" + words[i] + "/definitions?limit=200&includeRelated=true&useCanonical=false&includeTags=false&api_key=a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5");
                        if (!line.Equals("[]"))
                        {
                            string[] lines1 = System.Text.RegularExpressions.Regex.Split(line, "\"text\":\"");
                            string[] lines2 = System.Text.RegularExpressions.Regex.Split(lines1[1], "\",\"sequence\"[\\W\\w]+");
                            System.Console.WriteLine(lines2[0]);
                        }
                        else
                        {
                            System.Console.WriteLine("Definition cannot be found, word is mispelled or doesn't exist within our current data");
                        }
                    }

                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
            }
        }
Beispiel #21
0
        public String chooseSentenceMenu()
        {
            int userInputNumber = 0;
            string userChoosenSentence = "";
            System.Console.WriteLine("Choose a sentence to use from your current text");
            System.Console.WriteLine("Must be a space between each sentence");
            try
            {
                java.io.File file = new java.io.File("C:\\en-sent.bin");
                java.io.InputStream modelIn = new FileInputStream("C:\\Users\\jcoleman\\Documents\\Capstone\\jcoleman_Capstone\\Code\\NEWCHATBOT\\ConsoleBot\\ConsoleBot\\en-sent.bin");
                SentenceModel model = new SentenceModel(modelIn);
                SentenceDetectorME sentenceDetector = new SentenceDetectorME(model);

                string text = "";
                FileText = System.IO.File.ReadAllLines(FilePath);

                for (int i = 0; i < FileText.Length; i++)
                {
                    text += FileText[i];
                }

                string[] sentences = sentenceDetector.sentDetect(text);

                for(int s = 0;s < sentences.Length;s++)
                {
                    System.Console.WriteLine((s+1) +" : " +sentences[s]);
                }

                string userInput = System.Console.ReadLine();
                userInputNumber = int.Parse(userInput);

                userChoosenSentence = sentences[userInputNumber - 1];
                modelIn.close();
            }
            catch(Exception e)
            {
                System.Console.WriteLine(e.Message);
            }

            return userChoosenSentence;
        }
Beispiel #22
0
        public localKeyManager(
            string keystorepath
            )
        {
            Console.WriteLine("enter localKeyManager");


            try
            {
                var xFileInputStream = default(FileInputStream);


                var xKeyStore = default(KeyStore);
                // certmgr.msc
                var xKeyStoreDefaultType = "Windows-MY";
                var xKeyStorePassword = default(char[]);

                //try
                //{
                //    Console.WriteLine(new { xKeyStoreDefaultType });
                //    xKeyStore = KeyStore.getInstance(xKeyStoreDefaultType);
                //}
                //catch
                {
                    xKeyStoreDefaultType = java.security.KeyStore.getDefaultType();
                    // http://www.coderanch.com/t/377172/java/java/cacerts-JAVA-HOME-jre-lib
                    // /usr/lib/jvm/default-java/jre/lib/security/cacerts

                    Console.WriteLine(new { xKeyStoreDefaultType });
                    xKeyStore = KeyStore.getInstance(xKeyStoreDefaultType);

                    var fa = new FileInfo(typeof(Program).Assembly.Location);

                    try
                    {
                        xFileInputStream = new FileInputStream(keystorepath);
                        xKeyStorePassword = "".PadLeft(6, '0').ToCharArray();
                    }
                    catch
                    {
                        throw;
                    }
                }

                Console.WriteLine("localKeyManager " + new { xKeyStore });

                xKeyStore.load(xFileInputStream, xKeyStorePassword);


                java.util.Enumeration en = xKeyStore.aliases();
                //Console.WriteLine("aliases... done");

                while (en.hasMoreElements())
                {
                    alias = (string)en.nextElement();
                }

                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");

                Console.WriteLine("localKeyManager " + new { kmf, alias });


                kmf.init(xKeyStore, xKeyStorePassword);

                KeyManagers = kmf.getKeyManagers();

                Console.WriteLine("localKeyManager " + new { KeyManagers.Length });


                //{ xKeyStoreDefaultType = Windows-MY }
                //WindowsMYKeyManagers { xKeyStore = java.security.KeyStore@ac4d3b }
                //WindowsMYKeyManagers { kmf = javax.net.ssl.KeyManagerFactory@1c7d56b }
                //WindowsMYKeyManagers { KeyManagers = [Ljavax.net.ssl.KeyManager;@f77511 }

                // http://docs.oracle.com/javase/7/docs/api/javax/net/ssl/KeyManager.html
                // http://stackoverflow.com/questions/5292074/how-to-specify-outbound-certificate-alias-for-https-calls
                // http://www.angelfire.com/or/abhilash/site/articles/jsse-km/customKeyManager.html

                foreach (var KeyManager in KeyManagers)
                {
                    var xX509KeyManager = KeyManager as X509KeyManager;
                    if (xX509KeyManager != null)
                    {
                        Console.WriteLine("localKeyManager " + new { xX509KeyManager });

                        InternalX509KeyManager = xX509KeyManager;
                    }
                }



                // http://stackoverflow.com/questions/15076820/java-sslhandshakeexception-no-cipher-suites-in-common
                // http://stackoverflow.com/questions/7535154/chrome-closing-connection-on-handshake-with-java-ssl-server
            }
            catch
            {
                throw;

            }
        }
        public int run(String[] arguments) {
            sourceFiles.clear();
            if (!handleArguments(arguments)) {
                return 1;
            }
            
            var t0 = System.nanoTime();
            
			try {
				var results = new Compiler().compileFromFiles(parameters, sourceFiles.toArray(new File[sourceFiles.size()]));
				var hasErrors = false;
				foreach (var error in results.Errors) {
					var filename = error.Filename;
					if (filename != null) {
						System.out.print(new File(error.Filename).getAbsolutePath());
					} else {
						System.out.print("Unknown source");
					}
					if (error.Line > 0) {
						System.out.print(" (");
						System.out.print(error.Line);
						if (error.Column > 0) {
							System.out.print(", ");
							System.out.print(error.Column);
						}
						System.out.print(")");
					}
					if (error.Level == 0) {
						hasErrors = true;
						System.out.print(" error ");
					} else {
						System.out.print(" warning ");
					}
					System.out.print(error.Id);
					System.out.print(": ");
					System.out.println(error.Message);
				}
				if (!hasErrors) {
					var outputFile = new File(outputPath);
					if (outputFile.isDirectory() || outputPath.endsWith("\\") || outputPath.endsWith("/")) {
						foreach (var e in results.ClassFiles.entrySet()) {
							var file = new File(outputFile, e.Key.replace('.', '/') + ".class");
							var dir = file.getParentFile();
							if (!dir.exists()) {
								dir.mkdirs();
							}
							using (var s = new FileOutputStream(file)) {
								s.write(e.Value);
							}
						}
					} else {
						var destination = outputPath;
						if (PathHelper.getExtension(destination).length() == 0) {
							destination += ".jar";
						}
						using (var zipStream = new ZipOutputStream(new FileOutputStream(destination))) {
							if (manifestPath != null) {
								var zipEntry = new ZipEntry("META-INF/MANIFEST.MF");
								zipStream.putNextEntry(zipEntry);
								var buffer = new byte[4096];
								var inputStream = new FileInputStream(manifestPath);
								int read;
								while ((read = inputStream.read(buffer)) != -1) {
									zipStream.write(buffer, 0, read);
								}
								inputStream.close();
							}
							if (resourcesPath != null) {
								var rootDir = new File(resourcesPath);
								foreach (var content in rootDir.list()) {
									var file = new File(rootDir, content);
									if (file.isDirectory()) {
										exploreDirectory(zipStream, "", file);
									} else {
										addEntry(zipStream, "", file);
									}
								}
							}
							foreach (var e in results.ClassFiles.entrySet()) {
								var zipEntry = new ZipEntry(e.Key.replace('.', '/') + ".class");
								zipStream.putNextEntry(zipEntry);
								zipStream.write(e.Value);
							}
						}
					}
					System.out.println();
					System.out.println(String.format("%d class(es) successfully generated in %.2fs",
						results.classFiles.size(), (System.nanoTime() - t0) / 1e9));
					return 0;
				} else {
					System.out.println();
					System.out.println("Compilation failed");
					return 1;
				}
			} catch (TypeLoadException e) {
				System.out.println("Cannot find type " + e.TypeName + ". The class is missing from the classpath.");
				System.out.println("Compilation failed");
				return 1;
			}
        }
        private POSTaggerME PreparePosTagger()
        {
            var model = string.Format(@"Models\{0}-pos-maxent.bin", _language);

            var posModelStream = new FileInputStream(model);
            var posModel = new POSModel(posModelStream);
            posModelStream.close();
            return new POSTaggerME(posModel);
        }
Beispiel #25
0
        public static void Main(string[] args)
        {
            // https://javacruft.wordpress.com/2014/06/18/168k-instances/
            // http://www.ubuntu.com/cloud

            //File.WriteAllText(f, w.ToString());

            try
            {
                // https://lists.ubuntu.com/archives/upstart-devel/2014-August/003360.html

                Console.WriteLine("ready!");

                // http://stackoverflow.com/questions/11203483/run-a-java-application-as-a-service-on-linux

                // http://askubuntu.com/questions/99232/how-to-make-a-jar-file-run-on-startup-and-when-you-log-out

                // "X:\torrent\ubuntu-14.04.3-server-amd64.iso"
                // http://standards.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html
                // http://www.markhneedham.com/blog/2012/09/29/upstart-job-getting-stuck-in-the-startkilled-state/

                System.Console.WriteLine("hello ubuntu!! " + new
                {
                    //typeof(object).AssemblyQualifiedName,

                    // rt location.
                    //typeof(object).Assembly.Location,
                    typeof(Program).Assembly.Location,

                    // /home/xuser
                    //Environment.CurrentDirectory
                }
                );


                //Implementation not found for type import :
                //type: System.Environment
                //method: Void set_CurrentDirectory(System.String)

                //Environment.CurrentDirectory =;

                var fa = new FileInfo(typeof(Program).Assembly.Location);
                var keystorepath = fa.Directory.FullName + "/domain.keystore";

                //var fadir = new DirectoryInfo(Path.GetDirectoryName(fa.FullName));



                Console.WriteLine(new { fa.Directory });


                #region truststore/keystore
                {
                    var xKeyStoreDefaultType = java.security.KeyStore.getDefaultType();
                    //xKeyStoreDefaultType = "/usr/lib/jvm/default-java/jre/lib/security/cacerts";
                    //xKeyStoreDefaultType = "cacerts.jks";

                    Console.WriteLine("... " + new { xKeyStoreDefaultType });


                    // You can't do it with the system properties. You would have to write and load your own X509KeyManager and create your own SSLContext with it.
                    // https://docs.oracle.com/cd/E19830-01/819-4712/ablqw/index.html

                    var keyStore = java.lang.System.getProperty("javax.net.ssl.keyStore");
                    Console.WriteLine(new { keyStore });
                    var trustStore = java.lang.System.getProperty("javax.net.ssl.trustStore");
                    Console.WriteLine(new { trustStore });

                    // are we running in GUI or TTY?
                    // can we enumerate keystores?

                    // ... { xKeyStoreDefaultType = jks }


                    Action<string, Func<InputStream>> f = (keyStoreType, loadstream) =>
                    {
                        // jsc should do implicit try catch for closures? while asking for explicit catch for non closures?

                        //{ ks = java.security.KeyStore@d3ade7 }
                        //{ aliasKey = peer integrity authority for cpu BFEBFBFF000306A9, SerialNumber = 03729f49acf3e79d4cc40da08149433d, SimpleName = peer integrity authority for cpu BFEBFBFF000306A9 }
                        //{ aliasKey = peer integrity authority for cpu BFEBFBFF000306C3, SerialNumber = c4761e1ea779bc9546151afce47c7c26, SimpleName = peer integrity authority for cpu BFEBFBFF000306C3 }

                        try
                        {
                            // http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/sun/security/mscapi/SunMSCAPI.java

                            // https://docs.oracle.com/javase/7/docs/technotes/guides/security/SunProviders.html

                            // https://social.msdn.microsoft.com/Forums/expression/en-US/52dca221-1e05-44c1-8c45-9e0d4a807853/java-keystoreload-for-windowsmy-pops-up-insert-smart-card-window?forum=windowssecurity
                            // I removed some personal certificaties at key manager (certmgr.msc) and wala!

                            //Client Authentication (1.3.6.1.5.5.7.3.2)
                            //Secure Email (1.3.6.1.5.5.7.3.4)


                            // https://www.chilkatsoft.com/p/p_280.asp
                            // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\Defaults\Provider\Microsoft Base Smart Card Crypto Provider

                            // http://stackoverflow.com/questions/27692904/how-to-avoid-smart-card-selection-popup-when-accessing-windows-my-using-java

                            // http://stackoverflow.com/questions/4552100/how-to-prevent-popups-when-loading-a-keystore
                            // http://stackoverflow.com/questions/15220976/how-to-obtain-a-users-identity-from-a-smartcard-on-windows-mscapi-with-java

                            KeyStore xKeyStore = KeyStore.getInstance(keyStoreType);
                            Console.WriteLine(new { xKeyStore });
                            Console.WriteLine("load... " + new { keyStoreType });
                            xKeyStore.load(loadstream(), null);
                            //Console.WriteLine("load... done");
                            Console.WriteLine("aliases...");
                            java.util.Enumeration en = xKeyStore.aliases();
                            //Console.WriteLine("aliases... done");

                            while (en.hasMoreElements())
                            {
                                var aliasKey = (string)en.nextElement();

                                Console.WriteLine(new { aliasKey });

                                // PCSC?hhhhhhhhhhhh
                                var c509 = xKeyStore.getCertificate(aliasKey) as java.security.cert.X509Certificate;
                                if (c509 != null)
                                {
                                    X509Certificate2 crt = new __X509Certificate2 { InternalElement = c509 };

                                    //Console.WriteLine(new { crt.Subject, crt.SerialNumber, SimpleName = crt.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, false) });
                                    Console.WriteLine(new { aliasKey, crt.SerialNumber, SimpleName = crt.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, false), crt.Issuer });

                                }
                                //if (aliasKey.equals("myKey") ) {
                                //      PrivateKey key = (PrivateKey)ks.getKey(aliasKey, "monPassword".toCharArray());
                                //      Certificate[] chain = ks.getCertificateChain(aliasKey);
                                //}
                            }

                        }
                        catch //(Exception closure)
                        {
                            throw;
                        }
                    };

                    //hello ubuntu! { AssemblyQualifiedName = java.lang.Object, rt }
                    //... { xKeyStoreDefaultType = jks }
                    //{ xKeyStore = java.security.KeyStore@9980d5 }
                    //load... { keyStoreType = jks }
                    //aliases...
                    //done


                    // on RED there are no entries?
                    // what about ubuntu?
                    f(xKeyStoreDefaultType, () =>
                        {
                            var xx = default(FileInputStream);

                            try
                            {
                                xx = new FileInputStream(keystorepath);
                            }
                            catch { throw; }
                            return xx;
                        }
                        );
                }
                #endregion

                var w = new StringBuilder { };

                w.AppendLine(new { DateTime.Now }.ToString());


                // https://bugs.launchpad.net/ubuntu/+source/systemd/+bug/1387241
                // https://www.digitalocean.com/community/tutorials/how-to-use-systemctl-to-manage-systemd-services-and-units
                // http://unix.stackexchange.com/questions/196166/how-to-find-out-if-a-system-uses-sysv-upstart-or-systemd-initsystem
                // https://lists.ubuntu.com/archives/upstart-devel/2011-January/001370.html
                // http://askubuntu.com/questions/62790/upstart-service-never-starts-or-stops-completely
                // http://askubuntu.com/questions/19320/how-to-enable-or-disable-services
                // http://serverfault.com/questions/251982/ubuntu-upstart-script-hangs-on-start-and-stop



                //var servicesdir = new DirectoryInfo("/lib/systemd/system/");

                // https://www.centos.org/forums/viewtopic.php?t=4300
                // http://upstart.ubuntu.com/getting-started.html

                // initctl reload-configuration 
                // https://www.centos.org/forums/viewtopic.php?t=4300
                // initctl show-config
                // http://unix.stackexchange.com/questions/84252/how-to-start-a-service-automatically-when-ubuntu-starts
                // https://serversforhackers.com/video/process-monitoring-with-upstart
                // http://upstart.ubuntu.com/cookbook/

                // http://www.yyosifov.com/2014/04/upstart-syntax-error-bad-fd-number.html
                // /var/log/upstart/ubuntubootexperiment.log

                // http://serverfault.com/questions/453136/understanding-upstart-script-stanza
                // https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=582745
                // http://askubuntu.com/questions/162768/starting-java-processes-with-upstart

                // https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=582745
                // ps aux
                // http://askubuntu.com/questions/397502/reboot-a-server-from-command-line

                var servicesdir = new DirectoryInfo("/etc/init/");
                w.AppendLine(new { servicesdir }.ToString());


                foreach (var service in servicesdir.GetFiles())
                {
                    w.AppendLine(
                        new { service.FullName }.ToString()
                    );

                }


                var ff = fa.Directory.FullName + "/hello.txt";

                Console.WriteLine(new { ff });
                //File.WriteAllText(fadir + "/hello.txt", "hi");

                System.IO.File.WriteAllText(ff, w.ToString());


                // are we running in GUI or TTY?
                // can we enumerate keystores?

                //var sw = Stopwatch.StartNew();

                //while (sw.ElapsedMilliseconds < 20000)
                //{
                //    Console.WriteLine(new { sw.ElapsedMilliseconds });
                //    Thread.Sleep(500);
                //}

                Console.WriteLine("boot into tcp server...");

                // haha. jsc cannot use a release build version of the ref
                // nor can it call the Main again.

                // why cant main call main?
                // cuz the type name is the same?
                JVMCLRTCPServerAsync.Program2.Main2(args);


                //Thread.Sleep(30000);

                // tail -f .log
            }
            catch (Exception err)
            {

                Console.WriteLine(new { err.Message, err.StackTrace });

                Console.ReadLine();
            }


            // CLR not available? unless there was mono?
            //CLRProgram.CLRMain();
        }
 public void setUpParser()
 {
     string modelPath = "C:\\Users\\jcoleman\\Documents\\Capstone\\jcoleman_Capstone\\Code\\NEWCHATBOT\\ConsoleBot\\ConsoleBot\\en-parser-chunking.bin";
     java.io.FileInputStream modelInpstream = new java.io.FileInputStream(modelPath);
     parserModel = new ParserModel(modelInpstream);
     parser = ParserFactory.create(parserModel);
     parse = ParserTool.parseLine(sentence, parser, 1);
 }
 private NameFinderME PrepareNameFinder()
 {
     var modelInputStream = new FileInputStream(_nameFinderModelPath);
     var model = new TokenNameFinderModel(modelInputStream);
     modelInputStream.close();
     return new NameFinderME(model);
 }
Beispiel #28
0
        //chooseServerAlias { keyType = EC_EC }
        //getClientAliases
        //chooseServerAlias { keyType = RSA }
        //getClientAliases
        //chooseServerAlias { keyType = RSA }
        //getClientAliases
        //chooseServerAlias { keyType = RSA }
        //getClientAliases
        //chooseServerAlias { keyType = RSA }
        //getClientAliases


        public static KeyManager[] WindowsMYKeyManagers()
        {
            Console.WriteLine("enter WindowsMYKeyManagers");
            var KeyManagers = new KeyManager[0];


            try
            {
                var xFileInputStream = default(FileInputStream);


                var xKeyStore = default(KeyStore);
                // certmgr.msc
                var xKeyStoreDefaultType = "Windows-MY";

                try
                {
                    Console.WriteLine(new { xKeyStoreDefaultType });
                    xKeyStore = KeyStore.getInstance(xKeyStoreDefaultType);
                }
                catch
                {
                    xKeyStoreDefaultType = java.security.KeyStore.getDefaultType();
                    // http://www.coderanch.com/t/377172/java/java/cacerts-JAVA-HOME-jre-lib
                    // /usr/lib/jvm/default-java/jre/lib/security/cacerts

                    Console.WriteLine(new { xKeyStoreDefaultType });
                    xKeyStore = KeyStore.getInstance(xKeyStoreDefaultType);

                    var fa = new FileInfo(typeof(Program).Assembly.Location);
                    var keystorepath = fa.Directory.FullName + "/domain.keystore";

                    try
                    {
                        xFileInputStream = new FileInputStream(keystorepath);
                    }
                    catch { throw; }
                }

                Console.WriteLine("WindowsMYKeyManagers " + new { xKeyStore });

                xKeyStore.load(xFileInputStream, null);

                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");

                Console.WriteLine("WindowsMYKeyManagers " + new { kmf });


                kmf.init(xKeyStore, null);

                KeyManagers = kmf.getKeyManagers();

                Console.WriteLine("WindowsMYKeyManagers " + new { KeyManagers.Length });


                //{ xKeyStoreDefaultType = Windows-MY }
                //WindowsMYKeyManagers { xKeyStore = java.security.KeyStore@ac4d3b }
                //WindowsMYKeyManagers { kmf = javax.net.ssl.KeyManagerFactory@1c7d56b }
                //WindowsMYKeyManagers { KeyManagers = [Ljavax.net.ssl.KeyManager;@f77511 }

                // http://docs.oracle.com/javase/7/docs/api/javax/net/ssl/KeyManager.html
                // http://stackoverflow.com/questions/5292074/how-to-specify-outbound-certificate-alias-for-https-calls
                // http://www.angelfire.com/or/abhilash/site/articles/jsse-km/customKeyManager.html

                foreach (var KeyManager in KeyManagers)
                {
                    var xX509KeyManager = KeyManager as X509KeyManager;
                    if (xX509KeyManager != null)
                    {
                        Console.WriteLine("WindowsMYKeyManagers " + new { xX509KeyManager });

                    }
                }

                //WindowsMYKeyManagers { Length = 1 }
                //WindowsMYKeyManagers { xX509KeyManager = sun.security.ssl.SunX509KeyManagerImpl@ea3932 }


                //KeyStore ks = KeyStore.getInstance("JKS");
                //// initialize KeyStore object using keystore name
                //ks.load(new FileInputStream(keyFile), null);
                //kmf.init(ks, keystorePasswd.toCharArray());
                //ret = kmf.getKeyManagers();

                // chooseServerAlias { keyType = RSA, StackTrace = <__StackTrace> }

                //java.security.KeyStore ks = null;

                //KeyManagerFactory kmf

                // http://stackoverflow.com/questions/15076820/java-sslhandshakeexception-no-cipher-suites-in-common
                // http://stackoverflow.com/questions/7535154/chrome-closing-connection-on-handshake-with-java-ssl-server
            }
            catch
            {
                throw;

            }

            return KeyManagers;
        }
 private TokenizerME PrepareTokenizer()
 {
     //TODO[danielcamargo]: we need to find/train the model in spanish
     var tokenInputStream =
         new FileInputStream(string.Format(@"Models\{0}-token.bin", _language == "es" ? "pt" : _language));
     var tokenModel = new TokenizerModel(tokenInputStream);
     tokenInputStream.close();
     return new TokenizerME(tokenModel);
 }
Beispiel #30
0
        private void SubsetFontFile(string subsetString, java.io.File paramFile1, java.io.File paramFile2)
        {
            FontFactory localFontFactory = FontFactory.getInstance();

            java.io.FileInputStream localFileInputStream = null;
            try
            {
                localFileInputStream = new java.io.FileInputStream(paramFile1);
                byte[] arrayOfByte = new byte[(int)paramFile1.length()];
                localFileInputStream.read(arrayOfByte);
                Font[] arrayOfFont = null;
                arrayOfFont = localFontFactory.loadFonts(arrayOfByte);
                Font localFont1 = arrayOfFont[0];
                java.util.ArrayList localArrayList = new java.util.ArrayList();
                localArrayList.add(CMapTable.CMapId.WINDOWS_BMP);
                //java.lang.Object localObject1 = null;
                java.lang.Object localObject2 = null;

                Font             localFont2 = localFont1;
                java.lang.Object localObject3;
                if (subsetString != null)
                {
                    localObject2 = new RenumberingSubsetter(localFont2, localFontFactory);
                    ((Subsetter)localObject2).setCMaps(localArrayList, 1);
                    localObject3 = (java.lang.Object)GlyphCoverage.getGlyphCoverage(localFont1, subsetString);
                    ((Subsetter)localObject2).setGlyphs((java.util.List)localObject3);
                    var localHashSet = new java.util.HashSet();
                    localHashSet.add(java.lang.Integer.valueOf(SfntlyTag.GDEF));
                    localHashSet.add(java.lang.Integer.valueOf(SfntlyTag.GPOS));
                    localHashSet.add(java.lang.Integer.valueOf(SfntlyTag.GSUB));
                    localHashSet.add(java.lang.Integer.valueOf(SfntlyTag.kern));
                    localHashSet.add(java.lang.Integer.valueOf(SfntlyTag.hdmx));
                    localHashSet.add(java.lang.Integer.valueOf(SfntlyTag.vmtx));
                    localHashSet.add(java.lang.Integer.valueOf(SfntlyTag.VDMX));
                    localHashSet.add(java.lang.Integer.valueOf(SfntlyTag.LTSH));
                    localHashSet.add(java.lang.Integer.valueOf(SfntlyTag.DSIG));
                    localHashSet.add(java.lang.Integer.valueOf(SfntlyTag.intValue(new byte[] { 109, 111, 114, 116 })));
                    localHashSet.add(java.lang.Integer.valueOf(SfntlyTag.intValue(new byte[] { 109, 111, 114, 120 })));
                    ((Subsetter)localObject2).setRemoveTables(localHashSet);
                    localFont2 = ((Subsetter)localObject2).subset().build();
                }
                if (this.strip)
                {
                    localObject2 = new HintStripper(localFont2, localFontFactory);
                    localObject3 = new HashSet();
                    ((Set)localObject3).add(Integer.valueOf(Tag.fpgm));
                    ((Set)localObject3).add(Integer.valueOf(Tag.prep));
                    ((Set)localObject3).add(Integer.valueOf(Tag.cvt));
                    ((Set)localObject3).add(Integer.valueOf(Tag.hdmx));
                    ((Set)localObject3).add(Integer.valueOf(Tag.VDMX));
                    ((Set)localObject3).add(Integer.valueOf(Tag.LTSH));
                    ((Set)localObject3).add(Integer.valueOf(Tag.DSIG));
                    ((Subsetter)localObject2).setRemoveTables((Set)localObject3);
                    localFont2 = ((Subsetter)localObject2).subset().build();
                }
                localObject2 = new java.io.FileOutputStream(paramFile2);
                if (this.woff)
                {
                    localObject3 = new WoffWriter().convert(localFont2);
                    ((WritableFontData)localObject3).copyTo((OutputStream)localObject2);
                }
                else if (this.eot)
                {
                    localObject3 = new EOTWriter(this.mtx).convert(localFont2);
                    ((WritableFontData)localObject3).copyTo((OutputStream)localObject2);
                }
                else
                {
                    localFontFactory.serializeFont(localFont2, (OutputStream)localObject2);
                }
            }
            catch (System.Exception ex)
            {
                throw new System.Exception(ex.Message);
            }
        }
Beispiel #31
0
 public CloseableAnonymousInnerClassHelper(FileInputStream outerInstance)
 {
     this.OuterInstance = outerInstance;
 }
 private NameFinderME PrepareNameFinder()
 {
     var modelInputStream = new FileInputStream(_nameFinderModelPath); //load the name model into a stream
     var model = new TokenNameFinderModel(modelInputStream); //load the model
     return new NameFinderME(model); //create the namefinder
 }