List of usage examples for java.io FileWriter FileWriter
public FileWriter(FileDescriptor fd)
From source file:com.sakadream.sql.SQLConfigJson.java
/** * Save SQLConfig to config.json/* ww w. j av a 2s . com*/ * @param sqlConfig SQLConfig object * @param encrypt Are you want to encrypt config.json? * @throws Exception */ public static void save(SQLConfig sqlConfig, Boolean encrypt) throws Exception { File file = new File(path); if (!file.exists()) { file.createNewFile(); } else { FileChannel outChan = new FileOutputStream(file, true).getChannel(); outChan.truncate(0); outChan.close(); } FileWriter writer = new FileWriter(file); String json = gson.toJson(sqlConfig, type); if (encrypt) { Security security = new Security(); writer.write(security.encrypt(json)); } else { writer.write(json); } writer.close(); }
From source file:eqtlmappingpipeline.util.ModuleEqtlNeutrophilReplication.java
/** * @param args the command line arguments *//* w w w . jav a 2 s . c o m*/ public static void main(String[] args) throws IOException, LdCalculatorException { System.out.println(HEADER); System.out.println(); System.out.flush(); //flush to make sure header is before errors try { Thread.sleep(25); //Allows flush to complete } catch (InterruptedException ex) { } CommandLineParser parser = new PosixParser(); final CommandLine commandLine; try { commandLine = parser.parse(OPTIONS, args, true); } catch (ParseException ex) { System.err.println("Invalid command line arguments: " + ex.getMessage()); System.err.println(); new HelpFormatter().printHelp(" ", OPTIONS); System.exit(1); return; } final String[] genotypesBasePaths = commandLine.getOptionValues("g"); final RandomAccessGenotypeDataReaderFormats genotypeDataType; final String replicationQtlFilePath = commandLine.getOptionValue("e"); final String interactionQtlFilePath = commandLine.getOptionValue("i"); final String outputFilePath = commandLine.getOptionValue("o"); final double ldCutoff = Double.parseDouble(commandLine.getOptionValue("ld")); final int window = Integer.parseInt(commandLine.getOptionValue("w")); System.out.println("Genotype: " + Arrays.toString(genotypesBasePaths)); System.out.println("Interaction file: " + interactionQtlFilePath); System.out.println("Replication file: " + replicationQtlFilePath); System.out.println("Output: " + outputFilePath); System.out.println("LD: " + ldCutoff); System.out.println("Window: " + window); try { if (commandLine.hasOption("G")) { genotypeDataType = RandomAccessGenotypeDataReaderFormats .valueOf(commandLine.getOptionValue("G").toUpperCase()); } else { if (genotypesBasePaths[0].endsWith(".vcf")) { System.err.println( "Only vcf.gz is supported. Please see manual on how to do create a vcf.gz file."); System.exit(1); return; } try { genotypeDataType = RandomAccessGenotypeDataReaderFormats .matchFormatToPath(genotypesBasePaths[0]); } catch (GenotypeDataException e) { System.err .println("Unable to determine input 1 type based on specified path. Please specify -G"); System.exit(1); return; } } } catch (IllegalArgumentException e) { System.err.println("Error parsing --genotypesFormat \"" + commandLine.getOptionValue("G") + "\" is not a valid input data format"); System.exit(1); return; } final RandomAccessGenotypeData genotypeData; try { genotypeData = genotypeDataType.createFilteredGenotypeData(genotypesBasePaths, 100, null, null, null, 0.8); } catch (TabixFileNotFoundException e) { LOGGER.fatal("Tabix file not found for input data at: " + e.getPath() + "\n" + "Please see README on how to create a tabix file"); System.exit(1); return; } catch (IOException e) { LOGGER.fatal("Error reading input data: " + e.getMessage(), e); System.exit(1); return; } catch (IncompatibleMultiPartGenotypeDataException e) { LOGGER.fatal("Error combining the impute genotype data files: " + e.getMessage(), e); System.exit(1); return; } catch (GenotypeDataException e) { LOGGER.fatal("Error reading input data: " + e.getMessage(), e); System.exit(1); return; } ChrPosTreeMap<ArrayList<ReplicationQtl>> replicationQtls = new ChrPosTreeMap<>(); CSVReader replicationQtlReader = new CSVReader(new FileReader(replicationQtlFilePath), '\t'); replicationQtlReader.readNext();//skip header String[] replicationLine; while ((replicationLine = replicationQtlReader.readNext()) != null) { try { GeneticVariant variant = genotypeData.getSnpVariantByPos(replicationLine[REPLICATION_SNP_CHR_COL], Integer.parseInt(replicationLine[REPLICATION_SNP_POS_COL])); if (variant == null) { continue; } ReplicationQtl replicationQtl = new ReplicationQtl(replicationLine[REPLICATION_SNP_CHR_COL], Integer.parseInt(replicationLine[REPLICATION_SNP_POS_COL]), replicationLine[REPLICATION_GENE_COL], Double.parseDouble(replicationLine[REPLICATION_BETA_COL]), variant.getAlternativeAlleles().get(0).getAlleleAsString()); ArrayList<ReplicationQtl> posReplicationQtls = replicationQtls.get(replicationQtl.getChr(), replicationQtl.getPos()); if (posReplicationQtls == null) { posReplicationQtls = new ArrayList<>(); replicationQtls.put(replicationQtl.getChr(), replicationQtl.getPos(), posReplicationQtls); } posReplicationQtls.add(replicationQtl); } catch (Exception e) { System.out.println(Arrays.toString(replicationLine)); throw e; } } int interactionSnpNotInGenotypeData = 0; int noReplicationQtlsInWindow = 0; int noReplicationQtlsInLd = 0; int multipleReplicationQtlsInLd = 0; int replicationTopSnpNotInGenotypeData = 0; final CSVWriter outputWriter = new CSVWriter(new FileWriter(new File(outputFilePath)), '\t', '\0'); final String[] outputLine = new String[14]; int c = 0; outputLine[c++] = "Chr"; outputLine[c++] = "Pos"; outputLine[c++] = "SNP"; outputLine[c++] = "Gene"; outputLine[c++] = "Module"; outputLine[c++] = "DiscoveryZ"; outputLine[c++] = "ReplicationZ"; outputLine[c++] = "DiscoveryZCorrected"; outputLine[c++] = "ReplicationZCorrected"; outputLine[c++] = "DiscoveryAlleleAssessed"; outputLine[c++] = "ReplicationAlleleAssessed"; outputLine[c++] = "bestLd"; outputLine[c++] = "bestLd_dist"; outputLine[c++] = "nextLd"; outputWriter.writeNext(outputLine); HashSet<String> notFound = new HashSet<>(); CSVReader interactionQtlReader = new CSVReader(new FileReader(interactionQtlFilePath), '\t'); interactionQtlReader.readNext();//skip header String[] interactionQtlLine; while ((interactionQtlLine = interactionQtlReader.readNext()) != null) { String snp = interactionQtlLine[1]; String chr = interactionQtlLine[2]; int pos = Integer.parseInt(interactionQtlLine[3]); String gene = interactionQtlLine[4]; String alleleAssessed = interactionQtlLine[9]; String module = interactionQtlLine[12]; double discoveryZ = Double.parseDouble(interactionQtlLine[10]); GeneticVariant interactionQtlVariant = genotypeData.getSnpVariantByPos(chr, pos); if (interactionQtlVariant == null) { System.err.println("Interaction QTL SNP not found in genotype data: " + chr + ":" + pos); ++interactionSnpNotInGenotypeData; continue; } ReplicationQtl bestMatch = null; double bestMatchR2 = Double.NaN; Ld bestMatchLd = null; double nextBestR2 = Double.NaN; ArrayList<ReplicationQtl> sameSnpQtls = replicationQtls.get(chr, pos); if (sameSnpQtls != null) { for (ReplicationQtl sameSnpQtl : sameSnpQtls) { if (sameSnpQtl.getGene().equals(gene)) { bestMatch = sameSnpQtl; bestMatchR2 = 1; } } } NavigableMap<Integer, ArrayList<ReplicationQtl>> potentionalReplicationQtls = replicationQtls .getChrRange(chr, pos - window, true, pos + window, true); for (ArrayList<ReplicationQtl> potentialReplicationQtls : potentionalReplicationQtls.values()) { for (ReplicationQtl potentialReplicationQtl : potentialReplicationQtls) { if (!potentialReplicationQtl.getGene().equals(gene)) { continue; } GeneticVariant potentialReplicationQtlVariant = genotypeData .getSnpVariantByPos(potentialReplicationQtl.getChr(), potentialReplicationQtl.getPos()); if (potentialReplicationQtlVariant == null) { notFound.add(potentialReplicationQtl.getChr() + ":" + potentialReplicationQtl.getPos()); ++replicationTopSnpNotInGenotypeData; continue; } Ld ld = interactionQtlVariant.calculateLd(potentialReplicationQtlVariant); double r2 = ld.getR2(); if (r2 > 1) { r2 = 1; } if (bestMatch == null) { bestMatch = potentialReplicationQtl; bestMatchR2 = r2; bestMatchLd = ld; } else if (r2 > bestMatchR2) { bestMatch = potentialReplicationQtl; nextBestR2 = bestMatchR2; bestMatchR2 = r2; bestMatchLd = ld; } } } double replicationZ = Double.NaN; double replicationZCorrected = Double.NaN; double discoveryZCorrected = Double.NaN; String replicationAlleleAssessed = null; if (bestMatch != null) { replicationZ = bestMatch.getBeta(); replicationAlleleAssessed = bestMatch.getAssessedAllele(); if (pos != bestMatch.getPos()) { String commonHap = null; double commonHapFreq = -1; for (Map.Entry<String, Double> hapFreq : bestMatchLd.getHaplotypesFreq().entrySet()) { double f = hapFreq.getValue(); if (f > commonHapFreq) { commonHapFreq = f; commonHap = hapFreq.getKey(); } } String[] commonHapAlleles = StringUtils.split(commonHap, '/'); discoveryZCorrected = commonHapAlleles[0].equals(alleleAssessed) ? discoveryZ : discoveryZ * -1; replicationZCorrected = commonHapAlleles[1].equals(replicationAlleleAssessed) ? replicationZ : replicationZ * -1; } else { discoveryZCorrected = discoveryZ; replicationZCorrected = alleleAssessed.equals(replicationAlleleAssessed) ? replicationZ : replicationZ * -1; } } c = 0; outputLine[c++] = chr; outputLine[c++] = String.valueOf(pos); outputLine[c++] = snp; outputLine[c++] = gene; outputLine[c++] = module; outputLine[c++] = String.valueOf(discoveryZ); outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(replicationZ); outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(discoveryZCorrected); outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(replicationZCorrected); outputLine[c++] = alleleAssessed; outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(bestMatch.getAssessedAllele()); outputLine[c++] = String.valueOf(bestMatchR2); outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(Math.abs(pos - bestMatch.getPos())); outputLine[c++] = String.valueOf(nextBestR2); outputWriter.writeNext(outputLine); } outputWriter.close(); for (String e : notFound) { System.err.println("Not found: " + e); } System.out.println("interactionSnpNotInGenotypeData: " + interactionSnpNotInGenotypeData); System.out.println("noReplicationQtlsInWindow: " + noReplicationQtlsInWindow); System.out.println("noReplicationQtlsInLd: " + noReplicationQtlsInLd); System.out.println("multipleReplicationQtlsInLd: " + multipleReplicationQtlsInLd); System.out.println("replicationTopSnpNotInGenotypeData: " + replicationTopSnpNotInGenotypeData); }
From source file:be.ac.ua.comp.scarletnebula.core.KeyManager.java
/** * Takes a keyname, an actual key and a provider name (for which this key * works) and then stores the key on disk. * /* ww w. j av a 2 s . c o m*/ * @param providerName * @param keyname * @param keystring */ static void addKey(final String providerName, final String keyname, final String keystring) { if (assureDirectory(providerName) == null) { return; } // Now store the key to file BufferedWriter out; try { out = new BufferedWriter(new FileWriter(getKeyFilename(providerName, keyname))); out.write(keystring); out.close(); } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.netscape.cmstools.CMCSharedToken.java
public static void main(String args[]) throws Exception { boolean isVerificationMode = false; // developer debugging only Options options = createOptions();//from ww w. j av a 2 s. c om CommandLine cmd = null; try { CommandLineParser parser = new PosixParser(); cmd = parser.parse(options, args); } catch (Exception e) { printError(e.getMessage()); System.exit(1); } if (cmd.hasOption("help")) { printHelp(); System.exit(0); } boolean verbose = cmd.hasOption("v"); String databaseDir = cmd.getOptionValue("d", "."); String passphrase = cmd.getOptionValue("s"); if (passphrase == null) { printError("Missing passphrase"); System.exit(1); } if (verbose) { System.out.println("passphrase String = " + passphrase); System.out.println("passphrase UTF-8 bytes = "); System.out.println(Arrays.toString(passphrase.getBytes("UTF-8"))); } String tokenName = cmd.getOptionValue("h"); String tokenPassword = cmd.getOptionValue("p"); String issuanceProtCertFilename = cmd.getOptionValue("b"); String issuanceProtCertNick = cmd.getOptionValue("n"); String output = cmd.getOptionValue("o"); try { CryptoManager.initialize(databaseDir); CryptoManager manager = CryptoManager.getInstance(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); tokenName = token.getName(); manager.setThreadToken(token); Password password = new Password(tokenPassword.toCharArray()); token.login(password); X509Certificate issuanceProtCert = null; if (issuanceProtCertFilename != null) { if (verbose) System.out.println("Loading issuance protection certificate"); String encoded = new String(Files.readAllBytes(Paths.get(issuanceProtCertFilename))); byte[] issuanceProtCertData = Cert.parseCertificate(encoded); issuanceProtCert = manager.importCACertPackage(issuanceProtCertData); if (verbose) System.out.println("issuance protection certificate imported"); } else { // must have issuance protection cert nickname if file not provided if (verbose) System.out.println("Getting cert by nickname: " + issuanceProtCertNick); if (issuanceProtCertNick == null) { System.out.println( "Invallid command: either nickname or PEM file must be provided for Issuance Protection Certificate"); System.exit(1); } issuanceProtCert = getCertificate(tokenName, issuanceProtCertNick); } EncryptionAlgorithm encryptAlgorithm = EncryptionAlgorithm.AES_128_CBC_PAD; KeyWrapAlgorithm wrapAlgorithm = KeyWrapAlgorithm.RSA; if (verbose) System.out.println("Generating session key"); SymmetricKey sessionKey = CryptoUtil.generateKey(token, KeyGenAlgorithm.AES, 128, null, true); if (verbose) System.out.println("Encrypting passphrase"); byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }; byte[] secret_data = CryptoUtil.encryptUsingSymmetricKey(token, sessionKey, passphrase.getBytes("UTF-8"), encryptAlgorithm, new IVParameterSpec(iv)); if (verbose) System.out.println("Wrapping session key with issuance protection cert"); byte[] issuanceProtWrappedSessionKey = CryptoUtil.wrapUsingPublicKey(token, issuanceProtCert.getPublicKey(), sessionKey, wrapAlgorithm); // final_data takes this format: // SEQUENCE { // encryptedSession OCTET STRING, // encryptedPrivate OCTET STRING // } DerOutputStream tmp = new DerOutputStream(); tmp.putOctetString(issuanceProtWrappedSessionKey); tmp.putOctetString(secret_data); DerOutputStream out = new DerOutputStream(); out.write(DerValue.tag_Sequence, tmp); byte[] final_data = out.toByteArray(); String final_data_b64 = Utils.base64encode(final_data, true); if (final_data_b64 != null) { System.out.println("\nEncrypted Secret Data:"); System.out.println(final_data_b64); } else System.out.println("Failed to produce final data"); if (output != null) { System.out.println("\nStoring Base64 secret data into " + output); try (FileWriter fout = new FileWriter(output)) { fout.write(final_data_b64); } } if (isVerificationMode) { // developer use only PrivateKey wrappingKey = null; if (issuanceProtCertNick != null) wrappingKey = (org.mozilla.jss.crypto.PrivateKey) getPrivateKey(tokenName, issuanceProtCertNick); else wrappingKey = CryptoManager.getInstance().findPrivKeyByCert(issuanceProtCert); System.out.println("\nVerification begins..."); byte[] wrapped_secret_data = Utils.base64decode(final_data_b64); DerValue wrapped_val = new DerValue(wrapped_secret_data); // val.tag == DerValue.tag_Sequence DerInputStream wrapped_in = wrapped_val.data; DerValue wrapped_dSession = wrapped_in.getDerValue(); byte wrapped_session[] = wrapped_dSession.getOctetString(); System.out.println("wrapped session key retrieved"); DerValue wrapped_dPassphrase = wrapped_in.getDerValue(); byte wrapped_passphrase[] = wrapped_dPassphrase.getOctetString(); System.out.println("wrapped passphrase retrieved"); SymmetricKey ver_session = CryptoUtil.unwrap(token, SymmetricKey.AES, 128, SymmetricKey.Usage.UNWRAP, wrappingKey, wrapped_session, wrapAlgorithm); byte[] ver_passphrase = CryptoUtil.decryptUsingSymmetricKey(token, new IVParameterSpec(iv), wrapped_passphrase, ver_session, encryptAlgorithm); String ver_spassphrase = new String(ver_passphrase, "UTF-8"); CryptoUtil.obscureBytes(ver_passphrase, "random"); System.out.println("ver_passphrase String = " + ver_spassphrase); System.out.println("ver_passphrase UTF-8 bytes = "); System.out.println(Arrays.toString(ver_spassphrase.getBytes("UTF-8"))); if (ver_spassphrase.equals(passphrase)) System.out.println("Verification success!"); else System.out.println("Verification failure! ver_spassphrase=" + ver_spassphrase); } } catch (Exception e) { if (verbose) e.printStackTrace(); printError(e.getMessage()); System.exit(1); } }
From source file:edu.asu.cse564.samples.crud.io.GradebookIO.java
public static void writeToGradebook(List<Gradebook> gradebookList, String filename) { //GradebookIO gbio = new GradebookIO(); try {//from w ww .j av a 2 s . co m //String path = gbio.getPath(filename); String path = filename; File file = new File(path); // if file doesnt exists, then create it if (!file.exists()) { LOG.info("Creating file as it does not exist"); file.createNewFile(); LOG.debug("Created file = {}", file.getAbsolutePath()); } String jsonString = null; jsonString = Converter.convertFromObjectToJSON(gradebookList, gradebookList.getClass()); LOG.info("File path = {}", file.getAbsolutePath()); FileWriter fw = new FileWriter(file.getAbsoluteFile()); try (BufferedWriter bw = new BufferedWriter(fw)) { bw.write(jsonString); } } catch (Exception e) { e.printStackTrace(); ; } }
From source file:JSONUtil.java
/** * @param out/*from w w w . ja v a2s . co m*/ * @param string * @throws IOException * @throws JSONException */ public static void saveJson(JSONObject out, String file) throws IOException, JSONException { File fo = new File(file); FileWriter fw = new FileWriter(fo); fw.append(out.toString(4)); fw.close(); }
From source file:cz.pichlik.goodsentiment.common.CSVWriter.java
public CSVWriter(String... header) { CSVFormat format = CSVFormats.format(header); try {// w w w . ja v a 2 s . c om this.temporaryResultFile = File.createTempFile("temp", "csv"); } catch (IOException e) { throw new RuntimeException("Cannot create a temp file for merging CSV files", e); } try { csvPrinter = new CSVPrinter(new FileWriter(this.temporaryResultFile), format); } catch (IOException e) { throw new RuntimeException("Cannot initialize the CSV printer", e); } }
From source file:com.testmax.util.FileUtility.java
public static void writeToFile(String path, String text) { try {/*from ww w . ja va2 s . c o m*/ // Create file FileWriter fstream = new FileWriter(path); BufferedWriter out = new BufferedWriter(fstream); out.write(text); //Close the output stream out.close(); } catch (Exception e) {//Catch exception if any System.err.println("Error: " + e.getMessage()); } }
From source file:com.dc.util.file.FileSupport.java
public static void writeTextFile(String folderPath, String fileName, String data, boolean isExecutable) throws IOException { File dir = new File(folderPath); if (!dir.exists()) { dir.mkdirs();/* w ww . j a v a 2 s.c o m*/ } File file = new File(dir, fileName); FileWriter fileWriter = null; BufferedWriter bufferedWriter = null; try { fileWriter = new FileWriter(file); bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(data); bufferedWriter.flush(); if (isExecutable) { file.setExecutable(true); } } finally { if (fileWriter != null) { fileWriter.close(); } if (bufferedWriter != null) { bufferedWriter.close(); } } }
From source file:Util.PacketGenerator.java
public static void GeneratePacket() { try {/*from ww w . jav a 2 s . c o m*/ File file = new File( "D:\\Mestrado\\Prototipo\\Trace\\Los Angeles\\equinix-sanjose.dirA.20120920-130000.UTC.anon.pcap.csv"); File newFile = new File("D:\\Mestrado\\SketchMatrix\\trunk\\Tracer_100_Pacotes.csv"); FileInputStream tracesFIS = new FileInputStream(file); DataInputStream tracesDIS = new DataInputStream(tracesFIS); BufferedReader tracesBR = new BufferedReader(new InputStreamReader(tracesDIS)); FileWriter tracesFW = new FileWriter(newFile); String tracesStr = tracesBR.readLine(); Random random = new Random(); long numberOfPackets = 0; while (tracesStr != null && numberOfPackets < 100) { String[] packetTokens = tracesStr.split(","); long time = Long.parseLong(packetTokens[0]); long srcIP = Long.parseLong(packetTokens[1]); long dstIP = Long.parseLong(packetTokens[2]); int srcPort = Integer.parseInt(packetTokens[3]); int dstPort = Integer.parseInt(packetTokens[4]); int payload = random.nextInt(256); tracesFW.write( time + "," + srcIP + "," + dstIP + "," + srcPort + "," + dstPort + "," + payload + "\n"); tracesStr = tracesBR.readLine(); numberOfPackets++; if ((numberOfPackets % 100000) == 0) { System.out.println(numberOfPackets / 1000 + "K Pacotes"); } } tracesBR.close(); tracesDIS.close(); tracesFIS.close(); tracesFW.close(); } catch (Exception ex) { ex.printStackTrace(); } }