List of usage examples for java.io FileReader close
public void close() throws IOException
From source file:org.gvnix.web.menu.roo.addon.MenuEntryOperationsImpl.java
/** * Creates or updates the contents for one resource represented by the given * target file path and relative source path. * /*from www .ja v a2 s . c om*/ * @param relativePath path relative to {@link Path.SRC_MAIN_WEBAPP} of * target file * @param resourceName path relative to classpath of file to be copied * (cannot be null) * @param toReplace * @param containsStrings */ private void installResourceIfNeeded(String relativePath, String resourceName, Map<String, String> toReplace, String[] containsStrings) { PathResolver pathResolver = getPathResolver(); String targetPath = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), relativePath); InputStream resource = getClass().getResourceAsStream(resourceName); String sourceContents; String targetContents = null; // load resource to copy try { sourceContents = IOUtils.toString(new InputStreamReader(resource)); // Replace params if (toReplace != null) { for (Entry<String, String> entry : toReplace.entrySet()) { sourceContents = StringUtils.replace(sourceContents, entry.getKey(), entry.getValue()); } } } catch (IOException e) { throw new IllegalStateException("Unable to load file to be copied '".concat(resourceName).concat("'"), e); } finally { try { resource.close(); } catch (IOException e) { e.printStackTrace(); } } // load target contents if exists if (fileManager.exists(targetPath)) { FileReader reader = null; try { reader = new FileReader(targetPath); targetContents = IOUtils.toString(reader); } catch (Exception e) { throw new IllegalStateException("Error reading '".concat(targetPath).concat("'"), e); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } } // prepare mutable file // use MutableFile in combination with FileManager to take advantage of // Roos transactional file handling which offers automatic rollback if // an // exception occurs MutableFile target = null; if (targetContents == null) { target = fileManager.createFile(targetPath); } else { // decide if need to replace target if (containsStrings == null || containsStrings.length == 0) { // No checks to do target = fileManager.updateFile(targetPath); } else { for (String contains : containsStrings) { if (!targetContents.contains(contains)) { target = fileManager.updateFile(targetPath); break; } } } } if (target == null) { return; } try { InputStream inputStream = null; OutputStreamWriter outputStream = null; try { inputStream = IOUtils.toInputStream(sourceContents); outputStream = new OutputStreamWriter(target.getOutputStream()); IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } catch (IOException e) { throw new IllegalStateException("Unable to create/update '".concat(targetPath).concat("'"), e); } }
From source file:corelyzer.data.CRPreferences.java
public boolean readDisplayConfig(final File aFile) { // read the file and loadin setups try {/*from ww w. jav a 2 s . co m*/ FileReader fr = new FileReader(aFile); BufferedReader br = new BufferedReader(fr); String line; line = br.readLine(); this.screenWidth = new Integer(line); line = br.readLine(); this.screenHeight = new Integer(line); line = br.readLine(); this.numberOfRows = new Integer(line); line = br.readLine(); this.numberOfColumns = new Integer(line); line = br.readLine(); this.dpix = new Float(line); line = br.readLine(); this.dpiy = new Float(line); line = br.readLine(); this.borderUp = new Float(line); line = br.readLine(); this.borderDown = new Float(line); line = br.readLine(); this.borderLeft = new Float(line); line = br.readLine(); this.borderRight = new Float(line); try { line = br.readLine(); this.column_offset = new Integer(line); line = br.readLine(); this.row_offset = new Integer(line); } catch (NumberFormatException e) { System.out.println("[CRPreferences] Ignore rest display.conf"); } br.close(); fr.close(); return true; } catch (Exception e) { System.out.println("ERROR Reading previous display settings"); e.printStackTrace(); return false; } }
From source file:org.clipsmonitor.core.MonitorGenMap.java
@SuppressWarnings("UnnecessaryUnboxing") private void LoadJsonMap(File jsonFile) throws ParseException { //creo una nuova istanza di scena try {/* ww w . j a v a 2s . c o m*/ //converto il file in un oggetto JSON FileReader jsonreader = new FileReader(jsonFile); char[] chars = new char[(int) jsonFile.length()]; jsonreader.read(chars); String jsonstring = new String(chars); jsonreader.close(); JSONObject json = new JSONObject(jsonstring); //leggo il numero di celle dalla radice del JSON int NumCellX = Integer.parseInt(json.get("cell_x").toString()); int NumCellY = Integer.parseInt(json.get("cell_y").toString()); SetNumCell(NumCellX, NumCellY); SetSizeCells(); //imposto la dimensione iniziale della scena scene = new String[NumCellX][NumCellY]; //initScene(scene); move = clone(scene); //estraggo il JSONArray dalla radice JSONArray arrayCelle = json.getJSONArray("cells"); for (int i = 0; i < arrayCelle.length(); i++) { //ciclo su ogni cella e setto il valore della cella letta nella scena JSONObject cell = arrayCelle.getJSONObject(i); int x = cell.getInt("x"); int y = cell.getInt("y"); String state = cell.getString("state"); setCell(x, y, state); } CopyToActive(scene); } catch (JSONException ex) { AppendLogMessage(ex.getMessage(), "error"); } catch (IOException ex) { AppendLogMessage(ex.getMessage(), "error"); } catch (NumberFormatException ex) { AppendLogMessage(ex.getMessage(), "error"); } }
From source file:org.clipsmonitor.core.MonitorGenMap.java
public void LoadMoves(File jsonFile) throws ParseException { try {//from www . j av a 2 s . c o m //converto il file in un oggetto JSON FileReader jsonreader = new FileReader(jsonFile); char[] chars = new char[(int) jsonFile.length()]; jsonreader.read(chars); String jsonstring = new String(chars); jsonreader.close(); JSONObject json = new JSONObject(jsonstring); Persons = new LinkedList<Person>(); //estraggo il JSONArray dalla radice JSONArray arrayPersons = json.getJSONArray("personList"); for (int i = 0; i < arrayPersons.length(); i++) { JSONObject person = arrayPersons.getJSONObject(i); String color = person.getString("color"); Person p = new Person(color); JSONArray arrayPaths = person.getJSONArray("paths"); for (int j = 0; j < arrayPaths.length(); j++) { JSONObject path = arrayPaths.getJSONObject(j); String pathName = path.getString("name"); int startStep = path.getInt("startStep"); int lastStep = path.getInt("lastStep"); p.paths.add(new Path(pathName, startStep, lastStep)); JSONArray arrayMoves = path.getJSONArray("moves"); for (int k = 0; k < arrayMoves.length(); k++) { JSONObject move = arrayMoves.getJSONObject(k); int x = move.getInt("x"); int y = move.getInt("y"); int step = move.getInt("step"); p.paths.getLast().move.add(new StepMove(x, y, step)); } } Persons.add(p); } maxduration = json.getInt("time"); } catch (JSONException ex) { AppendLogMessage(ex.getMessage(), "error"); } catch (IOException ex) { AppendLogMessage(ex.getMessage(), "error"); } catch (NumberFormatException ex) { AppendLogMessage(ex.getMessage(), "error"); } }
From source file:org.kuali.kfs.gl.document.service.impl.CorrectionDocumentServiceImpl.java
/** * Reads a file of origin entries and returns a List of those entry records * //from ww w .j a v a2s .c o m * @param fullPathUniqueFileName the file name of the file to read * @param abortThreshold if more entries than this need to be read...well, they just won't get read * @return a List of OriginEntryFulls */ protected List<OriginEntryFull> retrievePersistedOriginEntries(String fullPathUniqueFileName, int abortThreshold) { File fileIn = new File(fullPathUniqueFileName); if (!fileIn.exists()) { LOG.error("File " + fullPathUniqueFileName + " does not exist."); throw new RuntimeException("File does not exist"); } BufferedReader reader = null; FileReader fReader = null; List<OriginEntryFull> entries = new ArrayList<OriginEntryFull>(); int lineNumber = 0; try { fReader = new FileReader(fileIn); reader = new BufferedReader(fReader); String line; while ((line = reader.readLine()) != null) { OriginEntryFull entry = new OriginEntryFull(); entry.setFromTextFileForBatch(line, lineNumber); if (abortThreshold != UNLIMITED_ABORT_THRESHOLD && lineNumber >= abortThreshold) { return null; } lineNumber++; entries.add(entry); } } catch (IOException e) { LOG.error("retrievePersistedOriginEntries() Error reading file " + fileIn.getAbsolutePath(), e); throw new RuntimeException("Error reading file"); } finally { try { if (fReader != null) { fReader.close(); } if (reader != null) { reader.close(); } } catch (IOException e) { LOG.error("Unable to close file " + fileIn.getAbsolutePath(), e); throw new RuntimeException("Error closing file"); } } return entries; }
From source file:com.apifest.doclet.integration.tests.DocletTest.java
@Test public void when_doclet_run_outputs_tags() throws ParseException, IOException { // GIVEN/* w w w. j a va 2s . c o m*/ String parserFilePath = "./all-mappings-docs.json"; // WHEN runDoclet(); // THEN JSONParser parser = new JSONParser(); FileReader fileReader = null; try { fileReader = new FileReader(parserFilePath); JSONObject json = (JSONObject) parser.parse(fileReader); String version = (String) json.get("version"); JSONArray arr = (JSONArray) json.get("endpoints"); JSONObject obj = (JSONObject) arr.get(1); JSONObject obj1 = (JSONObject) arr.get(0); Assert.assertEquals(version, "v1"); Assert.assertEquals(obj.get("group"), "Twitter Followers"); Assert.assertEquals(obj.get("scope"), "twitter_followers"); Assert.assertEquals(obj.get("method"), "GET"); Assert.assertEquals(obj.get("endpoint"), "/v1/twitter/followers/metrics"); Assert.assertEquals(obj.get("description"), null); Assert.assertEquals(obj.get("summary"), null); Assert.assertEquals(obj.get("paramsDescription"), null); Assert.assertEquals(obj.get("resultsDescription"), null); Assert.assertEquals(obj1.get("group"), "Twitter Followers"); Assert.assertEquals(obj1.get("scope"), "twitter_followers"); Assert.assertEquals(obj1.get("method"), "GET"); Assert.assertEquals(obj1.get("endpoint"), "/v1/twitter/followers/stream"); Assert.assertNotEquals(obj1.get("description"), null); Assert.assertNotEquals(obj1.get("summary"), null); Assert.assertEquals(obj1.get("paramsDescription"), "** Parameter description is going here!**"); Assert.assertEquals(obj1.get("resultsDescription"), "** Result description is the best! **"); } finally { if (fileReader != null) { fileReader.close(); } deleteJsonFile(parserFilePath); } }
From source file:fsi_admin.admon.JAyudaPaginaDlg.java
private void GenerarAyudaReportes(String path, String pagina_final, String interfaz, String color) throws IOException { //carga el archivo de ayuda que contienen la plantilla completa String ps = ""; FileReader file = new FileReader("/usr/local/forseti/bin/forseti_doc/estructura_reportes.html"); BufferedReader buff = new BufferedReader(file); boolean eof = false; while (!eof) { String line = buff.readLine(); if (line == null) eof = true;/*from ww w .ja v a 2 s. c om*/ else ps += line + "\n"; } buff.close(); file.close(); buff = null; file = null; // extrae el inicio de la plantilla int fin_index = ps.indexOf("<!--_ini_datos_cabecero-->"); String p_inicio = ps.substring(0, fin_index); // extrae los datos del cabecero int ini_index = fin_index + 26; fin_index = ps.indexOf("<!--_fin_datos_cabecero-->"); String p_cabecero = ps.substring(ini_index, fin_index); //extrae inicio de cabecero ini_index = 0; fin_index = p_cabecero.indexOf("<!--_ini_titulo_cabecero-->"); String p_ini_datos_cabecero = p_cabecero.substring(ini_index, fin_index); //Extrae titulo del cabecero ini_index = fin_index + 27; fin_index = p_cabecero.indexOf("<!--_fin_titulo_cabecero-->"); String p_titulo_cabecero = p_cabecero.substring(ini_index, fin_index); //Extrae columnas del cabecero ini_index = p_cabecero.indexOf("<!--_ini_columnas_cabecero-->") + 29; fin_index = p_cabecero.indexOf("<!--_fin_columnas_cabecero-->"); String p_columnas_cabecero = p_cabecero.substring(ini_index, fin_index); //extrae final de cabecero ini_index = fin_index + 29; String p_fin_datos_cabecero = p_cabecero.substring(ini_index); // extrae los datos del filtro ini_index = ps.indexOf("<!--_ini_datos_filtro-->") + 24; fin_index = ps.indexOf("<!--_fin_datos_filtro-->"); String p_filtro = ps.substring(ini_index, fin_index); //extrae inicio de filtro ini_index = 0; fin_index = p_filtro.indexOf("<!--_ini_titulo_filtro-->"); String p_ini_datos_filtro = p_filtro.substring(ini_index, fin_index); //Extrae titulo del filtro ini_index = fin_index + 25; fin_index = p_filtro.indexOf("<!--_fin_titulo_filtro-->"); String p_titulo_filtro = p_filtro.substring(ini_index, fin_index); //Extrae columnas del filtro ini_index = p_filtro.indexOf("<!--_ini_columnas_filtro-->") + 27; fin_index = p_filtro.indexOf("<!--_fin_columnas_filtro-->"); String p_columnas_filtro = p_filtro.substring(ini_index, fin_index); //extrae final de filtro ini_index = fin_index + 27; String p_fin_datos_filtro = p_filtro.substring(ini_index); // extrae los datos del nivel ini_index = ps.indexOf("<!--_ini_datos_nivel-->") + 23; fin_index = ps.indexOf("<!--_fin_datos_nivel-->"); String p_nivel = ps.substring(ini_index, fin_index); //extrae inicio de nivel ini_index = 0; fin_index = p_nivel.indexOf("<!--_ini_titulo_nivel-->"); String p_ini_datos_nivel = p_nivel.substring(ini_index, fin_index); //Extrae titulo del nivel ini_index = fin_index + 24; fin_index = p_nivel.indexOf("<!--_fin_titulo_nivel-->"); String p_titulo_nivel = p_nivel.substring(ini_index, fin_index); //Extrae columnas del nivel ini_index = p_nivel.indexOf("<!--_ini_columnas_nivel-->") + 26; fin_index = p_nivel.indexOf("<!--_fin_columnas_nivel-->"); String p_columnas_nivel = p_nivel.substring(ini_index, fin_index); //Extrae agregados del nivel ini_index = p_nivel.indexOf("<!--_ini_agregados_nivel-->") + 27; fin_index = p_nivel.indexOf("<!--_fin_agregados_nivel-->"); String p_agregados_nivel = p_nivel.substring(ini_index, fin_index); //Extrae codigo del nivel ini_index = p_nivel.indexOf("<!--_ini_codigo_nivel-->") + 24; fin_index = p_nivel.indexOf("<!--_fin_codigo_nivel-->"); String p_codigo_nivel = p_nivel.substring(ini_index, fin_index); //extrae final de nivel ini_index = fin_index + 24; String p_fin_datos_nivel = p_nivel.substring(ini_index); //extrae el fin de la plantilla ini_index = ps.indexOf("<!--_fin_datos_nivel-->") + 23; String p_final = ps.substring(ini_index); String nbd = ""; if (interfaz.equals("CEF")) { //System.out.println("Reportes del CEF"); JAdmVariablesSet var = new JAdmVariablesSet(null); var.ConCat(true); var.m_Where = "ID_Variable = 'IDEMPAYUDA'"; var.Open(); JBDSSet set = new JBDSSet(null); set.ConCat(true); set.m_Where = "ID_BD = '" + var.getAbsRow(0).getVEntero() + "'"; set.Open(); if (set.getNumRows() == 0) return; if (!set.getAbsRow(0).getSU().equals("3")) return; nbd = set.getAbsRow(0).getNombre(); } JReportesSet prm = new JReportesSet(null); if (interfaz.equals("SAF")) prm.ConCat(true); else { prm.ConCat(3); prm.setBD(nbd); } prm.m_OrderBy = "ID_Report ASC"; prm.Open(); JUsuariosPermisosCatalogoSet pc = new JUsuariosPermisosCatalogoSet(null); if (interfaz.equals("SAF")) pc.ConCat(true); else { pc.ConCat(3); pc.setBD(nbd); } pc.Open(); //System.out.println(prm.getSQL()); for (int k = 0; k < prm.getNumRows(); k++) { //Inicia por la ayuda JReportesAyudaSet as = new JReportesAyudaSet(null); if (interfaz.equals("SAF")) as.ConCat(true); else { as.ConCat(3); as.setBD(nbd); } as.m_Where = "ID_Report = '" + prm.getAbsRow(k).getID_Report() + "'"; as.Open(); String inicio = p_inicio; inicio = JUtil.replace(inicio, "fsi-color-interfaz", color); inicio = JUtil.replace(inicio, "_documentacion", as.getAbsRow(0).getHelp()); int index = prm.getAbsRow(k).getTipo().indexOf('_'); String base = prm.getAbsRow(k).getTipo().substring(0, index); String modulo = prm.getAbsRow(k).getTipo(); String basedesc = "", modulodesc = ""; for (int p = 0; p < pc.getNumRows(); p++) { if (pc.getAbsRow(p).getID_Permiso().equals(modulo)) modulodesc = pc.getAbsRow(p).getModulo(); if (pc.getAbsRow(p).getID_Permiso().equals(base)) basedesc = pc.getAbsRow(p).getModulo(); } String pagfin = pagina_final; String pathfin = path; if (interfaz.equals("SAF")) pathfin += "FSI-SAFREP-" + prm.getAbsRow(k).getID_Report() + ".html"; else pathfin += "FSI-CEFREP-" + prm.getAbsRow(k).getID_Report() + ".html"; pagfin = JUtil.replace(pagfin, "fsi-color-titulo", color); pagfin = JUtil.replace(pagfin, "fsi-cuerpo-titulo", prm.getAbsRow(k).getDescription()); String cuerpo = p_ini_datos_cabecero + "\n"; String titulo = p_titulo_cabecero; titulo = JUtil.replace(titulo, "fsi-color-modulo", color); cuerpo += titulo + "\n"; String columnas = p_columnas_cabecero; columnas = JUtil.replace(columnas, "_clave", Integer.toString(prm.getAbsRow(k).getID_Report())); columnas = JUtil.replace(columnas, "_descripcion", prm.getAbsRow(k).getDescription()); columnas = JUtil.replace(columnas, "_base", basedesc); columnas = JUtil.replace(columnas, "_modulo", modulodesc); columnas = JUtil.replace(columnas, "_graficar", (prm.getAbsRow(k).getGraficar() ? "<img src=\"../forsetidoc/IMG/chart.png\" style=\"border:0px solid;margin:0px;\" />" : " ")); cuerpo += columnas + "\n"; cuerpo += p_fin_datos_cabecero + "\n"; //Ahora el filtro JReportesFiltroSet fs = new JReportesFiltroSet(null); if (interfaz.equals("SAF")) fs.ConCat(true); else { fs.ConCat(3); fs.setBD(nbd); } fs.m_Where = "ID_Report = '" + prm.getAbsRow(k).getID_Report() + "'"; fs.m_OrderBy = "ID_Column ASC"; fs.Open(); if (fs.getNumRows() > 0) { cuerpo += p_ini_datos_filtro + "\n"; titulo = p_titulo_filtro; titulo = JUtil.replace(titulo, "fsi-color-modulo", color); cuerpo += titulo + "\n"; for (int fsi = 0; fsi < fs.getNumRows(); fsi++) { columnas = p_columnas_filtro; columnas = JUtil.replace(columnas, "_objeto", fs.getAbsRow(fsi).getPriDataName()); columnas = JUtil.replace(columnas, "_descripcion", fs.getAbsRow(fsi).getInstructions()); columnas = JUtil.replace(columnas, "_tipo_dato", fs.getAbsRow(fsi).getBindDataType()); columnas = JUtil.replace(columnas, "_rango", (fs.getAbsRow(fsi).getIsRange() ? "<img src=\"../forsetidoc/IMG/range.png\" style=\"border:0px solid;margin:0px;\" />" : " ")); cuerpo += columnas + "\n"; } cuerpo += p_fin_datos_filtro + "\n"; } //Fin del filtro //Ahora los niveles JReportesSentenciasSet ss = new JReportesSentenciasSet(null); JReportesSentenciasColumnasSet cs = new JReportesSentenciasColumnasSet(null); if (interfaz.equals("SAF")) { ss.ConCat(true); cs.ConCat(true); } else { ss.ConCat(3); ss.setBD(nbd); cs.ConCat(3); cs.setBD(nbd); } for (int niv = 1; niv <= 3; niv++) { cs.m_Where = "ID_Report = '" + prm.getAbsRow(k).getID_Report() + "' and ID_Sentence = '" + niv + "' and ID_IsCompute = '0'"; cs.m_OrderBy = "ID_Column ASC"; cs.Open(); ss.m_Where = "ID_Report = '" + prm.getAbsRow(k).getID_Report() + "' and ID_Sentence = '" + niv + "' and ID_IsCompute = '0'"; ss.Open(); if (cs.getNumRows() > 0) { cuerpo += p_ini_datos_nivel + "\n"; titulo = p_titulo_nivel; titulo = JUtil.replace(titulo, "_nivel", Integer.toString(niv)); cuerpo += titulo + "\n"; for (int csi = 0; csi < cs.getNumRows(); csi++) { columnas = p_columnas_nivel; columnas = JUtil.replace(columnas, "_columna", cs.getAbsRow(csi).getColName()); columnas = JUtil.replace(columnas, "_tipo_dato", cs.getAbsRow(csi).getBindDataType()); cuerpo += columnas + "\n"; } String codigo = p_codigo_nivel; codigo = JUtil.replace(codigo, "fsi-color-interfaz", color); codigo = JUtil.replace(codigo, "_codigo", ss.getAbsRow(0).getSelect_Clause()); cuerpo += codigo + "\n"; cuerpo += p_fin_datos_nivel + "\n"; } cs.m_Where = "ID_Report = '" + prm.getAbsRow(k).getID_Report() + "' and ID_Sentence = '" + niv + "' and ID_IsCompute = '1'"; cs.m_OrderBy = "ID_Column ASC"; cs.Open(); ss.m_Where = "ID_Report = '" + prm.getAbsRow(k).getID_Report() + "' and ID_Sentence = '" + niv + "' and ID_IsCompute = '1'"; ss.Open(); if (cs.getNumRows() > 0) { cuerpo += p_ini_datos_nivel + "\n"; for (int csi = 0; csi < cs.getNumRows(); csi++) { String agregados = p_agregados_nivel; agregados = JUtil.replace(agregados, "_columna", cs.getAbsRow(csi).getColName()); agregados = JUtil.replace(agregados, "_tipo_dato", cs.getAbsRow(csi).getBindDataType()); cuerpo += agregados + "\n"; } String codigo = p_codigo_nivel; codigo = JUtil.replace(codigo, "fsi-color-interfaz", color); codigo = JUtil.replace(codigo, "_codigo", ss.getAbsRow(0).getSelect_Clause()); cuerpo += codigo + "\n"; cuerpo += p_fin_datos_nivel + "\n"; } //Fin del nivel } String pagina = inicio + "\n" + cuerpo + "\n" + p_final; pagfin = JUtil.replace(pagfin, "fsi-cuerpo-todo", pagina); FileWriter fwp = new FileWriter(pathfin); PrintWriter pwp = new PrintWriter(fwp); pwp.println(pagfin); fwp.close(); } }
From source file:org.jrman.parser.Parser.java
public void parse(String filename) throws Exception { if (currentDirectory != null) { String fullFileName = (String) fullFileNames.get(filename); if (fullFileName == null) { fullFileName = currentDirectory + File.separator + filename; fullFileNames.put(filename, fullFileName); }/* w w w . j a v a2 s . c o m*/ filename = fullFileName; } FileReader fr = new FileReader(filename); Tokenizer st = new Tokenizer(new BufferedReader(fr)); // st.commentChar('#'); int tk; while ((tk = st.nextToken()) != StreamTokenizer.TT_EOF) { try { if (tk != StreamTokenizer.TT_WORD) throw new Exception("Expected keyword at line " + st.lineno()); String keyword = st.sval; KeywordParser kp = getKeyWordParser(keyword); if (!kp.getValidStates().contains(state)) throw new IllegalStateException( "Keyword" + kp + " is not valid in state " + state + ", at line " + st.lineno()); kp.parse(st); } catch (Exception pe) { System.err.println("Error: " + pe); pe.printStackTrace(); } } fr.close(); }
From source file:com.sec.ose.osi.ui.frm.main.identification.codematch.JPanCodeMatchMain.java
private void markMySourceSnippet() { MutableAttributeSet attr = new SimpleAttributeSet(); StyleConstants.setBackground(attr, new Color(255, 255, 180)); startMySourceMatchPos.clear();//from w ww.j av a 2 s . co m endMySourceMatchPos.clear(); String projectName = IdentifyMediator.getInstance().getSelectedProjectName(); File mySourceCode = new File(protexSDK.getSourceLocation(projectName) + File.separator + currentFileName); if (mySourceCode.exists()) { FileReader fr = null; try { fr = new FileReader(mySourceCode); BufferedReader br = new BufferedReader(fr); String tmpStr = null; int curLine = 1; int curTextSize = 0; while ((tmpStr = br.readLine()) != null) { setMySourceMatchLine(curLine, curTextSize); curTextSize += tmpStr.length() + 1; curLine++; } totalLine = curLine - 1; setMySourceMatchLine(curLine, curTextSize); } catch (Exception e) { log.warn(e); } finally { try { if (fr != null) { fr.close(); } } catch (Exception e) { log.warn(e); } } getJPanMatchedSourceViewLeft().clearStyle(); if (startMySourceMatchPos.size() > endMySourceMatchPos.size()) endMySourceMatchPos .add(getJPanMatchedSourceViewLeft().getStyledDocumentForSourcePane().getLength()); int snippetCnt = startMySourceMatchPos.size(); if (snippetCnt > 0) { for (int i = 0; i < snippetCnt; i++) { int offset = startMySourceMatchPos.get(i); int length = endMySourceMatchPos.get(i) - offset; getJPanMatchedSourceViewLeft().getStyledDocumentForSourcePane().setCharacterAttributes(offset, length, attr, true); } getJPanMatchedSourceViewLeft().getJTextPaneSourceView() .setCaretPosition(startMySourceMatchPos.get(0)); } } }
From source file:eu.stratosphere.pact.runtime.task.DataSinkTaskTest.java
@Test @SuppressWarnings("unchecked") public void testSortingDataSinkTask() { int keyCnt = 100; int valCnt = 20; super.initEnvironment(MEMORY_MANAGER_SIZE * 4, NETWORK_BUFFER_SIZE); super.addInput(new UniformRecordGenerator(keyCnt, valCnt, true), 0); DataSinkTask<Record> testTask = new DataSinkTask<Record>(); // set sorting super.getTaskConfig().setInputLocalStrategy(0, LocalStrategy.SORT); super.getTaskConfig().setInputComparator(new RecordComparatorFactory(new int[] { 1 }, ((Class<? extends Key<?>>[]) new Class[] { IntValue.class })), 0); super.getTaskConfig().setMemoryInput(0, 4 * 1024 * 1024); super.getTaskConfig().setFilehandlesInput(0, 8); super.getTaskConfig().setSpillingThresholdInput(0, 0.8f); super.registerFileOutputTask(testTask, MockOutputFormat.class, new File(tempTestPath).toURI().toString()); try {// ww w.ja v a 2s . c o m testTask.invoke(); } catch (Exception e) { LOG.debug(e); Assert.fail("Invoke method caused exception."); } File tempTestFile = new File(this.tempTestPath); Assert.assertTrue("Temp output file does not exist", tempTestFile.exists()); FileReader fr = null; BufferedReader br = null; try { fr = new FileReader(tempTestFile); br = new BufferedReader(fr); Set<Integer> keys = new HashSet<Integer>(); int curVal = -1; while (br.ready()) { String line = br.readLine(); Integer key = Integer.parseInt(line.substring(0, line.indexOf("_"))); Integer val = Integer.parseInt(line.substring(line.indexOf("_") + 1, line.length())); // check that values are in correct order Assert.assertTrue("Values not in ascending order", val >= curVal); // next value hit if (val > curVal) { if (curVal != -1) { // check that we saw 100 distinct keys for this values Assert.assertTrue("Keys missing for value", keys.size() == 100); } // empty keys set keys.clear(); // update current value curVal = val; } Assert.assertTrue("Duplicate key for value", keys.add(key)); } } catch (FileNotFoundException e) { Assert.fail("Out file got lost..."); } catch (IOException ioe) { Assert.fail("Caught IOE while reading out file"); } finally { if (br != null) { try { br.close(); } catch (Throwable t) { } } if (fr != null) { try { fr.close(); } catch (Throwable t) { } } } }