public static void write() { File db = new File( TrueEconomy.getStatic().getDataFolder().toString() + File.separator + "ores" + File.separator + "diamond" + ".efd"); File db1 = new File(TrueEconomy.getStatic().getDataFolder().toString()); File db2 = new File(TrueEconomy.getStatic().getDataFolder().toString() + File.separator + "ores"); if (!db1.exists()) db1.mkdir(); if (!db2.exists()) db2.mkdir(); if (db.exists()) return; FileWriter fileWriter = null; BufferedWriter bufferWriter = null; try { fileWriter = new FileWriter(db); bufferWriter = new BufferedWriter(fileWriter); bufferWriter.append("a: 100000"); bufferWriter.newLine(); bufferWriter.append("r: 1.00"); bufferWriter.newLine(); bufferWriter.append("l: false"); bufferWriter.flush(); bufferWriter.close(); fileWriter.close(); } catch (IOException ex) { } }
public void updateLocalList(String versionID, String filename) { Integer vid = Integer.parseInt(versionID); vid = vid + 1; File file = new File(url + "locallist"); BufferedReader reader = null; BufferedWriter writer = null; // loop the valued info in to arraylist try { reader = new BufferedReader(new FileReader(file)); String lineString = null; List list = new ArrayList(); while ((lineString = reader.readLine()) != null) { if (lineString.equals(filename + " " + versionID)) { continue; } else { list.add(lineString); } } writer = new BufferedWriter(new FileWriter(file)); for (int i = 0; i < list.size(); i++) { writer.write(list.get(i).toString()); writer.newLine(); } writer.write(filename + " " + vid.toString()); writer.newLine(); writer.flush(); writer.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Write the resources to the specified data file. * * @param f data file to which to write the CSV data * @param resources resources to process * @param serverBase server based to which to preprend the resource id (to build fullUrl) * @param writeColumnTitles true to write a line containing column titles * @throws IOException */ private void writeData( File f, List<Resource> resources, String serverBase, boolean writeColumnTitles) throws IOException { // return fast if there is nothing to do if (resources.size() == 0) { return; } if (!f.exists()) { f.createNewFile(); } String fullUrlBase = serverBase; if (!serverBase.endsWith("/")) { fullUrlBase += "/"; } // Create Writer final BufferedWriter bw = new BufferedWriter(new FileWriter(f, true)); final SimplePatientCsvFormat fmt = new SimplePatientCsvFormat(); try { if (writeColumnTitles) { bw.write("fullUrl"); bw.write(COMMA); bw.write(fmt.getHeaders()); bw.newLine(); } // Process each resource in the list for (Resource r : resources) { if (ResourceType.Patient.equals(r.getResourceType())) { // convert resource to CSV String csv = fmt.toCsv((Patient) r); if (csv != null) { // put fullURL to the start of the line bw.write(DOUBLE_QUOTE); bw.write(fullUrlBase); if (FULLURL_FORMAT_VERSIONED.equals(getFullUrlFormat())) { // HAPI FHIR provides <id>/_history/<version> bw.write(r.getId()); } else { // use SIMPLE format bw.write(r.getIdElement().getResourceType()); bw.write(SLASH); bw.write(r.getIdElement().getIdPart()); } bw.write(DOUBLE_QUOTE); bw.write(COMMA); bw.write(csv); bw.newLine(); } } else { LOG.error("Unsupported Resource Type: {}", r.getResourceType().toString()); } } } finally { bw.close(); } }
private void writeCSR(int[] rows, int[] columns) throws IOException { try (BufferedWriter writer = new BufferedWriter(new FileWriter("CSR.txt"))) { writer.append("R: "); for (int i = 0; i < rows.length; i++) { writer.append(String.format("%4d ", rows[i])); } writer.newLine(); writer.append("C: "); for (int i = 0; i < columns.length; i++) { writer.append(String.format("%4d ", columns[i])); } writer.newLine(); writer.newLine(); // write graph neighbors for (int i = 0; i < rows.length - 1; i++) { int start = rows[i]; int end = rows[i + 1]; writer.append(String.format("%4d: ", i)); for (int j = start; j < end; j++) { writer.append(String.format("%4d ", columns[j])); } writer.newLine(); } } }
private void updateVersionFile(final Wagon wagon) throws IOException, TransferFailedException, ResourceDoesNotExistException, AuthorizationException { // update the version.txt accordingly final File versionOldFile = File.createTempFile("version-old", "txt"); final File versionNewFile = File.createTempFile("version-new", "txt"); wagon.get("version.txt", versionOldFile); boolean updated = false; // look for our artifactId entry final BufferedReader reader = new BufferedReader(new FileReader(versionOldFile)); final BufferedWriter writer = new BufferedWriter(new FileWriter(versionNewFile)); for (String line = reader.readLine(); null != line; line = reader.readLine()) { if (line.equals(project.getArtifactId())) { updateArtifactEntry(reader, writer); updated = true; } else { // line remains the same writer.write(line); writer.newLine(); } } if (!updated) { writer.newLine(); updateArtifactEntry(reader, writer); } reader.close(); writer.close(); wagon.put(versionNewFile, "version.txt"); }
public static void tagFile(Tagger tagger, String input_file, String output_file) { BufferedWriter bw = null; BufferedReader br = null; try { br = new BufferedReader(new FileReader(input_file)); bw = new BufferedWriter(new FileWriter(output_file)); String str = br.readLine(); List<String> sentence = new ArrayList<String>(); List<String> tags = new ArrayList<String>(); while (str != null) { if (StringUtils.isBlank(str)) { tags = tagger.tag(sentence); for (int i = 0; i < sentence.size(); i++) { bw.write(sentence.get(i) + " " + tags.get(i)); bw.newLine(); } bw.write(""); bw.newLine(); sentence = new ArrayList<String>(); str = br.readLine(); tags = new ArrayList<String>(); continue; } sentence.add(str); str = br.readLine(); } bw.close(); } catch (IOException e) { e.printStackTrace(); } }
/** * 오류가 발생한 경우 사용하도록 한다. * * <p>WEBCASH 폴더에 yyyyMMdd.log 파일명으로 저장된다. * * <p> * * @param message */ public static void saveSdCardErrorLog(String... message) { if (LibConf.ISRELEASE) return; String path = Environment.getExternalStorageDirectory() + "/WEBCASH"; File logFile = new File(path); if (!logFile.exists()) { logFile.mkdir(); } String fileName = "/" + CurrDate("yyyy-MM-dd") + ".err"; logFile = new File(path + fileName); if (!logFile.exists()) { try { logFile.createNewFile(); } catch (IOException exp) { exp.printStackTrace(); } } try { // BufferedWriter for performance, true to set append to file flag BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); buf.newLine(); buf.newLine(); buf.append("[").append(CurrDate("HH:mm:ss SSS")).append("]"); for (int i = 0; i < message.length; i++) { buf.newLine(); buf.append(message[i]); } buf.close(); } catch (IOException exp) { exp.printStackTrace(); } }
public static void create(String player, String target, double amount, boolean hidden) { File db = new File( TrueEconomy.getStatic().getDataFolder().toString() + File.separator + "bounties" + File.separator + player.toLowerCase() + ".efd"); File db1 = new File(TrueEconomy.getStatic().getDataFolder().toString()); File db2 = new File(TrueEconomy.getStatic().getDataFolder().toString() + File.separator + "bounties"); if (!db1.exists()) db1.mkdir(); if (!db2.exists()) db2.mkdir(); if (db.exists()) return; FileWriter fileWriter = null; BufferedWriter bufferWriter = null; try { fileWriter = new FileWriter(db); bufferWriter = new BufferedWriter(fileWriter); bufferWriter.append("t: " + target); bufferWriter.newLine(); bufferWriter.append("a: " + amount); bufferWriter.newLine(); bufferWriter.append("h: " + hidden); bufferWriter.newLine(); bufferWriter.append("c: _null"); bufferWriter.newLine(); bufferWriter.append("f: _null"); bufferWriter.flush(); bufferWriter.close(); fileWriter.close(); } catch (IOException ex) { } }
private static void writePemEncrypted( BufferedWriter out, String pemHeader, byte[] encoding, CipherSpec cipher, char[] passwd) throws IOException { Cipher c = cipher.getCipher(); byte[] iv = new byte[c.getBlockSize()]; random.nextBytes(iv); byte[] salt = new byte[8]; System.arraycopy(iv, 0, salt, 0, 8); OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator(); pGen.init(PBEParametersGenerator.PKCS5PasswordToBytes(passwd), salt); KeyParameter param = (KeyParameter) pGen.generateDerivedParameters(cipher.getKeyLenInBits()); SecretKey secretKey = new SecretKeySpec( param.getKey(), org.jruby.ext.openssl.Cipher.Algorithm.getAlgorithmBase(c)); byte[] encData = null; try { c.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv)); encData = c.doFinal(encoding); } catch (GeneralSecurityException gse) { throw new IOException("exception using cipher: " + gse.toString()); } out.write(BEF_G + pemHeader + AFT); out.newLine(); out.write("Proc-Type: 4,ENCRYPTED"); out.newLine(); out.write("DEK-Info: " + cipher.getOsslName() + ","); writeHexEncoded(out, iv); out.newLine(); out.newLine(); writeEncoded(out, encData); out.write(BEF_E + pemHeader + AFT); out.flush(); }
private File createPasswordFile(int commentLines, int users) { try { File testFile = File.createTempFile(this.getClass().getName(), "tmp"); testFile.deleteOnExit(); BufferedWriter writer = new BufferedWriter(new FileWriter(testFile)); for (int i = 0; i < commentLines; i++) { writer.write(TEST_COMMENT); writer.newLine(); } for (int i = 0; i < users; i++) { writer.write(TEST_USERNAME + i + ":" + TEST_PASSWORD); writer.newLine(); } writer.flush(); writer.close(); _testPwdFiles.add(testFile); return testFile; } catch (IOException e) { fail("Unable to create test password file." + e.getMessage()); } return null; }
/** * Writes a FASTA file from a defined input Database object. * * @param inputDb Input database. * @param outputPath Output path. */ public static void writeDatabase(Database inputDb, String outputPath) { try { BufferedWriter bfWriter = new BufferedWriter(new FileWriter(outputPath)); List<Entry> entries = inputDb.getEntries(); int count = 1; for (Entry e : entries) { String header = e.getName(); String gi = " "; if (header.contains("gi")) { String[] split = e.getName().split("\\s+"); for (String temp : split) { if (temp.contains("gi")) { gi = temp.substring(2); } } header = header.replaceFirst(">", ">gi|" + gi + "|"); } else { header = e.getName().replaceFirst(">", ">gi|GENSEQ" + count + "|"); } header = header.trim().replaceAll(" +", " "); bfWriter.write(header); bfWriter.newLine(); bfWriter.write(e.getSequenceAsString()); bfWriter.newLine(); count++; } bfWriter.flush(); bfWriter.close(); } catch (IOException e) { e.printStackTrace(); } }
private static void writeStrs( String outFileName, List<ShortTandemRepeat> strs, boolean writeAll) { BufferedWriter bw = null; File outFile = new File(outFileName); try { if (outFile.exists()) { outFile.delete(); } bw = new BufferedWriter(new FileWriter(outFile)); if (writeAll) { for (ShortTandemRepeat str : strs) { bw.write(str.toString()); bw.newLine(); } } else { for (ShortTandemRepeat str : strs) { bw.write(str.toSmallString()); bw.newLine(); } } } catch (IOException e) { e.printStackTrace(); } finally { if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
private void passivate(BufferedWriter writer, HashMap<String, List<String>> idx) throws IOException { StringBuilder bldr = new StringBuilder(); int ctr = 0; List<String> value; TreeMap<String, List<String>> map = new TreeMap<String, List<String>>(idx); for (Entry<String, List<String>> etr : map.entrySet()) { value = etr.getValue(); bldr.append(etr.getKey()).append("/").append(value.size()).append(":"); bldr.append(asString(value)); bldr.append("#"); ctr++; if (ctr % 1000 == 0) { writer.write(bldr.toString()); writer.newLine(); bldr.delete(0, bldr.length()); writer.flush(); } } writer.write(bldr.toString()); bldr.delete(0, bldr.length()); writer.newLine(); writer.flush(); writer.close(); idx.clear(); idx = null; map.clear(); map = null; }
/** * Parse text from reader and write word broken output to writer * * @param r * @param w * @throws IOException */ public void parse(BufferedReader r, BufferedWriter w) throws IOException { MyanmarParser mp = new MyanmarParser(); String line = r.readLine(); Vector<ClusterProperties> syllables = new Vector<ClusterProperties>(); while (line != null) { int offset = 0; do { if (line.length() == 0) { w.newLine(); continue; } ClusterProperties cp = mp.getNextSyllable(line, offset); syllables.add(cp); MyPairStatus status = cp.getBreakStatus(); if (status == MyPairStatus.MY_PAIR_WORD_BREAK || status == MyPairStatus.MY_PAIR_EOL || status == MyPairStatus.MY_PAIR_PUNCTUATION) { checkAndAppendSyllables(w, line, syllables); } offset = cp.getEnd(); } while (offset < line.length()); w.newLine(); line = r.readLine(); } }
private void logCompitationProblem( String entry, String compilationProblemMessage, ErrorType errorToCheck) { try { String[] columns = entry.split(";"); String revision = columns[0]; String classFile = columns[1]; if (errorToCheck == ErrorType.IMPORT_ERROR) { File file = new File("results/log_parser_import_issue.csv"); FileWriter fw = new FileWriter(file, true); BufferedWriter bw = new BufferedWriter(fw); bw.write(revision + ";" + classFile + ";" + compilationProblemMessage); bw.newLine(); bw.close(); fw.close(); } else if (errorToCheck == ErrorType.DUPLICATED_ERROR) { File file = new File("results/log_parser_duplicated_issue.csv"); FileWriter fw = new FileWriter(file, true); BufferedWriter bw = new BufferedWriter(fw); bw.write(revision + ";" + classFile + ";" + compilationProblemMessage); bw.newLine(); bw.close(); fw.close(); } } catch (IOException e) { e.printStackTrace(); } }
public static void writeDHParameters(Writer _out, DHParameterSpec params) throws IOException { BufferedWriter out = makeBuffered(_out); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); ASN1EncodableVector v = new ASN1EncodableVector(); BigInteger value; if ((value = params.getP()) != null) { v.add(new DERInteger(value)); } if ((value = params.getG()) != null) { v.add(new DERInteger(value)); } aOut.writeObject(new DERSequence(v)); byte[] encoding = bOut.toByteArray(); out.write(BEF_G + PEM_STRING_DHPARAMS + AFT); out.newLine(); writeEncoded(out, encoding); out.write(BEF_E + PEM_STRING_DHPARAMS + AFT); out.newLine(); out.flush(); }
protected void evaluate( Collection<EquivClassCandRanking> cands, Dictionary testDict, String outFileName) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(outFileName)); DecimalFormat df = new DecimalFormat("0.00"); writer.write("K\tAccuracy@TopK\tNumInDict"); writer.newLine(); Set<EquivalenceClass> goldTrans; double oneInTopK, total, accInTopK; for (int i = 0; i < K.length; i++) { oneInTopK = 0; total = 0; for (EquivClassCandRanking ranking : cands) { goldTrans = testDict.translate(ranking.getEqClass()); if (goldTrans != null) { oneInTopK += (ranking.numInTopK(goldTrans, K[i]) > 0) ? 1 : 0; total++; } } accInTopK = 100.0 * oneInTopK / total; writer.write(K[i] + "\t" + df.format(accInTopK) + "\t" + total); writer.newLine(); } writer.close(); }
private static void writeOneFile(LinkedList<int[]> inv_list, String filename, int term_sum) { try { String word = filename.substring(0, filename.indexOf('.')); String field = filename.substring(filename.indexOf('.') + 1, filename.length()); BufferedWriter bw = new BufferedWriter(new FileWriter(new File("data/" + field + "_local/" + filename))); bw.write(word + " " + word); bw.write(" " + term_sum); bw.write(" " + 0); // here just want to be consistent with the .inv lists bw.newLine(); int[] chunk = null; while ((chunk = inv_list.pollFirst()) != null) { bw.write(chunk[0] + " "); bw.write(chunk[1] + " "); bw.write(chunk[2] + " "); for (int j = 0; j < chunk[1]; j++) { bw.write( Integer.toString(chunk[j + 2])); // if not converted to String, it will write bytes if (j != chunk[1] - 1) bw.write(" "); } if (inv_list.size() != 0) bw.newLine(); } bw.close(); } catch (Exception e) { e.printStackTrace(); } }
public void output(Set<String> permissions) { int permsize = permissions.size(); try { output.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(output)); writer.write("#// ------------ PERMISSIONS LIST ------------ \\\\#"); writer.newLine(); writer.write( "#// --------------- " + FunctionHelper.getCurrentDateString() + " --------------- \\\\#"); writer.newLine(); writer.write("#// ------------ Total amount: " + permsize + " ------------ \\\\#"); writer.newLine(); writer.write("#// ------------------------------------------ \\\\#"); writer.newLine(); writer.newLine(); for (String perm : permissions) { writer.write(perm); writer.newLine(); } writer.close(); } catch (Exception e) { } }
private static void writeData( String file, Map<String, Map<String, String>> data, Set<String> cases) throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write("geneSymbol"); for (String header : cases) { out.write("\t" + header); } out.newLine(); for (Map.Entry<String, Map<String, String>> entry : data.entrySet()) { out.write(entry.getKey()); Map<String, String> map = entry.getValue(); for (String header : cases) { out.write("\t"); String value = map.get(header); if (value == null) { out.write("NA"); } else { out.write(value); } } out.newLine(); } out.close(); }
/** * SD카드에 WEBCASH 폴더에 당일 날짜의 파일명으로 로그를 저장한다. * * @param message : 저장할 메시지 */ public static void saveSdCard(String... message) { if (LibConf.ISRELEASE) return; String fileName = "/" + CurrDate("yyyy-MM-dd") + ".log"; try { File logFile = getLogFile(fileName); if (logFile == null) return; // BufferedWriter for performance, true to set append to file flag BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); for (int i = 0; i < message.length; i++) { buf.append("[").append(CurrDate("HH:mm:ss SSS")).append("]"); buf.newLine(); buf.append(message[i]); buf.newLine(); } buf.newLine(); buf.close(); } catch (IOException exp) { exp.printStackTrace(); } }
public String command(final CommandSender sender, Command command, String[] args) { try { BufferedWriter banlist = new BufferedWriter(new FileWriter("banned-players.txt", true)); for (String p : plugin.cache.keySet()) { for (BanInfo info : plugin.cache.get(p)) { if (info.getType() == BanType.BAN.getId()) { banlist.newLine(); banlist.write(g(p, info.getAdmin(), info.getReason())); } } } banlist.close(); BufferedWriter iplist = new BufferedWriter(new FileWriter("banned-ips.txt", true)); for (String p : plugin.cacheIP.keySet()) { for (BanInfo info : plugin.cacheIP.get(p)) { if (info.getType() == BanType.IPBAN.getId()) { iplist.newLine(); iplist.write(g(p, info.getAdmin(), info.getReason())); } } } iplist.close(); } catch (IOException e) { String msg = ChatColor.translateAlternateColorCodes('&', lang.getString("Export.Failed")); if (plugin.getLog()) plugin.getLogger().severe(ChatColor.stripColor(msg)); e.printStackTrace(); return msg; } String msg = ChatColor.translateAlternateColorCodes('&', lang.getString("Export.Completed")); if (plugin.getLog()) plugin.getLogger().info(ChatColor.stripColor(msg)); return msg; }
private void printNumberOfHouseholdsBySize() throws IOException { out.write("P(s)"); out.newLine(); // [1],[2],[3],[4],[5],[>=6] double[] counters = new double[6]; for (Household household : this.microcensus.getHouseholds().getHouseholds().values()) { String id = household.getId().toString(); int size = Integer.parseInt( (String) this.microcensus .getHouseholdAttributes() .getAttribute(id, MZConstants.HOUSEHOLD_SIZE)); double hh_weight = Double.parseDouble( (String) this.microcensus .getHouseholdAttributes() .getAttribute(id, MZConstants.HOUSEHOLD_WEIGHT)); if (size >= 6) size = 6; counters[size - 1] += hh_weight; } for (int a = 0; a <= counters.length - 1; a++) { out.write("Size " + (a + 1) + ":\t" + counters[a]); out.newLine(); } }
private static void patchConfFile(File originalConf, File dest, String library) throws IOException { Scanner sc = new Scanner(originalConf); try { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest))); try { boolean patched = false; while (sc.hasNextLine()) { String line = sc.nextLine(); out.append(line); out.newLine(); if (!patched && "[plexus.core]".equals(line)) { out.append("load ").append(library); out.newLine(); patched = true; } } } finally { out.close(); } } finally { sc.close(); } }
private void updateArtifactEntry(final BufferedReader reader, final BufferedWriter writer) throws IOException { // this line remains the same writer.write(project.getArtifactId()); writer.newLine(); // next line is version, author (or "deployer"), date & time, reader.readLine(); writer.write( project.getVersion() + " was last deployed by " + System.getProperty("user.name") + " at " + SimpleDateFormat.getDateTimeInstance().format(now)); writer.newLine(); // next line is the quote for (String line = reader.readLine(); null != line && 0 < line.length(); line = reader.readLine()) {} ; final String quote = project.getProperties().getProperty("version.quote"); if (null != quote) { writer.write(quote); writer.newLine(); writer.newLine(); } }
private static void writeToFile(int priority, String tag, String msg, Throwable tr) { if ((priority >= sCurrentPriority) && (sBufferedWriter != null)) { try { if (checkFileSize()) { sBufferedWriter = new BufferedWriter(new FileWriter(sTheLogFile, true)); } sBufferedWriter.write(formatMsg(tag, msg)); sBufferedWriter.newLine(); if (tr != null) { sBufferedWriter.write(Log.getStackTraceString(tr)); sBufferedWriter.newLine(); } sBufferedWriter.flush(); } catch (IOException e) { Log.e("FileLog", Log.getStackTraceString(e)); } } if (sBufferedWriter == null) { Log.e("FileLog", "You have to call FileLog.open(...) before starting to log"); } }
private void generate(Integer iterations) { BufferedWriter writerWriter = null; BufferedWriter readerWriter = null; try { File outputDir = sendersFile.getParentFile(); File writerOutputFile = new File(outputDir, "WriterAccessLog.txt"); writerWriter = new BufferedWriter(new FileWriter(writerOutputFile)); File readerOutputFile = new File(outputDir, "ReaderAccessLog.txt"); readerWriter = new BufferedWriter(new FileWriter(readerOutputFile)); for (int i = 0; i < iterations; i++) { String message = writerLogLine(); writerWriter.write(message); writerWriter.newLine(); readerWriter.write(readerLogLine()); readerWriter.newLine(); } } catch (IOException ioe) { throw new RuntimeException(ioe); } finally { try { writerWriter.close(); readerWriter.close(); } catch (IOException e) { } } }
public void actionPerformed(ActionEvent event) { System.out.println("Done listener"); setVisible(false); try { // will transpose table before writing for ease... BufferedWriter output = new BufferedWriter(new FileWriter(defaultFile)); output.newLine(); for (int col = 0; col < table.getColumnCount(); col++) { // IJ.log("starting col: " + col + " of " + table.getColumnCount() +"total\n" ); output.write(colNames.get(col) + "\t"); for (int row = 0; row < table.getRowCount(); row++) { // IJ.log("starting row: " + row + " of " + table.getRowCount() +"total\n" ); if (table.getValueAt(row, col) != null) { output.write((String) table.getValueAt(row, col)); output.write(("\t")); } // IJ.log("writing " + table.getValueAt(row, col)); } output.newLine(); } // IJ.log("about to close prefs file"); output.close(); } catch (IOException e) { // TODO Auto-generated catch block IJ.log("IO exception writing file: " + defaultFile); e.printStackTrace(); } dispose(); }
public void store(View v) { Spanned s = (Spanned) mTextView.getText(); BackgroundColorSpan[] spans = s.getSpans(0, s.length(), BackgroundColorSpan.class); BufferedWriter bw = null; try { int len = spans.length; bw = new BufferedWriter(new FileWriter(mFile)); bw.write(String.valueOf(len)); bw.newLine(); for (BackgroundColorSpan span : spans) { int start = s.getSpanStart(span); int end = s.getSpanEnd(span); int color = span.getBackgroundColor(); bw.write("" + start + "," + end + "," + color); bw.newLine(); } bw.write(mText); clear(v); } catch (IOException e) { Log.e(TAG, "IO error", e); } finally { closeQuietly(bw); } }
/* * (non-Javadoc) * * @see com.sitewhere.spi.server.lifecycle.ILifecycleComponent#start() */ @Override public void start() throws SiteWhereException { try { String key = URLEncoder.encode(getSasKey(), "UTF8"); String connectionString = "amqps://" + getSasName() + ":" + key + "@" + getServiceBusName(); File file = File.createTempFile("eventhub", ".props"); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write("connectionfactory.SBCF = " + connectionString); writer.newLine(); writer.write("queue.EVENTHUB = " + getEventHubName()); writer.newLine(); writer.close(); Hashtable<String, String> env = new Hashtable<String, String>(); env.put( Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.amqp_1_0.jms.jndi.PropertiesFileInitialContextFactory"); env.put(Context.PROVIDER_URL, file.getAbsolutePath()); Context context = new InitialContext(env); this.factory = (ConnectionFactory) context.lookup("SBCF"); this.destination = (Destination) context.lookup("EVENTHUB"); this.connection = factory.createConnection(); this.session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); this.sender = session.createProducer(destination); } catch (IOException e) { throw new SiteWhereException(e); } catch (NamingException e) { throw new SiteWhereException(e); } catch (JMSException e) { throw new SiteWhereException(e); } }