Java Code Examples for java.io.FileWriter

The following are top voted examples for showing how to use java.io.FileWriter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: Torrent-Client   File: utpserver.java View source code 7 votes vote down vote up
public static void main(String [] args) throws Exception {
	UTPServerSocket server = new UTPServerSocket(5000);
	UTPSocket conn = server.listen();
   InputStream in = conn.getInputStream();
	String incoming = "";  
	File test = new File("temp.txt");
	FileWriter outfile = new FileWriter(test);
	while (true) {
		int n = in.read();
		if (n == -1) {
			break;
		} else {
			outfile.write(n);
		}
	}
	outfile.flush();
	outfile.close();
	System.out.println("FINISHED READ");
}
 
Example 2
Project: raylew_algorithm   File: ??????.java View source code 6 votes vote down vote up
public static void createResFile(boolean createFile) throws Exception {
	if (createFile) {
		FileWriter writer = new FileWriter("F:/????.txt");
		for (int i = 0; i < size; i++) {
			writer.write(arr[i] + " ");
		}
		writer.close();
	} else {
		printArr(arr);
	}
}
 
Example 3
Project: iot-server-appliances   File: AJAXService.java View source code 6 votes vote down vote up
private void writeResourceJson(JSONObject jsonObject) {
	try {
		String displayAgentHome = ResourceUtil.getDisplayAgentHome();
		FileWriter file = new FileWriter(
				displayAgentHome + File.separator + LauncherConstants.WEB_APPS_PATH + File.separator
						+ "_system" + File.separator + "current_resource.json");
		file.write(jsonObject.toJSONString());
		file.flush();
		file.close();
	} catch (IOException e) {
		log.severe("Error occurred while writing to `current_resource.json` ! \n" + e
				.getMessage());
	}
}
 
Example 4
Project: aws-toolkit-eclipse   File: Ec2WebProxy.java View source code 6 votes vote down vote up
/**
 * Connects to the proxy and publishes the proxy configuration.
 *
 * @throws IOException
 *             If any problems were encountered publishing the
 *             configuration.
 */
@Override
public void publishServerConfiguration(File unused) throws Exception {
	HaproxyConfigurationListenSection section
		= new HaproxyConfigurationListenSection("proxy", serverPort);

	for (Instance instance : proxiedInstances) {
		section.addServer(instance.getPrivateDnsName() + ":" + serverPort);
	}

	String proxyConfiguration
		= getGlobalSection().toConfigString()
		+ getDefaultsSection().toConfigString()
		+ section.toConfigString();

	logger.fine("Publishing proxy configuration:\n" + proxyConfiguration);

	File f = File.createTempFile("haproxyConfig", ".cfg");
	FileWriter writer = new FileWriter(f);
	try {
		writer.write(proxyConfiguration);
	} finally {
		writer.close();
	}

	String remoteFile = "/tmp/" + f.getName();
	remoteCommandUtils.copyRemoteFile(f.getAbsolutePath(), remoteFile, instance);

	String remoteCommand = "cp " + remoteFile + " /etc/haproxy.cfg";
	remoteCommandUtils.executeRemoteCommand(remoteCommand, instance);
}
 
Example 5
Project: ArubaSyslog   File: StartProcessing.java View source code 6 votes vote down vote up
/**
 * @param args
 * @throws ParseException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public static void main(String[] args) throws ParseException, IOException, NoSuchAlgorithmException {
    
    File inFile, outFile;
    FileWriter fileWriter;
    StartProcessing sp = new StartProcessing();

    sp.ReadCmd(args);

    inFile = new File(sp.inFile);
    outFile = new File(sp.outFile);
    BufferedReader in = new BufferedReader(new FileReader(inFile));
    
    if (!outFile.exists())
        outFile.createNewFile();
    
    fileWriter = new FileWriter(outFile);
    String input;
    ArrayList<String> apName = new ArrayList<String>();

    while ((input = in.readLine()) != null) {
        String output = SyslogPreprocess.Filter(input);
        output = SyslogPreprocess.APIPDeletion(output);

        output = SyslogPreprocess.APNameAnonymous(output, apName);
        output = SyslogPreprocess.IPAnonymous(output);
        output = SyslogPreprocess.MacAnonymous(output);
        output = SyslogPreprocess.UserNameAnonymous(output);
        
        if (output != null)
            fileWriter.write(output + "\n");
    }
    
    fileWriter.close();
}
 
Example 6
Project: jbosgi   File: LayeredBundlePathTest.java View source code 6 votes vote down vote up
private void writeLayersConf(String rootName, String... layers) throws IOException {
    if (layers != null && layers.length > 0) {

        StringBuilder sb = new StringBuilder("layers=");
        for (int i = 0; i < layers.length; i++) {
            if (i > 0) {
                sb.append(',');
            }
            sb.append(layers[i]);
        }

        File repo = "root-a".equals(rootName) ? repoA : repoB;
        File layersConf = new File(repo, "layers.conf");
        layersConf.createNewFile();
        FileWriter fw = new FileWriter(layersConf);
        try {
            PrintWriter pw = new PrintWriter(fw);
            pw.println(sb.toString());
            pw.close();
        } finally {
            try {
                fw.close();
            } catch (Exception e) {
                // meh
            }
        }
    }
}
 
Example 7
Project: OsmUi   File: mxUtils.java View source code 6 votes vote down vote up
/**
 * Writes the given string into the given file.
 * 
 * @param contents
 *            String representing the file contents.
 * @param filename
 *            Name of the file to be written.
 * @throws IOException
 */
public static void writeFile(String contents, String filename)
		throws IOException
{
	FileWriter fw = new FileWriter(filename);
	fw.write(contents);
	fw.flush();
	fw.close();
}
 
Example 8
Project: jena   File: PatternCompilerBuilder.java View source code 6 votes vote down vote up
static private void outRules(String name) throws IOException {
    count = 0;
    // if (true) throw new RuntimeException();
    out = new FileWriter("src/main/jflex/org/apache/jena/iri/impl/"+name+".jflex");
    copy("src/main/jflex/org/apache/jena/iri/impl/iri.jflex");
    out.write("%class Lexer");
    out.write(name.substring(0, 1).toUpperCase());
    out.write(name.substring(1));
    out.write("\n%%\n");
    int exc1[]=
        new int[]{DOUBLE_DASH_IN_REG_NAME,NOT_DNS_NAME};
    int empty[]= new int[0];
    int sub1[] = new int[]{ACE_PREFIX};
    //        int sub2[] = new int[]{DOUBLE_DASH_IN_REG_NAME,ACE_PREFIX};
    int sub4[] = new int[]{DOUBLE_DASH_IN_REG_NAME};
    int sub3[] = new int[]{NOT_DNS_NAME};
    
    new ExpandAndOutput(exc1,empty,true).expand("@{" + name + "}");
    //   new ExpandAndOutput(empty,sub2,true).expand("@{" + name + "}");
    new ExpandAndOutput(sub1,sub4,true).expand("@{" + name + "}");
    new ExpandAndOutput(empty,sub3,true).expand("@{" + name + "}");

    out.write("\n");
    System.out.println(name + ": " + count + " expansions");
    out.close();

    MainGenerateLexers.runJFlex(new String[] { "-d", "src/main/java/org/apache/jena/iri/impl", "src/main/jflex/org/apache/jena/iri/impl/"+name+".jflex" });
    System.out.println(System.currentTimeMillis() - start);

}
 
Example 9
Project: WiFi-Automatic   File: Logger.java View source code 6 votes vote down vote up
@SuppressWarnings("deprecation")
public static void log(String msg) {
    if (!BuildConfig.DEBUG) return;
    android.util.Log.d(APP, msg);
    try {
        if (fw == null) {
            fw = new FileWriter(new File(
                    Environment.getExternalStorageDirectory().toString() + "/" + APP + ".log"),
                    true);
        }
        date.setTime(System.currentTimeMillis());
        fw.write(date.toLocaleString() + " - " + msg + "\n");
        fw.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 10
Project: wso2-synapse   File: ConfigurationMigrator.java View source code 6 votes vote down vote up
public static void doTransform(String xmlFile, String xslFile, String outFile)
        throws TransformerException, IOException {

    FileReader xslFileReader = new FileReader(xslFile);
    StreamSource xslStreamSource = new StreamSource(xslFileReader);

    FileReader xmlFileReader = new FileReader(xmlFile);
    StreamSource xmlStreamSource = new StreamSource(xmlFileReader);

    FileWriter outFileWriter = new FileWriter(outFile);
    StreamResult outStreamResult = new StreamResult(outFileWriter);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer(xslStreamSource);

    transformer.transform(xmlStreamSource, outStreamResult);
    outFileWriter.flush();
}
 
Example 11
Project: AIDR   File: CollectorManageResource.java View source code 6 votes vote down vote up
@GET
@Path("/persist")
@Produces(MediaType.TEXT_PLAIN)
public String persistRunningCollections() {

    String response = "";
    List<CollectionTask> collections = GenericCache.getInstance().getAllRunningCollectionTasks();
    if (collections == null || collections.isEmpty()) {
        return "No running collection found to persist.";
    }
    
    logger.info(collections.size() + " collections found to be persisted.");
    Gson gson = new Gson();
    try {
        FileWriter file = new FileWriter("fetcher_running_coll.json");
        for (CollectionTask collection : collections) {
            String json = gson.toJson(collection);
            response += "Persisting: " + collection.getCollectionCode() + "\n";
            file.write(json + "\n");
        }
        file.flush();
        file.close();

    } catch (IOException e) {
        logger.error("Error in persisting running collections");
    }

    return response;

}
 
Example 12
Project: stargate-core   File: CQLUnitD.java View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Person[] persons = jsonMapper.readValue(is2, Person[].class);
    File file = new File("samples/sample-json.cql");
    FileWriter fileWriter = new FileWriter(file);
    for (Person person : persons) {
        fileWriter.write(person.toInsertString() + "\n");
    }
    fileWriter.flush();
    fileWriter.close();
}
 
Example 13
Project: MinecraftAutoInstaller   File: ProfileCreator.java View source code 6 votes vote down vote up
public void addProfile() throws UnsupportedEncodingException, IOException {
    JSONParser parser = new JSONParser();
    SettingHandling sh = new SettingHandling();
    Properties settings = sh.getSettingFile();
    String profilename = new String(settings.getProperty("profilename").getBytes("ISO-8859-1"), "UTF-8");
    String profileversion = new String(settings.getProperty("profileverison").getBytes("ISO-8859-1"), "UTF-8");
    String path = null;
    if(isWindows()) {
        path = System.getenv("APPDATA") + "\\.minecraft\\";
    } else if(isMac()) {
        path = System.getenv("APPDATA") + "\\minecraft\\";
    } else {
        path = System.getenv("APPDATA") + "\\minecraft\\";
    }
    Object obj = null;
    try {
        obj = parser.parse(new FileReader(path + "\\launcher_profiles.json"));
    } catch (Exception ex) {
        Logger.getLogger(ProfileCreator.class.getName()).log(Level.SEVERE, null, ex);
    }
    JSONObject jsonObject = (JSONObject) obj;
    Object profiles = jsonObject.get("profiles");
    JSONObject profile = new JSONObject();
    profile.put("name", profilename);
    profile.put("lastVersionId", profileversion);
    JSONObject jprofiles = (JSONObject) profiles;
    jprofiles.put(profilename, profile);
    jsonObject.put("profiles", jprofiles);
    jsonObject.put("selectedProfile", profilename);
    try {
 
        FileWriter file = new FileWriter(path + "\\launcher_profiles.json");
        file.write(jsonObject.toJSONString());
        file.flush();
        file.close();
        
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 14
Project: ndogen_stalled   File: GeneratorUtils.java View source code 6 votes vote down vote up
public static void writeFile(String file, String content) throws IOException {
	File _file = new File(file);
	_file.getParentFile().mkdirs();
	FileWriter writer = new FileWriter(_file);
	writer.append(content);
	writer.flush();
	writer.close();
}
 
Example 15
Project: fiji   File: Export_EPS.java View source code 6 votes vote down vote up
public void run(ImageProcessor ip) {
	if (img.getStackSize() != 1) {
		IJ.error("Can only save 2D images!");
		return;
	}
	imgTitle = stripFileExtension(img.getTitle());
	SaveDialog sd = new SaveDialog("Save image as EPS", imgTitle, extension);
	String dir = sd.getDirectory();
	String name = sd.getFileName();
	if(name == null || name.length() == 0)
		return;
	if (ip.isBinary()) {
		YesNoCancelDialog bd = new YesNoCancelDialog(null, "EPS Export", "Save this image as binary bitmap?");
		if (bd.cancelPressed())
			return;
		saveAsBitmap = bd.yesPressed();
	}

	width = ip.getWidth();
	height = ip.getHeight();
	imgType = img.getType();
	imgCalib = img.getCalibration();
	realWidth = width * imgCalib.pixelWidth;
	realHeight = height * imgCalib.pixelHeight;
	ip.resetMinAndMax();

	IJ.showStatus("Writing EPS " + dir + name + "...");
	try {
		FileWriter output = new FileWriter(dir + name);
		writeHeader(output, name);
		writeImage(output, ip);
		writeTrailer(output);
		output.flush();
		output.close();
	} catch(IOException e) {
		e.printStackTrace();
		IJ.error("Error writing EPS file " + dir + name);
	}
	IJ.showStatus("");
}
 
Example 16
Project: galen   File: TestNgReportBuilder.java View source code 6 votes vote down vote up
private void exportTesngReport(List<GalenTestAggregatedInfo> tests, String reportPath) throws IOException, TemplateException {
    File file = new File(reportPath);
    makeSurePathExists(file);
    file.createNewFile();
    
    FileWriter fileWriter = new FileWriter(file);
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("tests", tests);
    
    Template template = new Template("report-main", new InputStreamReader(getClass().getResourceAsStream("/testng-report/testng-report.ftl.xml")), freemarkerConfiguration);
    template.process(model, fileWriter);
    fileWriter.flush();
    fileWriter.close();
}
 
Example 17
Project: avaje-ebeanorm   File: PlatformDdlWriter.java View source code 6 votes vote down vote up
/**
 * Write the ddl files.
 */
protected void writePlatformDdl(DdlWrite write, File resourcePath, int migrationVersion) throws IOException {

  if (!write.isApplyEmpty()) {
    FileWriter applyWriter = createWriter(resourcePath, migrationVersion, "apply.sql");
    try {
      writeApplyDdl(applyWriter, write);
      applyWriter.flush();
    } finally {
      applyWriter.close();
    }

    if (!write.isApplyRollbackEmpty()) {
      FileWriter applyRollbackWriter = createWriter(resourcePath, migrationVersion, "applyRollback.sql");
      try {
        writeApplyRollbackDdl(applyRollbackWriter, write);
        applyRollbackWriter.flush();
      } finally {
        applyRollbackWriter.close();
      }
    }
  }

  if (!write.isDropEmpty()) {
    FileWriter dropWriter = createWriter(resourcePath, migrationVersion, "drop.sql");
    try {
      writeDropDdl(dropWriter, write);
      dropWriter.flush();
    } finally {
      dropWriter.close();
    }
  }
}
 
Example 18
Project: visuwall   File: ZooKeeperServerMainTest.java View source code 6 votes vote down vote up
public MainThread(int clientPort) throws IOException {
    super("Standalone server with clientPort:" + clientPort);
    File tmpDir = ClientBase.createTmpDir();
    confFile = new File(tmpDir, "zoo.cfg");

    FileWriter fwriter = new FileWriter(confFile);
    fwriter.write("tickTime=2000\n");
    fwriter.write("initLimit=10\n");
    fwriter.write("syncLimit=5\n");

    File dataDir = new File(tmpDir, "data");
    if (!dataDir.mkdir()) {
        throw new IOException("unable to mkdir " + dataDir);
    }
    
    // Convert windows path to UNIX to avoid problems with "\"
    String dir = dataDir.toString();
    String osname = java.lang.System.getProperty("os.name");
    if (osname.toLowerCase().contains("windows")) {
        dir = dir.replace('\\', '/');
    }
    fwriter.write("dataDir=" + dir + "\n");
    
    fwriter.write("clientPort=" + clientPort + "\n");
    fwriter.flush();
    fwriter.close();

    main = new TestZKSMain();
}
 
Example 19
Project: lodmill   File: Stats.java View source code 6 votes vote down vote up
static void writeTextileMappingTable(
		final List<Entry<String, Integer>> occurenceEntries,
		final List<Entry<String, StringBuilder>> valueEntries,
		final File textileMappingFile) throws IOException {
	final StringBuilder textileBuilder = new StringBuilder(
			"|*field*|*frequency or values separated with commata*|\n");
	LOG.info("Field\tFrequency or comma separated values");
	LOG.info("----------------");
	createCsv(occurenceEntries, textileBuilder);
	createCsv(valueEntries, textileBuilder);
	textileWriter = new FileWriter(textileMappingFile);
	try {
		textileWriter.write(textileBuilder.toString());
		textileWriter.flush();
	} finally {
		textileWriter.close();
	}
}
 
Example 20
Project: sysart-itext   File: BuildTutorial.java View source code 6 votes vote down vote up
/**
 * Main method so you can call the convert method from the command line.
 * @param args 4 arguments are expected:
 * <ul><li>a sourcedirectory (root of the tutorial xml-files),
 * <li>a destination directory (where the html and build.xml files will be generated),
 * <li>an xsl to transform the index.xml into a build.xml
 * <li>an xsl to transform the index.xml into am index.html</ul>
 */

public static void main(String[] args) {
	if (args.length == 4) {
		File srcdir = new File(args[0]);
		File destdir = new File(args[1]);
		File xsl_examples = new File(srcdir, args[2]);
		File xsl_site = new File(srcdir, args[3]);
		try {
			System.out.print("Building tutorial: ");
			root = new File(args[1], srcdir.getName()).getCanonicalPath();
			System.out.println(root);
			build = new FileWriter(new File(root, "build.xml"));
			build.write("<project name=\"tutorial\" default=\"all\" basedir=\".\">\n");
			build.write("<target name=\"all\">\n");
			action(srcdir, destdir, xsl_examples, xsl_site);
			build.write("</target>\n</project>");
			build.flush();
			build.close();
		}
		catch(IOException ioe) {
			ioe.printStackTrace();
		}
	} else {
		System.err
				.println("Wrong number of parameters.\nUsage: BuildSite srcdr destdir xsl_examples xsl_site");
	}
}
 
Example 21
Project: android-platform-tools-base   File: ManifestMerger2SmallTest.java View source code 6 votes vote down vote up
/**
 * Utility method to save a [email protected] String} XML into a file.
 */
private static File inputAsFile(String testName, String input) throws IOException {
    File tmpFile = File.createTempFile(testName, ".xml");
    FileWriter fw = null;
    try {
        fw = new FileWriter(tmpFile);
        fw.append(input);
    } finally {
        if (fw != null) fw.close();
    }
    return tmpFile;
}
 
Example 22
Project: mileniagrafter   File: ConfigWriter.java View source code 6 votes vote down vote up
/**
 * Creates admin dir and admin.xml if not exists
 * @param urlX file name
 */

public ConfigWriter ( String nameX )
{
	
	//System.out.println( System.currentTimeMillis() + " MilGraAdmin Application.createConfig" );

	File adminDir = new File( "admin" );
	if ( !adminDir.exists( ) )
	{
		
		adminDir.mkdir( );
		File adminXML = new File( nameX );
		
		try
		{
			
			adminXML.createNewFile( );
			
			FileWriter writer = new FileWriter( adminXML );
			writer.append( "<!DOCTYPE root>\n<root>\n" );
			writer.append( "<enabled>\n<ip>*</ip>\n</enabled>\n" );
			writer.append( "<accesslogging>true</accesslogging>\n" );
			writer.append( "<graphslogging>true</graphslogging>\n" );
			writer.append( "<username>admin</username>\n" );
			writer.append( "<password>admin</password>\n" );
			writer.append( "</root>" );
					
			writer.flush( );
			writer.close( );
			
		}
		catch ( IOException exception ) { exception.printStackTrace( );	}
		
	}
	
}
 
Example 23
Project: aws-sdk-android   File: FileUtils.java View source code 6 votes vote down vote up
/**
 * Appends the given data to the file specified in the input and returns the
 * reference to the file.
 *
 * @param file
 * @param dataToAppend
 * @return reference to the file.
 * @throws IOException
 */
public static File appendDataToTempFile(File file, String dataToAppend)
        throws IOException {
    FileWriter outputWriter = new FileWriter(file);

    try {
        outputWriter.append(dataToAppend);
    } finally {
        outputWriter.close();
    }

    return file;
}
 
Example 24
Project: RplotGallary   File: Tools.java View source code 6 votes vote down vote up
public static void setCurrentFilePath() {
    try {
        if (!CURRENT_FILE_PATH.isEmpty()) {
            FileWriter fw = new FileWriter("CurrentFilePath.txt");
            fw.append(CURRENT_FILE_PATH);
            fw.flush();
            fw.close();
        }
    } catch (Exception ex) {
    }
}
 
Example 25
Project: cloudtm-data-platform   File: OidSqlGenerator.java View source code 6 votes vote down vote up
public void write() throws IOException {
    final FileWriter fileWriter = new FileWriter(getFilename());
    fileWriter.append("set autocommit = 0;\n");
    fileWriter.append("begin;\n\n");

    writeContents(fileWriter);

    fileWriter.append("\ncommit;\n");
    fileWriter.close();
}
 
Example 26
Project: netlib   File: TorConfig.java View source code 5 votes vote down vote up
/** used to store some new values to a file */
private void writeToFile(String filename) {
    if (filename==null) {
        return;
    }
    
    try {
        StringBuffer config = new StringBuffer();

        log.fine( "TorConfig.writeToFile(): " + config);
        // Write variable config information here

        // security parameters
        config.append(writeInt("StreamsPerCircuit",streamsPerCircuit));
        config.append(writeFloat("RankingIndexEffect",rankingIndexEffect));
        config.append(writeInt("RouteMinLength",routeMinLength));
        config.append(writeInt("RouteMaxLength",routeMaxLength));
        config.append(writeDouble("MinPercentage",minDescriptorsPercentage));
        config.append(writeInt("MinDescriptors",minDescriptors));
        config.append(writeBoolean("RouteUniqClassC",routeUniqueClassC));
        config.append(writeBoolean("RouteUniqCountry",routeUniqueCountry));
        config.append(writeInt("AllowNodeMultipleCircuits", allowModeMultipleCircuits));

         // Avoided countries
        Iterator<String> it = avoidedCountries.iterator();
        while (it.hasNext()) {
            String countryName = (String)it.next();
            config.append(writeString("AvoidCountry",countryName)); 
            log.fine("TorConfig.writeToFile: will avoid country "+countryName);
        }
         // Avoided nodes
        for (byte[] fingerprint : avoidedNodeFingerprints) {
            String fingerprintStr = Encoding.toHexString(fingerprint);
            config.append(writeString("AvoidNode", fingerprintStr)); 
            log.fine("TorConfig.writeToFile: will avoid node "+fingerprintStr);
        }
        // Functionality 
        config.append(writeInt("cacheMaxAgeSeconds",cacheMaxAgeSeconds));
        config.append(writeInt("startupDelaySeconds",startupDelaySeconds));
        config.append(writeInt("dirserverport",dirserverPort));
        config.append(writeInt("orport",orPort));
        config.append(writeString("nickname",nickname));

        // QoS parameters
        config.append(writeInt("RetriesConnect",retriesConnect));
        config.append(writeInt("RetriesStreamBuildup",retriesStreamBuildup));
        config.append(writeInt("ReconnectCircuit",reconnectCircuit));
        config.append(writeInt("DefaultIdleCircuits",defaultIdleCircuits));

        config.append(writeInt("QueueTimeoutCircuit",queueTimeoutCircuit));
        config.append(writeInt("QueueTimeoutResolve",queueTimeoutResolve));
        config.append(writeInt("QueueTimeoutStreamBuildup",queueTimeoutStreamBuildup));

        config.append(writeInt("CircuitClosesOnFailures",circuitClosesOnFailures));
        config.append(writeInt("circuitsMaximumNumber",circuitsMaximumNumber));
        
        config.append(writeBoolean("veryAggressiveStreamBuilding",veryAggressiveStreamBuilding));

        // FIXME: Check if this really works
        config.append(writeFloat("RankingTransferPerServerUpdate",rankingTransferPerServerUpdate));
        // directory parameters
        config.append(writeInt("DirectoryV1Refresh",intervalDirectoryV1Refresh));
        config.append(writeInt("DirectoryRefresh",intervalDirectoryRefresh));
        config.append(writeInt("MaxNumberOfDescriptorsFirstTime",dirV2ReadMaxNumberOfDescriptorsFirstTime));
        config.append(writeInt("MaxNumberOfDescriptorsPerUpdate",dirV2ReadMaxNumberOfDescriptorsPerUpdate));
        config.append(writeInt("dirV2ReloadRetries",dirV2ReloadRetries));
        config.append(writeInt("dirV2ReloadTimeout",dirV2ReloadTimeout));
        config.append(writeInt("dirV2DescriptorsPerBatch",dirV2DescriptorsPerBatch));

        FileWriter writer = new FileWriter(new File(filename));
        writer.write(config.toString());
        writer.close();

    } catch (IOException e) {
        log.warning("TorConfig.writeToFile(): Warning: " + e.getMessage());
    }
 
}
 
Example 27
Project: AndroidLibraryProject   File: CsvFileWriter.java View source code 5 votes vote down vote up
/**
 * Method to get the data from table and generate a csv file
 * @param tableName Table name for which you want to query the database
 * @param writer FileWriter object where data need to be written
 * @return int 1 if data successfully written on csv file, 0 if error
 */
public int getDataFromTable(String tableName, FileWriter writer)
{
	int success = 0;

	ContextAwareSQLiteHelper dbhelper = new ContextAwareSQLiteHelper(localContext);
	String data = null;
	try
	{ 
		// Need to be written in synchronized block to stop editing the same csv file from any other thread 
		synchronized(this) 
		{
			//Log.d("Debug",tableName);

			// Get the permission to read the database 
			SQLiteDatabase database = dbhelper.getReadableDatabase();
			//Log.d("Debug","PrevRowCount = " + prevRowCount);

			// Query to get the newly inserted data in the table
			String query = "select * from "+ tableName +" where id > " + prevRowCount;

			//To get the row count
			String queryForgetCount = " select * from  " + tableName ;

			// Execute the query 
			Cursor getcolumnCount = database.rawQuery(queryForgetCount, null);

			// Total number of rows in the selected table 
			totalRowCount = getcolumnCount.getCount();

			// Get the newly added rows in the table
			curCSV = database.rawQuery(query,null);//new String [] {checkCondition});

			curRowCount =  curCSV.getCount();
			prevRowCount = prevRowCount + curRowCount;
			//Log.d("Debug","CurRowCount = " + curRowCount+ "Total = " + totalRowCount);
			
			int i =0;
			
			int columnCount = curCSV.getColumnCount();
			
			while(curCSV.moveToNext())
			{
				if(tableName.equals("accelerometer"))
				{
					//One row, each column data delimited with "," in form of single string
					data = dataToWrite(curCSV.getInt(0),curCSV.getLong(1),curCSV.getFloat(2),curCSV.getFloat(3),curCSV.getFloat(4));
				}
				else if(tableName.equals("location"))
				{
					data = dataToWrite(curCSV.getInt(0),curCSV.getLong(1),curCSV.getFloat(2),curCSV.getFloat(3),curCSV.getFloat(4),curCSV.getString(5));
				}
				else if(tableName.equals("light"))
				{
					data = dataToWrite(curCSV.getInt(0),curCSV.getLong(1),curCSV.getFloat(2));
				}
				else if(tableName.equals("proximity"))
				{
					data = dataToWrite(curCSV.getInt(0),curCSV.getLong(1),curCSV.getFloat(2),curCSV.getFloat(3));
				}
				else if(tableName.equals("gyroscope"))
				{
					data = dataToWrite(curCSV.getInt(0),curCSV.getLong(1),curCSV.getFloat(2),curCSV.getFloat(3),curCSV.getFloat(4));
				}
				else
				{
					Log.d(TAG,"No table found");
				}
				// writeData(data, writer);
				writer.append(data+"\n");
				//Log.d("Debug","Data from cursor to write function");


			}
			//csvWrite.close();

			writer.flush();
			writer.close();
			curCSV.close();
			//Log.d(TAG,"Data correctly written in the csv file ");
			success =1;
		}
		return success;
	}
	catch(Exception sqlEx)
	{
		Log.e("ERROR in Simple  FileWriter", sqlEx.getMessage(), sqlEx);
		success= 0;
		return success;
	}
}
 
Example 28
Project: BioWiki   File: XMLRPCClient.java View source code 5 votes vote down vote up
public void preparePostMethod(String method, Object[] params, File tempFile) throws IOException, XMLRPCException, IllegalArgumentException, IllegalStateException {
    // prepare POST body
    if (method.equals("wp.uploadFile")) {

        if (!tempFile.exists() && !tempFile.mkdirs()) {
            throw new XMLRPCException("Path to file could not be created.");
        }

        FileWriter fileWriter = new FileWriter(tempFile);
        mSerializer.setOutput(fileWriter);

        mSerializer.startDocument(null, null);
        mSerializer.startTag(null, TAG_METHOD_CALL);
        // set method name
        mSerializer.startTag(null, TAG_METHOD_NAME).text(method).endTag(null, TAG_METHOD_NAME);
        if (params != null && params.length != 0) {
            // set method params
            mSerializer.startTag(null, TAG_PARAMS);
            for (int i = 0; i < params.length; i++) {
                mSerializer.startTag(null, TAG_PARAM).startTag(null, XMLRPCSerializer.TAG_VALUE);
                XMLRPCSerializer.serialize(mSerializer, params[i]);
                mSerializer.endTag(null, XMLRPCSerializer.TAG_VALUE).endTag(null, TAG_PARAM);
            }
            mSerializer.endTag(null, TAG_PARAMS);
        }
        mSerializer.endTag(null, TAG_METHOD_CALL);
        mSerializer.endDocument();

        fileWriter.flush();
        fileWriter.close();

        FileEntity fEntity = new FileEntity(tempFile, "text/xml; charset=\"UTF-8\"");
        fEntity.setContentType("text/xml");
        //fEntity.setChunked(true);
        mPostMethod.setEntity(fEntity);
    } else {
        StringWriter bodyWriter = new StringWriter();
        mSerializer.setOutput(bodyWriter);

        mSerializer.startDocument(null, null);
        mSerializer.startTag(null, TAG_METHOD_CALL);
        // set method name
        mSerializer.startTag(null, TAG_METHOD_NAME).text(method).endTag(null, TAG_METHOD_NAME);
        if (params != null && params.length != 0) {
            // set method params
            mSerializer.startTag(null, TAG_PARAMS);
            for (int i = 0; i < params.length; i++) {
                mSerializer.startTag(null, TAG_PARAM).startTag(null, XMLRPCSerializer.TAG_VALUE);
                if (method.equals("metaWeblog.editPost") || method.equals("metaWeblog.newPost")) {
                    XMLRPCSerializer.serialize(mSerializer, params[i]);
                } else {
                    XMLRPCSerializer.serialize(mSerializer, params[i]);
                }
                mSerializer.endTag(null, XMLRPCSerializer.TAG_VALUE).endTag(null, TAG_PARAM);
            }
            mSerializer.endTag(null, TAG_PARAMS);
        }
        mSerializer.endTag(null, TAG_METHOD_CALL);
        mSerializer.endDocument();

        HttpEntity entity = new StringEntity(bodyWriter.toString());
        //Log.i("WordPress", bodyWriter.toString());
        mPostMethod.setEntity(entity);
    }

    //set timeout to 30 seconds, does it need to be set for both mClient and method?
    mClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
    mClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
    mPostMethod.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
    mPostMethod.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
}
 
Example 29
Project: abiquo   File: TemplateFileSystem.java View source code 5 votes vote down vote up
/**
 * synch to avoid multiple changes on the package folder (before 'clearOVFStatusMarks').
 * 
 * @throws RepositoryException
 */
public static synchronized void createTemplateStatusMarks(
    final String enterpriseRepositoryPath, final String ovfId,
    final TemplateStatusEnumType status, final String errorMsg)
{
    final String packagePath = getTemplatePath(enterpriseRepositoryPath, ovfId);

    clearTemplateStatusMarks(packagePath);

    File mark = null;
    boolean errorCreate = false;
    try
    {
        switch (status)
        {
            case DOWNLOAD:
                // after clean the prev. marks, nothing to do.
                break;

            case NOT_DOWNLOAD: // once the OVF envelope (.ovf) is deleted its NOT_FOUND
                break;

            case DOWNLOADING:
                mark = new File(packagePath + '/' + TEMPLATE_STATUS_DOWNLOADING_MARK);
                errorCreate = !mark.createNewFile();
                break;

            case ERROR:
                mark = new File(packagePath + '/' + TEMPLATE_STATUS_ERROR_MARK);
                errorCreate = !mark.createNewFile();

                if (!errorCreate)
                {
                    FileWriter fileWriter = new FileWriter(mark);
                    fileWriter.append(errorMsg);
                    fileWriter.close();
                }
                break;

            default:
                throw new AMException(AMError.TEMPLATE_UNKNOW_STATUS, status.name());

        }// switch

    }
    catch (IOException ioe)
    {
        throw new AMException(AMError.TEMPLATE_CHANGE_STATUS, mark.getAbsoluteFile()
            .getAbsolutePath());
    }

    if (errorCreate)
    {
        throw new AMException(AMError.TEMPLATE_CHANGE_STATUS, mark.getAbsoluteFile()
            .getAbsolutePath());
    }
}