List of usage examples for java.io FileReader close
public void close() throws IOException
From source file:com.photon.phresco.impl.HtmlApplicationProcessor.java
private List<Configuration> getConfiguration(File jsonFile, String componentName) throws PhrescoException { FileReader reader = null; try {/*from ww w . j a v a2 s .c o m*/ reader = new FileReader(jsonFile); JsonParser parser = new JsonParser(); Object obj = parser.parse(reader); JsonObject jsonObject = (JsonObject) obj; List<Configuration> configurations = new ArrayList<Configuration>(); Configuration configuration = new Configuration(); Properties properties = new Properties(); Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet(); for (Entry<String, JsonElement> entry : entrySet) { JsonElement value = entry.getValue(); JsonObject asJsonObject = value.getAsJsonObject(); Set<Entry<String, JsonElement>> entrySet2 = asJsonObject.entrySet(); for (Entry<String, JsonElement> entry2 : entrySet2) { JsonElement value2 = entry2.getValue(); JsonObject asJsonObject1 = value2.getAsJsonObject(); Set<Entry<String, JsonElement>> entrySet3 = asJsonObject1.entrySet(); for (Entry<String, JsonElement> entry3 : entrySet3) { String key = entry3.getKey(); JsonElement value3 = entry3.getValue(); properties.setProperty(key, value3.getAsString()); } } configuration.setProperties(properties); configurations.add(configuration); return configurations; } } catch (Exception e) { throw new PhrescoException(e); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { throw new PhrescoException(e); } } return null; }
From source file:GUI.ReadFile.java
public boolean readTrace(String fileName) { FileReader fileReader; CSVParser csvFileParser;//from w w w .j a v a2s . c o m boolean isSuccess = true; CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(TRACE_HEADER_MAPPING); try { ArrayList<String> Activity_set = new ArrayList<String>(); HashSet<String> ID_set = new HashSet<String>(); traces = new ArrayList<Trace>(); //initialize FileReader object System.out.println(fileName); fileReader = new FileReader(fileName); //initialize CSVParser object csvFileParser = new CSVParser(fileReader, csvFileFormat); //Get a list of CSV file records List<CSVRecord> csvRecords = csvFileParser.getRecords(); Trace t = new Trace(""); //Read the CSV file records starting from the second record to skip the header for (int i = 1; i < csvRecords.size(); i++) { CSVRecord record = csvRecords.get(i); String ID = record.get(CaseID); if (!ID_set.contains(ID) || (i == csvRecords.size() - 1)) { //Discard void trace if (i != 1) { traces.add(t); } ID_set.add(ID); t = new Trace(ID); } Activity ac = new Activity(record.get(Activity), record.get(StartTime), record.get(CompleteTime), record.get(Timestamp)); t.add_activity(ac); if (!Activity_set.contains(ac.get_name())) { Activity_set.add(ac.get_name()); } } //sort activity set by string Collections.sort(Activity_set); //sort trace by ID Collections.sort(traces, new Comparator<Trace>() { @Override public int compare(Trace t1, Trace t2) { return Integer.parseInt(t1.get_ID()) < Integer.parseInt(t2.get_ID()) ? -1 : 1; } }); //Set activity set for each trace for (Trace T : traces) { T.set_ActivitySet((List<String>) Activity_set.clone()); } } catch (Exception e) { System.out.println("Error in CsvFileReader !!!"); e.printStackTrace(); isSuccess = false; return isSuccess; } if (isSuccess) { try { fileReader.close(); csvFileParser.close(); } catch (IOException e) { System.out.println("Error while closing fileReader/csvFileParser !!!"); } } return isSuccess; }
From source file:skoa.helpers.Graficos.java
/********************************************************************************************************** * Busca la unidad, leyendo la 1 lnea del fichero. * * @param nombre, no usa la variable global nombreFichero xq funciona para evolucion() y no para barras().* * @return devuelve la unidad, y si el fichero est vaco null. * **********************************************************************************************************/ private String buscarUnidad(String nombre) { File archivo = new File(ruta + nombre); FileReader fr = null; BufferedReader linea = null;//from w ww. jav a2s.c om String line; try { fr = new FileReader(archivo); linea = new BufferedReader(fr); //Se crea para leer las lineas line = linea.readLine(); //Leo la primera linea del finchero. if (line != null) { //Si no es nula, busco la unidad. line = line.substring(line.indexOf("\t") + 1); if (posiblesBooleanos(line, 0) || posiblesBooleanos(line, 1)) return "Bool"; else { line = line.substring(line.indexOf(" ") + 1); if (line.indexOf("C") >= 0) line = "C"; return line; } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != fr) fr.close(); //Se cierra si todo va bien. } catch (Exception e2) { //Sino salta una excepcion. e2.printStackTrace(); } } return null; }
From source file:gsn.wrappers.general.CSVWrapper.java
public void run() { Exception preivousError = null; long previousModTime = -1; long previousCheckModTime = -1; while (isActive()) { File dataFile = new File(handler.getDataFile()); File chkPointFile = new File(handler.getCheckPointFile()); long lastModified = -1; long lastModifiedCheckPoint = -1; if (dataFile.isFile()) lastModified = dataFile.lastModified(); if (chkPointFile.isFile()) lastModifiedCheckPoint = chkPointFile.lastModified(); FileReader reader = null; /*/*w w w. j av a 2 s.c o m*/ DEBUG_INFO("* Entry *"); DEBUG_INFO(list("lastModified", lastModified)); DEBUG_INFO(list("lastModifiedCheckPoint", lastModifiedCheckPoint)); */ try { ArrayList<TreeMap<String, Serializable>> output = null; if (preivousError == null || (preivousError != null && ((lastModified != previousModTime || lastModifiedCheckPoint != previousCheckModTime) || useCounterForCheckPoint))) { reader = new FileReader(handler.getDataFile()); output = handler.work(reader, checkPointDir); for (TreeMap<String, Serializable> se : output) { StreamElement streamElement = new StreamElement(se, getOutputFormat()); String[] ses = streamElement.getFieldNames(); processedLineCounter++; for (int i = 0; i < ses.length; i++) { if ("anetz_snow_height".equalsIgnoreCase(ses[i]) || "mst_surface_temp".equalsIgnoreCase(ses[i])) { logger.warn(dataFile + " : " + se); break; } } boolean insertionSuccess = postStreamElement(streamElement); if (!useCounterForCheckPoint) handler.updateCheckPointFile(streamElement.getTimeStamp()); // write latest processed timestamp else handler.updateCheckPointFile(processedLineCounter); // write latest processed line number } } //if (output==null || output.size()==0) //More intelligent sleeping, being more proactive once the wrapper receives huge files. Thread.sleep(samplingPeriodInMsc); } catch (Exception e) { if (preivousError != null && preivousError.getMessage().equals(e.getMessage())) continue; logger.error(e.getMessage() + " :: " + dataFile, e); preivousError = e; previousModTime = lastModified; previousCheckModTime = lastModifiedCheckPoint; } finally { if (reader != null) try { reader.close(); } catch (IOException e) { logger.debug(e.getMessage(), e); } } /* DEBUG_INFO("* Exit *"); */ } }
From source file:org.gluu.oxtrust.action.ManageCertificateAction.java
private KeyPair getKeyPair(String fileName) { KeyPair pair = null;/*from w w w.j a v a 2s.co m*/ JCERSAPrivateCrtKey privateKey = null; PEMReader r = null; FileReader fileReader = null; File keyFile = new File(getTempCertDir() + fileName.replace("crt", "key")); if (keyFile.isFile()) { try { fileReader = new FileReader(keyFile); r = new PEMReader(fileReader, new PasswordFinder() { public char[] getPassword() { // Since keys are stored without a password this // function should not be called. return null; } }); Object keys = r.readObject(); if (keys == null) { log.error(" Unable to read keys from: " + keyFile.getAbsolutePath()); return null; } if (keys instanceof KeyPair) { pair = (KeyPair) keys; log.debug(keyFile.getAbsolutePath() + "contains KeyPair"); } else if (keys instanceof JCERSAPrivateCrtKey) { privateKey = (JCERSAPrivateCrtKey) keys; log.debug(keyFile.getAbsolutePath() + "contains JCERSAPrivateCrtKey"); BigInteger exponent = privateKey.getPublicExponent(); BigInteger modulus = privateKey.getModulus(); RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(modulus, exponent); PublicKey publicKey = null; try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); publicKey = keyFactory.generatePublic(publicKeySpec); } catch (Exception e) { e.printStackTrace(); } pair = new KeyPair(publicKey, privateKey); } else { log.error(keyFile.getAbsolutePath() + " Contains unsupported key type: " + keys.getClass().getName()); return null; } } catch (IOException e) { log.error(e.getMessage(), e); return null; } finally { try { r.close(); fileReader.close(); } catch (Exception e) { log.error(e.getMessage(), e); return null; } } } else { log.error("Key file does not exist : " + keyFile.getAbsolutePath()); } log.debug("KeyPair successfully extracted from: " + keyFile.getAbsolutePath()); return pair; }
From source file:org.kuali.kfs.gl.batch.service.impl.BalancingServiceBaseImpl.java
/** * This is a helper method that wraps parsing poster entries for updateEntryHistory and updateBalanceHistory. * * @param startUniversityFiscalYear fiscal year for which to accept the earlier parsed lines from the input file * @return indicated whether records where ignored due to being older then startUniversityFiscalYear *//*from ww w .ja v a 2s . com*/ protected int updateHistoriesHelper(Integer postMode, Integer startUniversityFiscalYear, File inputFile, File errorFile) { int ignoredRecordsFound = 0; int lineNumber = 0; if (inputFile == null || errorFile == null) { return 0; } try { FileReader posterInputFileReader = new FileReader(inputFile); BufferedReader posterInputBufferedReader = new BufferedReader(posterInputFileReader); FileReader posterErrorFileReader = new FileReader(errorFile); BufferedReader posterErrorBufferedReader = new BufferedReader(posterErrorFileReader); // Reading input and error lines in tandem. Eliminating input lines if they were a line in error. String currentInputLine = posterInputBufferedReader.readLine(); String currentErrorLine = posterErrorBufferedReader.readLine(); while (currentInputLine != null) { lineNumber++; if (!StringUtils.isEmpty(currentInputLine) && !StringUtils.isBlank(currentInputLine.trim())) { if (currentInputLine.equals(currentErrorLine)) { // Skip it, it's in error. Increment to next error line currentErrorLine = posterErrorBufferedReader.readLine(); } else { // Line is good, parse it via delegation OriginEntryInformation originEntry = this.getOriginEntry(currentInputLine, lineNumber); if (originEntry.getUniversityFiscalYear() >= startUniversityFiscalYear) { // Line is in acceptable FY range, update history tables this.updateEntryHistory(postMode, originEntry); this.updateBalanceHistory(postMode, originEntry); this.updateCustomHistory(postMode, originEntry); } else { // Outside of trackable FY range. Log as being a failed line ignoredRecordsFound++; reportWriterService.writeError(originEntry, new Message(kualiConfigurationService.getPropertyValueAsString( KFSKeyConstants.Balancing.MESSAGE_BATCH_BALANCING_RECORD_BEFORE_FISCAL_YEAR), Message.TYPE_WARNING, startUniversityFiscalYear)); } } } currentInputLine = posterInputBufferedReader.readLine(); } posterInputFileReader.close(); posterInputBufferedReader.close(); posterErrorFileReader.close(); posterErrorBufferedReader.close(); } catch (Exception e) { LOG.fatal(String.format( kualiConfigurationService.getPropertyValueAsString( KFSKeyConstants.Balancing.ERROR_BATCH_BALANCING_UNKNOWN_FAILURE), e.getMessage(), lineNumber), e); reportWriterService.writeFormattedMessageLine(String.format( kualiConfigurationService.getPropertyValueAsString( KFSKeyConstants.Balancing.ERROR_BATCH_BALANCING_UNKNOWN_FAILURE), e.getMessage(), lineNumber)); throw new RuntimeException(String.format( kualiConfigurationService.getPropertyValueAsString( KFSKeyConstants.Balancing.ERROR_BATCH_BALANCING_UNKNOWN_FAILURE), e.getMessage(), lineNumber), e); } return ignoredRecordsFound; }
From source file:com.chinamobile.bcbsp.comm.MessageQueuesForDisk.java
/** * Load bucket from disk.//from ww w . ja v a 2 s. com * @param queuesBuckets * @param bucketIndex * @param queuePath * @throws IOException */ private void loadBucket(ArrayList<BucketMeta> queuesBuckets, int bucketIndex, String queuePath) throws IOException { LOG.info("[MessageQueuesForDisk] is loading the [" + queuePath + " Bucket-" + bucketIndex + "] <<< size = " + queuesBuckets.get(bucketIndex).count + "."); long start = System.currentTimeMillis(); /** Clock */ File messagesDataFileBucket; FileReader frMessagesData; BufferedReader brMessagesData; messagesDataFileBucket = new File(this.messagesDataFile + "/" + queuePath + "/" + "bucket-" + bucketIndex); if (!messagesDataFileBucket.exists()) { throw new IOException("Bucket file" + messagesDataFileBucket + " does not exit!"); } // Open file readers. frMessagesData = new FileReader(messagesDataFileBucket); brMessagesData = new BufferedReader(frMessagesData); // Read the file header. @SuppressWarnings("unused") String bucketHeader = brMessagesData.readLine(); ConcurrentHashMap<String, ConcurrentLinkedQueue<IMessage>> queueMap = queuesBuckets .get(bucketIndex).queueMap; if (queueMap == null) { queueMap = new ConcurrentHashMap<String, ConcurrentLinkedQueue<IMessage>>(); } String buffer; while ((buffer = brMessagesData.readLine()) != null) { String[] queueBuffer = buffer.split(Constants.KV_SPLIT_FLAG); if (queueBuffer[0] == "") { LOG.warn("[MessageQueuesForDisk] readLine = " + buffer); } String key = queueBuffer[0]; ConcurrentLinkedQueue<IMessage> queue = queueMap.get(key); if (queue == null) { queue = stringToQueue(queueBuffer[1]); this.sizeOfHashMapsInMem = this.sizeOfHashMapsInMem + (sizeOfRef + sizeOfInteger + sizeOfEmptyMessageQueue); } else { queue.addAll(stringToQueue(queueBuffer[1])); } queueMap.put(key, queue); } queuesBuckets.get(bucketIndex).queueMap = queueMap; brMessagesData.close(); frMessagesData.close(); // Update the meta data of the bucket. BucketMeta meta = queuesBuckets.get(bucketIndex); // Update the size of messages data in memory. this.sizeOfMessagesDataInMem = this.sizeOfMessagesDataInMem + (meta.length - meta.lengthInMemory); this.countOfMessagesDataInMem = this.countOfMessagesDataInMem + (meta.count - meta.countInMemory); meta.onDiskFlag = false; meta.lengthInMemory = meta.length; meta.countInMemory = meta.count; queuesBuckets.set(bucketIndex, meta); if (!messagesDataFileBucket.delete()) { throw new IOException("Bucket file delete failed!"); } this.readDiskTime = this.readDiskTime + (System.currentTimeMillis() - start); /** Clock */ }
From source file:com.httrack.android.HTTrackActivity.java
/** * Get the resource directory. Create it if necessary. Resources are created * in the dedicated cache, so that the files can be uninstalled upon * application removal./*from w w w.j a v a 2 s. c om*/ **/ private File buildResourceFile() { final File cache = android.os.Build.VERSION.SDK_INT >= VERSION_CODES.FROYO ? getExternalCacheDir() : getCacheDir(); final File rscPath = new File(cache, "resources"); final File stampFile = new File(rscPath, "resources.stamp"); final long stamp = installOrUpdateTime(); // Check timestamp of resources. If the applicate has been updated, // recreated cached resources. if (rscPath.exists()) { long diskStamp = 0; try { if (stampFile.exists()) { final FileReader reader = new FileReader(stampFile); final BufferedReader lreader = new BufferedReader(reader); try { diskStamp = Long.parseLong(lreader.readLine()); } catch (final NumberFormatException nfe) { diskStamp = 0; } lreader.close(); reader.close(); } } catch (final IOException io) { diskStamp = 0; } // Different one: wipe and recreate if (stamp != diskStamp) { Log.i(getClass().getSimpleName(), "deleting old resources " + rscPath.getAbsolutePath() + " (app_stamp=" + stamp + " != disk_stamp=" + diskStamp + ")"); CleanupActivity.deleteRecursively(rscPath); } else { Log.i(getClass().getSimpleName(), "keeping resources " + rscPath.getAbsolutePath() + " (app_stamp=disk_stamp=" + stamp + ")"); } } // Recreate resources ? if (!rscPath.exists()) { Log.i(getClass().getSimpleName(), "creating resources " + rscPath.getAbsolutePath() + " with stamp " + stamp); if (HTTrackActivity.mkdirs(rscPath)) { long totalSize = 0; int totalFiles = 0; try { final InputStream zipStream = getResources().openRawResource(R.raw.resources); final ZipInputStream file = new ZipInputStream(zipStream); ZipEntry entry; while ((entry = file.getNextEntry()) != null) { final File dest = new File(rscPath.getAbsoluteFile() + "/" + entry.getName()); if (entry.getName().endsWith("/")) { dest.mkdirs(); } else { final FileOutputStream writer = new FileOutputStream(dest); final byte[] bytes = new byte[1024]; int length; while ((length = file.read(bytes)) >= 0) { writer.write(bytes, 0, length); totalSize += length; } writer.close(); totalFiles++; dest.setLastModified(entry.getTime()); } } file.close(); zipStream.close(); Log.i(getClass().getSimpleName(), "created resources " + rscPath.getAbsolutePath() + " (" + totalFiles + " files, " + totalSize + " bytes)"); // Write stamp final FileWriter writer = new FileWriter(stampFile); final BufferedWriter lwriter = new BufferedWriter(writer); lwriter.write(Long.toString(stamp)); lwriter.close(); writer.close(); // Little info showNotification(getString(R.string.info_recreated_resources)); } catch (final IOException io) { Log.w(getClass().getSimpleName(), "could not create resources", io); CleanupActivity.deleteRecursively(rscPath); showNotification(getString(R.string.info_could_not_create_resources), true); } } } // Return resources path return rscPath; }
From source file:com.nwn.NwnUpdater.java
/** * Parse json file containing files required for server * Convert those files into ServerFile objects and store them *///from ww w. j a v a2 s . com private boolean parseServerFileJson() { boolean success = true; String compressedFileName; currentGui.setTaskProgressBarValue(0); int currentProgress = 0; int statusIncrement; currentGui.appendOutputText("\n\nReading file list"); try { Thread.sleep(500); FileReader reader = new FileReader(serverFileJson.toString()); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); Set<String> folders = jsonObject.keySet(); if (folders.size() > 0) { statusIncrement = 100 / folders.size(); } else { statusIncrement = 100; } for (String folderName : folders) { if (!folderName.contains("..") && !folderName.contains(":")) { affectedFolders.add(folderName); JSONArray filesByFolder = (JSONArray) jsonObject.get(folderName); Iterator fileItr = filesByFolder.iterator(); while (fileItr.hasNext()) { currentGui.appendOutputText("."); JSONObject fileJson = (JSONObject) fileItr.next(); URL fileUrl = new URL(fileJson.get("url").toString()); if (folderName.equalsIgnoreCase(FolderByExt.COMPRESSED.toString())) { ArrayList<String> compressedFileList = new ArrayList<>(); JSONArray compressedFileArray = (JSONArray) fileJson.get("files"); Iterator cfItr = compressedFileArray.iterator(); while (cfItr.hasNext()) { compressedFileName = cfItr.next().toString(); affectedFolders.add(NwnFileHandler.getFileExtension(compressedFileName)); compressedFileList.add(compressedFileName); } serverFileList.add(new ServerFile(fileJson.get("name").toString(), fileUrl, folderName, compressedFileList)); } else { serverFileList .add(new ServerFile(fileJson.get("name").toString(), fileUrl, folderName)); } } } else { currentGui.appendOutputText("An unusual folder path was detected: " + folderName + "\nServer owner may be attempting to place files outside of NWN." + "\nThis folder has been excluded from the update."); } currentProgress = currentProgress + statusIncrement; currentGui.setTaskProgressBarValue(currentProgress); } currentGui.appendOutputText("done"); reader.close(); } catch (IOException ex) { // ex.printStackTrace(); currentGui.appendOutputText("...failed\nERROR: Cannot read server file list."); error[0] = true; success = false; } catch (ParseException ex) { // ex.printStackTrace(); currentGui.appendOutputText("...failed\nERROR: Cannot parse server file list."); error[0] = true; success = false; } catch (InterruptedException ex) { currentGui.appendOutputText("...canceled"); success = false; } return success; }
From source file:fsi_admin.JFsiTareas.java
private void instalarActualizacion(String folderact, float versiondisp, int revisiondisp, float version, int revision, PrintWriter pw, MutableBoolean reiniciarServidor, PrintWriter out) throws Exception { if (out != null) { out.println("COMENZANDO LA ACTUALIZACION DE BASES DE DATOS " + versiondisp + "." + revisiondisp + ": " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss") + "<br>"); out.println("------------------------------------------------------------------------------<br>"); out.flush();//from w w w. j av a 2 s.c o m } pw.println("COMENZANDO LA ACTUALIZACION DE BASES DE DATOS " + versiondisp + "." + revisiondisp + ": " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss")); pw.println("------------------------------------------------------------------------------"); pw.flush(); FileReader file = new FileReader(folderact + "status_log"); BufferedReader buff = new BufferedReader(file); boolean eof = false; Map<String, String> map = new HashMap<String, String>(); Vector<String> actbd_sql = new Vector<String>(); Vector<String> actfsi_sql = new Vector<String>(); while (!eof) { String line = buff.readLine(); if (line == null) eof = true; else { try { StringTokenizer st = new StringTokenizer(line, "="); String key = st.nextToken(); String value = st.nextToken(); map.put(key, value); } catch (NoSuchElementException e) { continue; } } } buff.close(); file.close(); //ya tenemos el status_log en memoria, ahora lo utilizamos como base para la actualizacion JFsiScript sc = new JFsiScript(); sc.setVerbose(true); String ERROR = ""; String dirfsi = "/usr/local/forseti"; if (map.get("STATUS").equals("ACTBD")) // significa que no ha hecho nada, o que no se completo la actulizacion anterior { JBDSSet set = new JBDSSet(null); set.ConCat(true); set.m_Where = "ID_BD >= " + map.get("BD") + " and SU = '3'"; set.m_OrderBy = "ID_BD ASC"; set.Open(); for (int i = 0; i < set.getNumRows(); i++) { //verifica que la base de datos a actualizar, no sea mas antigua que las actuales en este servidor //Esto pudiera suceder porque se acaba de restaurar una base de datos que habia sido respaldada antes //de la ultima actualizacion del servidor JAdmVariablesSet var = new JAdmVariablesSet(null); var.setBD(set.getAbsRow(i).getNombre()); var.ConCat(3); var.m_Where = "ID_Variable = 'VERSION'"; var.Open(); //pw.println("SQL: " + set.getAbsRow(i).getNombre() + " " + var.getSQL()); //pw.println("TOTAL: " + var.getNumRows()); float varversion = var.getAbsRow(0).getVDecimal(); int varrevision = var.getAbsRow(0).getVEntero(); if (varversion < version || (varversion == version && varrevision < revision)) { if (out != null) { out.println( "LA BASE DE DATOS ESTA DESFASADA EN VERSION O REVISION Y NO SE PUEDE ACTUALIZAR: " + set.getAbsRow(i).getNombre() + ":" + varversion + "." + varrevision + " --- " + versiondisp + "." + revisiondisp + "<br>"); out.println( "ESTO PUEDE SER DEBIDO A QUE SE HA RESTAURADO UNA BASE DE DATOS QUE HABIA SIDO<br>"); out.println( "RESPALDADA ANTES DE LA ULTIMA ACTUALIZACION DEL SERVIDOR... INTENTA POR ACTUALIZACION DE EMPRESAS DESFASADAS<br>"); out.println( "-------------------------------------------------------------------------------------------------------------------<br>"); out.flush(); } pw.println("LA BASE DE DATOS ESTA DESFASADA EN VERSION O REVISION Y NO SE PUEDE ACTUALIZAR: " + set.getAbsRow(i).getNombre() + ":" + varversion + "." + varrevision + " --- " + versiondisp + "." + revisiondisp); pw.println("ESTO PUEDE SER DEBIDO A QUE SE HA RESTAURADO UNA BASE DE DATOS QUE HABIA SIDO"); pw.println( "RESPALDADA ANTES DE LA ULTIMA ACTUALIZACION DEL SERVIDOR... INTENTA POR ACTUALIZACION DE EMPRESAS DESFASADAS"); pw.println( "-------------------------------------------------------------------------------------------------------------------"); pw.flush(); continue; } if (out != null) { out.println("Actualizando BD :" + set.getAbsRow(i).getNombre() + "<br>"); out.flush(); } pw.println("Actualizando BD :" + set.getAbsRow(i).getNombre()); pw.flush(); if (map.get("PUNTO").equals("NC")) // nada actalizado a esta base de datos, comienza por los archivos { File dir = new File(folderact + "emp"); if (dir.exists()) { if (out != null) { out.println("Grabando los archivos del sistema para BD: " + set.getAbsRow(i).getNombre() + "<br>"); out.flush(); } pw.println("Grabando los archivos del sistema para BD: " + set.getAbsRow(i).getNombre()); pw.flush(); String CONTENT = "rsync -av --stats " + folderact + "emp/ " + dirfsi + "/emp/" + set.getAbsRow(i).getNombre().substring(6); sc.setContent(CONTENT); pw.println(CONTENT); String RES = sc.executeCommand(); ERROR += sc.getError(); if (!ERROR.equals("")) { //System.out.println(ERROR); if (out != null) { out.println(ERROR + "<br>"); out.flush(); } pw.println(ERROR); pw.flush(); return; } else { pw.println(RES); pw.flush(); } } map.put("PUNTO", "ARCHIVOS"); File f = new File(folderact + "status_log"); FileWriter fsl = new FileWriter(f); fsl.write("STATUS=ACTBD\nBD=" + set.getAbsRow(i).getID_BD() + "\nPUNTO=ARCHIVOS"); fsl.close(); pw.println("-----------------------------------------------------------------------------"); pw.flush(); } if (map.get("PUNTO").equals("ARCHIVOS")) // archivos actualizados, ahora la estructura de la bd { File sql = new File(folderact + "actbd.sql"); if (sql.exists()) { ////////////////////////////////////////////////////////////////////////////////////////////////// if (actbd_sql.size() == 0) { FileReader filebas = new FileReader(folderact + "actbd.sql"); BufferedReader buffbas = new BufferedReader(filebas); boolean eofbas = false; String strbas = ""; while (!eofbas) { String linebas = buffbas.readLine(); if (linebas == null) eofbas = true; else { if (linebas.indexOf("--@FIN_BLOQUE") == -1) strbas += linebas + "\n"; else { actbd_sql.addElement(strbas); strbas = ""; } } } buffbas.close(); filebas.close(); } if (out != null) { out.println( "Executando estructura SQL para BD: " + set.getAbsRow(i).getNombre() + "<br>"); out.flush(); } pw.println("Executando estructura SQL para BD: " + set.getAbsRow(i).getNombre()); pw.flush(); Connection con = JAccesoBD.getConexion(set.getAbsRow(i).getNombre()); con.setAutoCommit(false); Statement s = con.createStatement(); for (int j = 0; j < actbd_sql.size(); j++) { String actbdblq_sql = JUtil.replace(actbd_sql.get(j), "[[owner]]", set.getAbsRow(i).getUsuario()); pw.println(actbdblq_sql + "\n"); pw.flush(); s.executeUpdate(actbdblq_sql); } String varbd_sql = "UPDATE TBL_VARIABLES\n" + "SET VDecimal = '" + versiondisp + "', VEntero = '" + revisiondisp + "', VAlfanumerico = '" + versiondisp + "." + revisiondisp + "'\n" + "WHERE ID_Variable = 'VERSION';"; //"REASSIGN OWNED BY forseti TO " + set.getAbsRow(i).getUsuario() + ";"; pw.println(varbd_sql + "\n"); pw.flush(); s.executeUpdate(varbd_sql); con.commit(); s.close(); con.close(); //////////////////////////////////////////////////////////////////////////////////////////////// } else { Connection con = JAccesoBD.getConexion(set.getAbsRow(i).getNombre()); con.setAutoCommit(false); Statement s = con.createStatement(); String varbd_sql = "UPDATE TBL_VARIABLES\n" + "SET VDecimal = '" + versiondisp + "', VEntero = '" + revisiondisp + "', VAlfanumerico = '" + versiondisp + "." + revisiondisp + "'\n" + "WHERE ID_Variable = 'VERSION';"; pw.println(varbd_sql + "\n"); pw.flush(); s.executeUpdate(varbd_sql); con.commit(); s.close(); con.close(); } map.put("PUNTO", "ESTRUCTURA"); File f = new File(folderact + "status_log"); FileWriter fsl = new FileWriter(f); fsl.write("STATUS=ACTBD\nBD=" + set.getAbsRow(i).getID_BD() + "\nPUNTO=ESTRUCTURA"); fsl.close(); } ////////////////////////////////////////////////////////////////////// if (map.get("PUNTO").equals("ESTRUCTURA")) // Ahora los mensajes de esta bd los actualiza { File msj = new File(folderact + "bin/.forseti_es"); if (msj.exists()) { FileReader filemsj = new FileReader(folderact + "bin/.forseti_es"); BufferedReader buffmsj = new BufferedReader(filemsj); boolean eofmsj = false; if (out != null) { out.println("Executando mensajes para " + set.getAbsRow(i).getNombre() + "<br>"); out.flush(); } pw.println("Executando mensajes para " + set.getAbsRow(i).getNombre()); pw.flush(); Connection con = JAccesoBD.getConexion(set.getAbsRow(i).getNombre()); Statement s = con.createStatement(); String varmsj_sql = "TRUNCATE TABLE TBL_MSJ;"; pw.println(varmsj_sql + "\n"); pw.flush(); s.executeUpdate(varmsj_sql); while (!eofmsj) { String line = buffmsj.readLine(); if (line == null) eofmsj = true; else { if (line.equals("__INIT")) { String alc = "", mod = "", sub = "", elm = "", msj1 = "", msj2 = "", msj3 = "", msj4 = "", msj5 = ""; for (int im = 1; im <= 9; im++) { line = buffmsj.readLine(); switch (im) { case 1: msj1 = "'" + line + "'"; break; case 2: msj2 = (line.equals("null") ? "null" : "'" + JUtil.p(line) + "'"); break; case 3: msj3 = (line.equals("null") ? "null" : "'" + JUtil.p(line) + "'"); break; case 4: msj4 = (line.equals("null") ? "null" : "'" + JUtil.p(line) + "'"); break; case 5: msj5 = (line.equals("null") ? "null" : "'" + JUtil.p(line) + "'"); break; case 6: alc = "'" + JUtil.p(line) + "'"; break; case 7: mod = "'" + JUtil.p(line) + "'"; break; case 8: sub = "'" + JUtil.p(line) + "'"; break; case 9: elm = "'" + JUtil.p(line) + "'"; break; } } varmsj_sql = "INSERT INTO tbl_msj\nVALUES("; varmsj_sql += alc + "," + mod + "," + sub + "," + elm + "," + msj1 + "," + msj2 + "," + msj3 + "," + msj4 + "," + msj5 + ");"; pw.println(varmsj_sql + "\n"); pw.flush(); s.executeUpdate(varmsj_sql); } } } s.close(); con.close(); buffmsj.close(); filemsj.close(); } map.put("PUNTO", "MSJ"); File f = new File(folderact + "status_log"); FileWriter fsl = new FileWriter(f); fsl.write("STATUS=ACTBD\nBD=" + set.getAbsRow(i).getID_BD() + "\nPUNTO=MSJ"); fsl.close(); } /////////////////////////////////////////////////////////////////////// map.put("PUNTO", "NC"); } map.put("STATUS", "ACTFSI"); map.put("BD", "FSI"); map.put("PUNTO", "NC"); File f = new File(folderact + "status_log"); FileWriter fsl = new FileWriter(f); fsl.write("STATUS=ACTFSI\nBD=FSI\nPUNTO=NC"); fsl.close(); } if (map.get("STATUS").equals("ACTFSI")) //Significa que las bases de datos ya estan actualizadas, y falta FORSETI_ADMIN { if (map.get("PUNTO").equals("NC")) // nada actalizado a esta base de datos, comienza por los archivos { if (out != null) { out.println( "--------------------------------- FORSETI_ADMIN -------------------------------------------<br>"); out.flush(); } pw.println( "--------------------------------- FORSETI_ADMIN -------------------------------------------"); pw.flush(); File dir = new File(folderact + "act"); if (dir.exists()) { if (out != null) { out.println("Grabando los archivos act...<br>"); out.flush(); } pw.println("Grabando los archivos act..."); pw.flush(); String CONTENT = "rsync -av --stats " + folderact + "act/ " + dirfsi + "/act"; sc.setContent(CONTENT); pw.println(CONTENT); String RES = sc.executeCommand(); ERROR = sc.getError(); if (!ERROR.equals("")) { if (out != null) { out.println(ERROR + "<br>"); out.flush(); } pw.println(ERROR); pw.flush(); return; } else { pw.println(RES); pw.flush(); } } dir = new File(folderact + "bin"); if (dir.exists()) { if (out != null) { out.println("Grabando los archivos bin...<br>"); out.flush(); } pw.println("Grabando los archivos bin..."); pw.flush(); String CONTENT = "rsync -av --stats " + folderact + "bin/ " + dirfsi + "/bin"; sc.setContent(CONTENT); pw.println(CONTENT); String RES = sc.executeCommand(); ERROR = sc.getError(); if (!ERROR.equals("")) { if (out != null) { out.println(ERROR + "<br>"); out.flush(); } pw.println(ERROR); pw.flush(); return; } else { pw.println(RES); pw.flush(); } } dir = new File(folderact + "pac"); if (dir.exists()) { if (out != null) { out.println("Grabando los archivos pac...<br>"); out.flush(); } pw.println("Grabando los archivos pac..."); pw.flush(); String CONTENT = "rsync -av --stats " + folderact + "pac/ " + dirfsi + "/pac"; sc.setContent(CONTENT); pw.println(CONTENT); String RES = sc.executeCommand(); ERROR = sc.getError(); if (!ERROR.equals("")) { if (out != null) { out.println(ERROR + "<br>"); out.flush(); } pw.println(ERROR); pw.flush(); return; } else { pw.println(RES); pw.flush(); } } dir = new File(folderact + "rec"); if (dir.exists()) { if (out != null) { out.println("Grabando los archivos rec...<br>"); out.flush(); } pw.println("Grabando los archivos rec..."); pw.flush(); String CONTENT = "rsync -av --stats " + folderact + "rec/ " + dirfsi + "/rec"; sc.setContent(CONTENT); pw.println(CONTENT); String RES = sc.executeCommand(); ERROR = sc.getError(); if (!ERROR.equals("")) { if (out != null) { out.println(ERROR + "<br>"); out.flush(); } pw.println(ERROR); pw.flush(); return; } else { pw.println(RES); pw.flush(); } } map.put("PUNTO", "ARCHIVOS"); File f = new File(folderact + "status_log"); FileWriter fsl = new FileWriter(f); fsl.write("STATUS=ACTFSI\nBD=FSI\nPUNTO=ARCHIVOS"); fsl.close(); } if (map.get("PUNTO").equals("ARCHIVOS")) // archivos actualizados, ahora la estructura de la bd { File sql = new File(folderact + "actfsi.sql"); if (sql.exists()) { ////////////////////////////////////////////////////////////////////////////////////////////////// FileReader filebas = new FileReader(folderact + "actfsi.sql"); BufferedReader buffbas = new BufferedReader(filebas); boolean eofbas = false; String strbas = ""; while (!eofbas) { String linebas = buffbas.readLine(); if (linebas == null) eofbas = true; else { if (linebas.indexOf("--@FIN_BLOQUE") == -1) strbas += linebas + "\n"; else { actfsi_sql.addElement(strbas); strbas = ""; } } } buffbas.close(); filebas.close(); if (out != null) { out.println("Executando estructura SQL para FORSETI_ADMIN<br>"); out.flush(); } pw.println("Executando estructura SQL para FORSETI_ADMIN"); pw.flush(); Connection con = JAccesoBD.getConexion(); con.setAutoCommit(false); Statement s = con.createStatement(); for (int j = 0; j < actfsi_sql.size(); j++) { String actfsiblq_sql = actfsi_sql.get(j); pw.println(actfsiblq_sql + "\n"); pw.flush(); s.executeUpdate(actfsiblq_sql); } String varfsi_sql = "UPDATE TBL_VARIABLES\n" + "SET VDecimal = '" + versiondisp + "', VEntero = '" + revisiondisp + "', VAlfanumerico = '" + versiondisp + "." + revisiondisp + "'\n" + "WHERE ID_Variable = 'VERSION';"; pw.println(varfsi_sql + "\n"); pw.flush(); s.executeUpdate(varfsi_sql); con.commit(); s.close(); con.close(); } else { Connection con = JAccesoBD.getConexion(); con.setAutoCommit(false); Statement s = con.createStatement(); String varfsi_sql = "UPDATE TBL_VARIABLES\n" + "SET VDecimal = '" + versiondisp + "', VEntero = '" + revisiondisp + "', VAlfanumerico = '" + versiondisp + "." + revisiondisp + "'\n" + "WHERE ID_Variable = 'VERSION';"; pw.println(varfsi_sql + "\n"); pw.flush(); s.executeUpdate(varfsi_sql); con.commit(); s.close(); con.close(); } map.put("PUNTO", "ESTRUCTURA"); File f = new File(folderact + "status_log"); FileWriter fsl = new FileWriter(f); fsl.write("STATUS=ACTFSI\nBD=FSI\nPUNTO=ESTRUCTURA"); fsl.close(); } if (map.get("PUNTO").equals("ESTRUCTURA")) // Ahora los mensajes los actualiza { File msj = new File(folderact + "bin/.forseti_es"); if (msj.exists()) { FileReader filemsj = new FileReader(folderact + "bin/.forseti_es"); BufferedReader buffmsj = new BufferedReader(filemsj); boolean eofmsj = false; if (out != null) { out.println("Executando mensajes para FORSETI_ADMIN<br>"); out.flush(); } pw.println("Executando mensajes para FORSETI_ADMIN"); pw.flush(); Connection con = JAccesoBD.getConexion(); Statement s = con.createStatement(); String varmsj_sql = "TRUNCATE TABLE TBL_MSJ;"; pw.println(varmsj_sql + "\n"); pw.flush(); s.executeUpdate(varmsj_sql); while (!eofmsj) { String line = buffmsj.readLine(); if (line == null) eofmsj = true; else { if (line.equals("__INIT")) { String alc = "", mod = "", sub = "", elm = "", msj1 = "", msj2 = "", msj3 = "", msj4 = "", msj5 = ""; for (int i = 1; i <= 9; i++) { line = buffmsj.readLine(); switch (i) { case 1: msj1 = "'" + line + "'"; break; case 2: msj2 = (line.equals("null") ? "null" : "'" + JUtil.p(line) + "'"); break; case 3: msj3 = (line.equals("null") ? "null" : "'" + JUtil.p(line) + "'"); break; case 4: msj4 = (line.equals("null") ? "null" : "'" + JUtil.p(line) + "'"); break; case 5: msj5 = (line.equals("null") ? "null" : "'" + JUtil.p(line) + "'"); break; case 6: alc = "'" + JUtil.p(line) + "'"; break; case 7: mod = "'" + JUtil.p(line) + "'"; break; case 8: sub = "'" + JUtil.p(line) + "'"; break; case 9: elm = "'" + JUtil.p(line) + "'"; break; } } varmsj_sql = "INSERT INTO tbl_msj\nVALUES("; varmsj_sql += alc + "," + mod + "," + sub + "," + elm + "," + msj1 + "," + msj2 + "," + msj3 + "," + msj4 + "," + msj5 + ");"; pw.println(varmsj_sql + "\n"); pw.flush(); s.executeUpdate(varmsj_sql); } } } s.close(); con.close(); buffmsj.close(); filemsj.close(); } File f = new File(folderact + "status_log"); FileWriter fsl = new FileWriter(f); fsl.write("STATUS=ACTFSI\nBD=FSI\nPUNTO=MSJ"); fsl.close(); } if (map.get("PUNTO").equals("MSJ")) // mensajes actualizados, ahora el archivo ROOT { File root = new File(folderact + "ROOT.war"); if (root.exists()) { if (out != null) { out.println("Grabando el archivo ROOT para tomcat...<br>"); out.flush(); } pw.println("Grabando el archivo ROOT para tomcat..."); pw.flush(); String CONTENT = "rsync -av --stats " + folderact + "ROOT.war " + tomcat + "/webapps"; sc.setContent(CONTENT); pw.println(CONTENT); String RES = sc.executeCommand(); ERROR = sc.getError(); if (!ERROR.equals("")) { if (out != null) { out.println(ERROR + "<br>"); out.flush(); } pw.println(ERROR); pw.flush(); return; } else { pw.println(RES); pw.flush(); } } map.put("PUNTO", "ROOT"); File f = new File(folderact + "status_log"); FileWriter fsl = new FileWriter(f); fsl.write("STATUS=OK\nBD=FSI\nPUNTO=ROOT"); fsl.close(); reiniciarServidor.setValue(true); } } if (out != null) { out.println("FINALIZADA LA ACTUALIZACION DE BASES DE DATOS: " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss") + "<br>"); out.println("------------------------------------------------------------------------------<br>"); } pw.println("FINALIZADA LA ACTUALIZACION DE BASES DE DATOS: " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss")); pw.println("------------------------------------------------------------------------------"); }