Java Code Examples for java.io.FileReader

The following are top voted examples for showing how to use java.io.FileReader. 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: SharkFW   File: FSPropertyHolder.java View source code 7 votes vote down vote up
static void restoreFromFile(HashMap<String,String> properties, String filename) 
        throws SharkKBException {
    
    try {
        FileReader fr = new FileReader(filename);
        BufferedReader reader = new BufferedReader(fr);
    
        String line = null;
        line = reader.readLine();
        
        // there is something - clean up properties
        properties.clear();
        while(line != null) {
            // split into name value
            
            // StringTokenizer didn't work - made it by my own.
            
            String name;
            String value;
            int indexDelimiter = line.indexOf(DELIMITER);
            if(indexDelimiter >= 0 && indexDelimiter <= line.length()  ) {
                name = line.substring(0, indexDelimiter);
                value = line.substring(indexDelimiter + DELIMITER.length());
                // store
                properties.put(name, value);
            }
            
            // take next line
            line = reader.readLine();
            
        }
        fr.close();
    } catch (FileNotFoundException ex) {
        // ignore
    } 
    catch(IOException ioe) {
        throw new SharkKBException("cannot read from file: " + ioe.getMessage()); 
    }
}
 
Example 2
Project: bonita-simulation   File: CSVSimReportStorage.java View source code 7 votes vote down vote up
private void copyFile(String filename) throws Exception {
	File outputFile = new File(filename+"copy.csv"); //$NON-NLS-1$
	if(!outputFile.exists()){ //$NON-NLS-1$
		File inputFile = new File(filename);
	
		FileReader in = new FileReader(inputFile);
		FileWriter out = new FileWriter(outputFile);
		int c;

		while ((c = in.read()) != -1)
			out.write(c);

		in.close();
		out.close();
	}
}
 
Example 3
Project: panovit   File: TestNamedPipe.java View source code 7 votes vote down vote up
public void run() {
    FileReader fr = null;
    try {
        fr = new FileReader(new File("/tmp/testpipe"));
        StringBuffer buf = new StringBuffer();
        int i = 0;
        while((i = fr.read()) > -1) {
            //System.out.println((char)i);
            buf.append((char)i);
            if (':' == (char)i) {
                break;
            }
        }
        System.out.println(buf.toString());
        quit();
    }
    catch (IOException ioe) {
        ioe.printStackTrace();
    }
    finally {
        try {
            if (fr != null) {
                fr.close();
            }
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
 
Example 4
Project: aipo   File: PopulateSampleIndices.java View source code 6 votes vote down vote up
public static void main(String args[])
{
    try
    {
        TurbineConfig config = null;
        
        config = new TurbineConfig( "./webapp", "/WEB-INF/conf/TurbineResources.properties");
        config.init();
                
        FileReader reader = new FileReader(SAMPLE_URLS);
        BufferedReader breader = new BufferedReader(reader);
        String line = null;
        System.out.println("================= Populate Sample Indices =================");
        System.out.println("... creates Search sample portlet test data from URLs provided in file: " + SAMPLE_URLS);
        System.out.println("...");                        
        
        while (null != (line = breader.readLine()))
        {
            System.out.println("Creating index for: " + line);
            URL url = new URL(line);
            
            Search.add(url);                        
        }
        System.out.println("===========================================================");
        
        reader.close();           
    }
    catch (Exception e)
    {
        System.out.println("Exception reading URLS" + e);
    }
}
 
Example 5
Project: eadventure   File: JsonReader.java View source code 6 votes vote down vote up
public <T> T fromJson(String file, Type type) {
	File f = new File(file);
	if (f.exists()) {
		FileReader reader = null;
		try {
			reader = new FileReader(file);
			T json = gson.fromJson(reader, type);
			return json;
		} catch (Exception e) {
			logger.error("Error in file: " + file, e);
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {

				}
			}
		}
	}
	return null;
}
 
Example 6
Project: liferay-apps-content-targeting   File: CTSampleSQLBuilder.java View source code 6 votes vote down vote up
public static void main(String[] args) {
	InitUtil.initWithSpring();

	Reader reader = null;

	try {
		Properties properties = new SortedProperties();

		reader = new FileReader(args[0]);

		properties.load(reader);

		DataFactory dataFactory = new CTDataFactory(properties);

		new CTSampleSQLBuilder(properties, dataFactory);
	}
	catch (Exception e) {
		e.printStackTrace();
	}
	finally {
		if (reader != null) {
			try {
				reader.close();
			}
			catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
	}
}
 
Example 7
Project: fiji   File: GenerateFFMPEGClasses.java View source code 6 votes vote down vote up
private static String readFile(final File path) throws IOException {
	FileReader reader = new FileReader(path);
	StringBuffer buf = new StringBuffer();
	char[] cBuf = new char[65536];
	for (;;) {
		int count = reader.read(cBuf);
		if (count < 0)
			break;
		buf.append(cBuf, 0, count);
	}
	reader.close();
	return buf.toString();
}
 
Example 8
Project: eclipse-integration-commons   File: FileUtil.java View source code 6 votes vote down vote up
public static String readFile(File sourceFile, IProgressMonitor monitor) throws CoreException {
	long length = sourceFile.length();
	if (length > MAX_FILE_SIZE) {
		throw new CoreException(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "File \"" + sourceFile
				+ "\" is too large"));
	}

	try {
		monitor.beginTask("Reading file", (int) length);

		FileReader in = new FileReader(sourceFile);
		try {
			StringBuilder sb = new StringBuilder((int) length);
			int len;
			char[] buffer = new char[BUFFER_SIZE];
			while ((len = in.read(buffer)) > 0) {
				Policy.checkCancelled(monitor);

				sb.append(buffer, 0, len);
				monitor.worked(len);
			}
			return sb.toString();
		}
		finally {
			in.close();
		}
	}
	catch (IOException e) {
		throw new CoreException(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Could not read file \""
				+ sourceFile + "\"", e));
	}
	finally {
		monitor.done();
	}
}
 
Example 9
Project: SOLR   File: QueryResponseTest.java View source code 6 votes vote down vote up
@Test
public void testDateFacets() throws Exception   {
  XMLResponseParser parser = new XMLResponseParser();
  FileReader in = new FileReader("sampleDateFacetResponse.xml");
  assertTrue("in is null and it shouldn't be", in != null);
  NamedList<Object> response = parser.processResponse(in);
  in.close();
  
  QueryResponse qr = new QueryResponse(response, null);
  Assert.assertNotNull(qr);
  
  Assert.assertNotNull(qr.getFacetDates());
  
  for (FacetField f : qr.getFacetDates()) {
    Assert.assertNotNull(f);
    System.out.println(f.toString());
    System.out.println("GAP: " + f.getGap());
    System.out.println("END: " + f.getEnd());
  }
}
 
Example 10
Project: visuwall   File: Rcc.java View source code 6 votes vote down vote up
public static JFile parseFile(File file) throws FileNotFoundException, ParseException {
    curDir = file.getParent();
    curFileName = file.getName();
    FileReader reader = new FileReader(file);
    try {
        Rcc parser = new Rcc(reader);
        recTab = new Hashtable();
        return parser.Input();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
        }
    }
}
 
Example 11
Project: Mastodon   File: ConfigPersister.java View source code 6 votes vote down vote up
public void load(File f) throws ConfigPersisterException {
	try {
		FileReader r = new FileReader(f);
		char[] buf = new char[(int) f.length()];
		r.read(buf);
    	r.close();
    	// Convert 2.x config to 3.x
    	String s = String.valueOf(buf)
    			.replaceAll("<headerType>0<", "<headerType>gui<")
    			.replaceAll("<headerType>1<", "<headerType>console<")
    			.replaceAll("jarArgs>", "cmdLine>")
    			.replaceAll("<jarArgs[ ]*/>", "<cmdLine/>")
    			.replaceAll("args>", "opt>")
    			.replaceAll("<args[ ]*/>", "<opt/>")
    			.replaceAll("<dontUsePrivateJres>false</dontUsePrivateJres>",
    					"<jdkPreference>" + Jre.JDK_PREFERENCE_PREFER_JRE + "</jdkPreference>")
    			.replaceAll("<dontUsePrivateJres>true</dontUsePrivateJres>",
    					"<jdkPreference>" + Jre.JDK_PREFERENCE_JRE_ONLY + "</jdkPreference>")
    			.replaceAll("<initialHeapSize>0</initialHeapSize>", "")
    			.replaceAll("<maxHeapSize>0</maxHeapSize>", "");
    	_config = (Config) _xstream.fromXML(s);
    	setConfigPath(f);
	} catch (Exception e) {
		throw new ConfigPersisterException(e);
	}
}
 
Example 12
Project: Katari   File: HibernateUtilsTest.java View source code 6 votes vote down vote up
public void testMain() throws Exception {
  HibernateUtils.main(new String[] {
    "classpath:/com/globant/katari/tools/applicationContext.xml",
      "target/test.ddl"});

  // Open the file and check for 'create table ...
  FileReader in = new FileReader("target/test.ddl");
  char[] buffer = new char[4096];
  in.read(buffer, 0, 4096);
  String file = new String(buffer);

  assertTrue(file.contains("create table clients ("));
  assertTrue(file.contains("create table projects ("));
  assertTrue(file.contains("create table activities ("));

  in.close();
}
 
Example 13
Project: Earmouse   File: Module.java View source code 6 votes vote down vote up
/**
 * Constructs a Module by reading a JSON from the given filename
 * @param context The application context
 * @param moduleFile The File from which to read the JSON data
 */
public Module (Context context, File moduleFile) {
	mCtx = context;
	try {
		FileInputStream fis = new FileInputStream(moduleFile);
		FileReader filereader = new FileReader(fis.getFD());
		initModuleFromJson(filereader);
		filereader.close();
		fis.close();
	} catch (IOException e) {
		e.printStackTrace();

       }
	stats = new ModuleStats(mCtx, id);
}
 
Example 14
Project: slumdroid   File: Tools.java View source code 6 votes vote down vote up
/**
 * Merge.
 *
 * @param xml the xml
 * @param dir the dir
 */
private void merge(String xml, String dir) {
	int count = 0;
	boolean session_found = false;
	try{
		File fl[] = new Tools().dirListByAscendingDate( new File(dir) );
		if (fl.length > 0){
			FileWriter outFile = new FileWriter(xml, false);
			PrintWriter out = new PrintWriter(outFile);	
			for (File f : fl) {
				FileReader inFile = new FileReader(f); 
				BufferedReader in = new BufferedReader(inFile);
				String s = null; 
				while((s = in.readLine()) != null) {
					if (!s.equals("")) {
						count++;
						if (s.contains("</SESSION>")) {
							session_found = true;
						}
						out.println(s);
					}
				}
				inFile.close(); 
			}
			if (!session_found) {
				out.println("</SESSION>");
			}
			out.close();
		}
	} catch (Exception e){
		e.printStackTrace();
	}
	if (count == 0) {
		new File(xml).delete();
	}
}
 
Example 15
Project: BambooPlayer   File: VitamioInstaller.java View source code 6 votes vote down vote up
public static boolean isNativeLibsInited(Context context) {
	String packageName = context.getPackageName();
	File dir = new File(VitamioInstaller.getLibraryPath(packageName));
	if (dir.exists() && dir.isDirectory()) {
		String[] libs = dir.list();
		if (libs != null) {
			Arrays.sort(libs);
			for (String L : LIBS) {
				if (Arrays.binarySearch(libs, L) < 0) {
					return false;
				}
			}
			File lock = new File(getLibraryPath(packageName) + "/inited.lock");
			FileReader fr = null;
			try {
				fr = new FileReader(lock);
				int appVersion = getVersionCode(context);
				int libVersion = fr.read();
				if (libVersion == appVersion)
					return true;
			} catch (IOException e) {
			} finally {
				closeSilently(fr);
			}
		}
	}
	return false;
}
 
Example 16
Project: freemind-mmx   File: RevertAction.java View source code 6 votes vote down vote up
public RevertXmlAction createRevertXmlAction(File file) throws IOException {
	String fileName = file.getAbsolutePath();
	FileReader f = new FileReader(file);
	StringBuffer buffer = new StringBuffer();
	for (int c; (c = f.read()) != -1;)
		buffer.append((char) c);
	f.close();
	return createRevertXmlAction(buffer.toString(), fileName, null);
}
 
Example 17
Project: Desktop   File: FileUtils.java View source code 6 votes vote down vote up
public static String slurpFile(final File file) throws IOException {
	FileReader in = null;
	try {
		in = new FileReader(file);
		final StringBuilder builder = new StringBuilder();
		final char[] buf = new char[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			builder.append(buf, 0, len);
		}
		final String result = builder.toString();
		return result;
	}
	finally {
		if (in != null) {
			in.close();
		}
	}
}
 
Example 18
Project: word2vec-lucene   File: Text8Splitter.java View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  if(args.length != 2) usage();
  
  final String fin = args[0];
  final String fout = args[1];

  Reader r = null;
  PrintStream ps = null;
  try{
    r = new FileReader(fin);
    ps = new PrintStream(fout);
    int c = r.read();
    int counter = 0;
    while(c != -1){
      ps.print((char)c);
      if(c == ' '){
        if(++counter >= MAX_WORDS){
          counter = 0;
          ps.println();   // print CR
        }
      }
      c = r.read();
    }
  }
  finally{
    IOUtils.closeQuietly(r);
    IOUtils.closeQuietly(ps);
  }
  
}
 
Example 19
Project: HDP-2.2-Patched   File: TestNativeIO.java View source code 6 votes vote down vote up
@Test (timeout = 30000)
public void testSetFilePointer() throws Exception {
  if (!Path.WINDOWS) {
    return;
  }

  LOG.info("Set a file pointer on Windows");
  try {
    File testfile = new File(TEST_DIR, "testSetFilePointer");
    assertTrue("Create test subject",
        testfile.exists() || testfile.createNewFile());
    FileWriter writer = new FileWriter(testfile);
    try {
      for (int i = 0; i < 200; i++)
        if (i < 100)
          writer.write('a');
        else
          writer.write('b');
      writer.flush();
    } catch (Exception writerException) {
      fail("Got unexpected exception: " + writerException.getMessage());
    } finally {
      writer.close();
    }

    FileDescriptor fd = NativeIO.Windows.createFile(
        testfile.getCanonicalPath(),
        NativeIO.Windows.GENERIC_READ,
        NativeIO.Windows.FILE_SHARE_READ |
        NativeIO.Windows.FILE_SHARE_WRITE |
        NativeIO.Windows.FILE_SHARE_DELETE,
        NativeIO.Windows.OPEN_EXISTING);
    NativeIO.Windows.setFilePointer(fd, 120, NativeIO.Windows.FILE_BEGIN);
    FileReader reader = new FileReader(fd);
    try {
      int c = reader.read();
      assertTrue("Unexpected character: " + c, c == 'b');
    } catch (Exception readerException) {
      fail("Got unexpected exception: " + readerException.getMessage());
    } finally {
      reader.close();
    }
  } catch (Exception e) {
    fail("Got unexpected exception: " + e.getMessage());
  }
}
 
Example 20
Project: bigpetstore   File: TestHardLink.java View source code 6 votes vote down vote up
private String fetchFileContents(File file) 
throws IOException {
  char[] buf = new char[20];
  FileReader fr = new FileReader(file);
  int cnt = fr.read(buf); 
  fr.close();
  char[] result = Arrays.copyOf(buf, cnt);
  return new String(result);
}
 
Example 21
Project: jgit   File: T0003_BasicTest.java View source code 6 votes vote down vote up
@Test
public void test006_ReadUglyConfig() throws IOException,
		ConfigInvalidException {
	final File cfg = new File(db.getDirectory(), Constants.CONFIG);
	final FileBasedConfig c = new FileBasedConfig(cfg, db.getFS());
	final String configStr = "  [core];comment\n\tfilemode = yes\n"
			+ "[user]\n"
			+ "  email = A U Thor <[email protected]> # Just an example...\n"
			+ " name = \"A  Thor \\\\ \\\"\\t \"\n"
			+ "    defaultCheckInComment = a many line\\n\\\ncomment\\n\\\n"
			+ " to test\n";
	write(cfg, configStr);
	c.load();
	assertEquals("yes", c.getString("core", null, "filemode"));
	assertEquals("A U Thor <[email protected]>", c.getString("user", null,
			"email"));
	assertEquals("A  Thor \\ \"\t ", c.getString("user", null, "name"));
	assertEquals("a many line\ncomment\n to test", c.getString("user",
			null, "defaultCheckInComment"));
	c.save();
	final FileReader fr = new FileReader(cfg);
	final char[] cbuf = new char[configStr.length()];
	fr.read(cbuf);
	fr.close();
	assertEquals(configStr, new String(cbuf));
}
 
Example 22
Project: ecologylabFundamental   File: BibTeXParser.java View source code 6 votes vote down vote up
void testParser2() throws IOException, BibTeXFormatException, SIMPLTranslationException
{
	FileReader fr = new FileReader("C:/tmp/iis10.bib");
	StringBuilder sb = new StringBuilder();
	char[] buf = new char[4096];
	while (true)
	{
		int len = fr.read(buf);
		if (len < 0)
			break;
		sb.append(buf, 0, len);
	}

	List<AbstractBibTeXEntry> entities = parse(sb.toString().toCharArray());
	for (AbstractBibTeXEntry entity : entities)
	{
		SimplTypesScope.serialize(entity, System.out, StringFormat.XML);
		System.out.println();
		// entity.serialize(System.out, FORMAT.BIBTEX);
	}
}
 
Example 23
Project: cyberduck   File: Connection.java View source code 6 votes vote down vote up
/**
 * A convenience wrapper function which reads in a private key (PEM format, either DSA or RSA)
 * and then calls <code>authenticateWithPublicKey(String, char[], String)</code>.
 * <p>
 * NOTE PUTTY USERS: Event though your key file may start with "-----BEGIN..."
 * it is not in the expected format. You have to convert it to the OpenSSH
 * key format by using the "puttygen" tool (can be downloaded from the Putty
 * website). Simply load your key and then use the "Conversions/Export OpenSSH key"
 * functionality to get a proper PEM file.
 * 
 * @param user
 *            A <code>String</code> holding the username.
 * @param pemFile
 *            A <code>File</code> object pointing to a file containing a DSA or RSA
 *            private key of the user in OpenSSH key format (PEM, you can't miss the
 *            "-----BEGIN DSA PRIVATE KEY-----" or "-----BEGIN RSA PRIVATE KEY-----"
 *            tag).
 * @param password
 *            If the PEM file is encrypted then you must specify the password.
 *            Otherwise, this argument will be ignored and can be set to <code>null</code>.
 * 
 * @return whether the connection is now authenticated.
 * @throws IOException
 */
public synchronized boolean authenticateWithPublicKey(String user, File pemFile, String password)
		throws IOException
{
	if (pemFile == null)
		throw new IllegalArgumentException("pemFile argument is null");

	char[] buff = new char[256];

	CharArrayWriter cw = new CharArrayWriter();

	FileReader fr = new FileReader(pemFile);

	while (true)
	{
		int len = fr.read(buff);
		if (len < 0)
			break;
		cw.write(buff, 0, len);
	}

	fr.close();

	return authenticateWithPublicKey(user, cw.toCharArray(), password);
}
 
Example 24
Project: tr069   File: TestServlet.java View source code 6 votes vote down vote up
public static String getContent(File f, String deviceType) throws IOException {
	FileReader fr = new FileReader(f);
	char[] contentArr = new char[100000];
	fr.read(contentArr);
	String content = new String(contentArr);
	int endOfXmlPos = content.indexOf("</cwmp");
	endOfXmlPos = content.indexOf(">", endOfXmlPos) + 1;
	content = content.substring(0, endOfXmlPos);
	String xml = content.substring(content.indexOf("<cwmp"));
	for (int i = 1; i < 100; i++) {
		if (xml.indexOf("$VAR" + i) > -1) {
			int varPos = content.indexOf(deviceType + i);
			int eqPos = content.indexOf("=", varPos);
			int nlPos = content.indexOf("\n", eqPos);
			String var = content.substring(eqPos + 1, nlPos).trim();
			xml = xml.replace("$VAR" + i, var);
		} else
			break;
	}
	fr.close();
	return xml;
}
 
Example 25
Project: teiid-designer   File: DdlImporter.java View source code 6 votes vote down vote up
void importDdl(FileReader reader, IProgressMonitor monitor, int totalWork, Properties options) throws Exception {
	ddlString = null;
	importManager.getImportMessages().clear();

    // ------------------------------------------------------------------------------
    // Parse the DDL from the file
    // ------------------------------------------------------------------------------
    monitor.subTask(DdlImporterI18n.PARSING_DDL_MSG);
    // Read the file contents
    char[] buf = new char[FileUtils.DEFAULT_BUFFER_SIZE];
    StringBuilder builder = new StringBuilder();
    for (int charTot = reader.read(buf); charTot >= 0; charTot = reader.read(buf))
        builder.append(buf, 0, charTot);

    importDdl(builder.toString(), monitor, totalWork, options);
}
 
Example 26
Project: yarn-comment   File: TestHardLink.java View source code 6 votes vote down vote up
private String fetchFileContents(File file) 
throws IOException {
  char[] buf = new char[20];
  FileReader fr = new FileReader(file);
  int cnt = fr.read(buf); 
  fr.close();
  char[] result = Arrays.copyOf(buf, cnt);
  return new String(result);
}
 
Example 27
Project: ArubaSyslog   File: PPEFilter.java View source code 5 votes vote down vote up
public static void main(String[] args) throws IOException{
	
   	// Initial options
       String input_file_location = "";
       String output_file_location = "";
       
       // fetch command line options 
       int optSetting = 0;  
       for (; optSetting < args.length; optSetting++) {  
           if ("-i".equals(args[optSetting])) {  
               input_file_location = args[++optSetting];  
           } else if ("-o".equals(args[optSetting])) {  
               output_file_location = args[++optSetting];  
           }
       }

       if(input_file_location.length() == 0 || output_file_location.length() == 0) {
           System.out.println("Usage: PPEFilter -i <source> -o <destination>");
           System.exit(-1);
       }
       
       // prepare for reading files one by one
 		File input_folder = null;  
 		input_folder = new File(input_file_location);  
 		File[] files = input_folder.listFiles(); 
 		
 		// String input_file_path = "";
 		String uid = "";
 		String input_file_name = "";
 		String output_file = "";
 		
 		// Skip invalid files without name format \d+.mv
 		String filename_regex = "[\\d\\w.]+.mv$";
 		Pattern p = Pattern.compile(filename_regex);
 		Matcher m = null;
	
 		for (File input_file : files) {
 			
 			// extract input_file_name as output_file_name
 			// input_file_path = input_file.getAbsolutePath();
 		    input_file_name = input_file.getName();
 		    
 		    // Skip invalid files without name format \d+.mv
 		    m = p.matcher(input_file_name);
 		    if ( m.find() == false)
 		    	continue;
 		    
 		    uid = input_file_name.split("\\.")[0];
 		    output_file = output_file_location + uid;
 		    
 		    // Input stream
 			FileReader ifr = new FileReader(input_file);
 			BufferedReader ibr = new BufferedReader(ifr);
 			
 			// Create parent directories if they are not available.
 			File output_folder = new File(output_file_location);
 			if ( !output_folder.exists() )
 				output_folder.mkdirs();
 			
 			// Output stream
 			File file = new File(output_file);	
           if(!file.exists()) {
               if(!file.createNewFile()) {
               	System.out.println("Can't create file.");
               }
           }
           
 			FileWriter ofr = new FileWriter(file);
 			BufferedWriter obr = new BufferedWriter(ofr);
 			
 			// Processing one file for a user
 			String line ="";
 			String [] ap_info;
 			ConvSession cs = null;
 			
 			while ((line = ibr.readLine()) != null) {
			
 				line = line.replaceAll("[\\n\\r]*","");
 				
 				// Read the conversation sessions
 				// Each session ends with "OFF" flag.
 				// Each file will be split into sessions as 
 				// count of "OFF"'s
 				if ( cs == null )
 					cs = new ConvSession(uid);
			ap_info = line.split("\\t");
			
			if ( ap_info[1].equals("OFF") == false && ibr.ready() == true) {
				// If the last line is without OFF
				// Add a fake OFF signs to the session records
				cs.addRecord(Long.parseLong(ap_info[0]), ap_info[1]);
				continue;
			}
			cs.addRecord(Long.parseLong(ap_info[0]), "OFF");
			
			// Filter the Ping-Pong Effect on the basis of each session,
			// and write the new session into an output file.
			List<APRecord> final_records = cs.removePingPongEffect();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			TimeZone tz = TimeZone.getTimeZone("GMT-04:00");	//New York timezone
			df.setTimeZone(tz);
			
			for ( APRecord r : final_records) {
				Date start = new Date(r.start_time*1000);
				Date end = new Date((r.start_time+r.duration)*1000);
				obr.write(r.name+"\t"+df.format(start)+"\t"+r.duration+"\t"+df.format(end)+"\n");
				//System.out.println(r.name+"\t"+r.start_time+"\t"+r.duration);
			}
			//obr.write("OFF\n");
			
			// Reset to start a new session
			cs = null;
 			}
		
 			ibr.close();
 			ifr.close();
		obr.close();
		ofr.close();
 		}
}
 
Example 28
Project: modern-jogl-examples   File: DepthPeelingGL2.java View source code 5 votes vote down vote up
private void loadModel(GL2 gl2) throws FileNotFoundException, IOException, URISyntaxException {
        System.out.println("loadModel..");
        triangles = new ArrayList<>();

//        FileReader fileReader = new FileReader(new File(filename));
        FileReader fileReader = new FileReader(new File(getClass().getResource(filename).toURI()));
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String line = "";
        int pointer;
        String values[];
        float[] data = new float[12];
        pointer = 0;

        for (int i = 0; i < 3; i++) {
            min[i] = Float.MAX_VALUE;
            max[i] = Float.MIN_VALUE;
        }

        while ((line = bufferedReader.readLine()) != null) {

            line = line.trim().toLowerCase();

            // Read normals
            if (line.startsWith("facet")) {
                values = line.split(" ");
                for (int i = 2; i < values.length; i++) {
                    if (!values[i].isEmpty()) {
                        data[pointer + 9] = Float.parseFloat(values[i]);
                        pointer++;
                    }
                }
            }

            // Read points
            if (line.startsWith("vertex")) {
                values = line.split(" ");
                for (int i = 1; i < values.length; i++) {
                    if (!values[i].isEmpty()) {
                        data[pointer - 3] = Float.parseFloat(values[i]);
                        pointer++;
                    }
                }
            }

            if (pointer == 12) {
                for (int i = 0; i < 3; i++) {
                    min[i] = Math.min(data[i], min[i]);
                    min[i] = Math.min(data[i + 3], min[i]);
                    min[i] = Math.min(data[i + 6], min[i]);

                    max[i] = Math.max(data[i], max[i]);
                    max[i] = Math.max(data[i + 3], max[i]);
                    max[i] = Math.max(data[i + 6], max[i]);
                }
                pointer = 0;

                float t[] = new float[12];
                System.arraycopy(data, 0, t, 0, 12);
                triangles.add(t);
            }
        }

        bufferedReader.close();
        fileReader.close();

        createVBO(gl2, triangles);
    }
 
Example 29
Project: android-platform-tools-base   File: MergerTest.java View source code 5 votes vote down vote up
public void testCombinedParameters()
        throws IOException, ManifestMerger2.MergeFailureException {

    File outFile = File.createTempFile("test", "merger");

    final String[] args = { "--main", "src/main/AndroidManifest.xml",
            "--libs", "src/lib1/AndroidManifest.xml" + File.pathSeparator
                + "src/lib2/AndroidManifest.xml" + File.pathSeparator
                + "src/lib3/AndroidManifest.xml",
            "--overlays", "src/flavor1/AndroidManifest.xml" + File.pathSeparator
                + "src/flavor2/AndroidManifest.xml" + File.pathSeparator
                + "src/flavor3/AndroidManifest.xml",
            "--placeholder", "Foo=bar",
            "--property", "max_sdk_version=21",
            "--out", outFile.getAbsolutePath()};
    Merger merger = new MergerWithMock() {
        @Override
        protected ManifestMerger2.Invoker createInvoker(File mainManifestFile, ILogger logger) {
            try {
                XmlDocument xmlDocument = Mockito.mock(XmlDocument.class);
                when(mMergingReport.getResult()).thenReturn(MergingReport.Result.SUCCESS);
                when(mMergingReport.getMergedDocument()).thenReturn(Optional.of(xmlDocument));
                when(xmlDocument.prettyPrint()).thenReturn("Pretty combined");
                when(mInvoker.merge()).thenReturn(mMergingReport);
            } catch (ManifestMerger2.MergeFailureException e) {
                fail(e.getMessage());
            }
            return mInvoker;
        }
    };
    merger.process(args);
    verify(mInvoker).addLibraryManifest(new File("src/lib1/AndroidManifest.xml"));
    verify(mInvoker).addLibraryManifest(new File("src/lib2/AndroidManifest.xml"));
    verify(mInvoker).addLibraryManifest(new File("src/lib3/AndroidManifest.xml"));
    verify(mInvoker).addFlavorAndBuildTypeManifest(new File("src/flavor1/AndroidManifest.xml"));
    verify(mInvoker).addFlavorAndBuildTypeManifest(new File("src/flavor2/AndroidManifest.xml"));
    verify(mInvoker).addFlavorAndBuildTypeManifest(new File("src/flavor3/AndroidManifest.xml"));
    verify(mInvoker).setOverride(ManifestMerger2.SystemProperty.MAX_SDK_VERSION, "21");
    verify(mInvoker).setPlaceHolderValue("Foo", "bar");
    verify(mInvoker).merge();
    verifyNoMoreInteractions(mInvoker);

    // check the resulting file content.
    FileReader fileReader = null;
    try {
        fileReader = new FileReader(outFile);
        CharBuffer buffer = CharBuffer.allocate(256);
        fileReader.read(buffer);
        int endOfRead = buffer.position();
        assertEquals("Pretty combined", buffer.rewind().toString().substring(0, endOfRead));
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
    }
    assertTrue(outFile.delete());
}