Example usage for java.io FileReader close

List of usage examples for java.io FileReader close

Introduction

In this page you can find the example usage for java.io FileReader close.

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:com.photon.phresco.impl.HtmlApplicationProcessor.java

private void writeJson(File sourceFolderLocation, List<JsonElement> compJsonElements, String environment,
        String type) throws PhrescoException {
    File jsonDir = new File(sourceFolderLocation + File.separator + "src/main/webapp/json");
    if (!jsonDir.exists()) {
        return;//from w  w  w.  j  a va 2 s  . c o  m
    }

    if (CollectionUtils.isEmpty(compJsonElements)) {
        return;
    }

    File configFile = new File(getAppLevelConfigJson(sourceFolderLocation));

    JsonParser parser = new JsonParser();
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonObject jsonObject = new JsonObject();
    JsonObject envObject = new JsonObject();
    if (!configFile.exists()) {
        jsonObject.addProperty(Constants.NAME, environment);
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (JsonElement jsonElement : compJsonElements) {
            String jsonString = jsonElement.toString();
            sb.append(jsonString.substring(1, jsonString.length() - 1));
            sb.append(",");
        }
        String compConfig = sb.toString();
        compConfig = compConfig.substring(0, compConfig.length() - 1) + "}";
        jsonObject.add(type, parser.parse(compConfig));
        envObject.add(Constants.ENVIRONMENTS, parser.parse(Collections.singletonList(jsonObject).toString()));
    } else {
        FileReader reader = null;
        try {
            reader = new FileReader(configFile);
            Object obj = parser.parse(reader);
            envObject = (JsonObject) obj;
            JsonArray environments = (JsonArray) envObject.get(Constants.ENVIRONMENTS);
            jsonObject = getProductionEnv(environments, environment);
            JsonElement components = null;
            for (JsonElement compJsonElement : compJsonElements) {
                JsonObject allComponents = null;
                if (jsonObject == null) {
                    jsonObject = new JsonObject();
                    JsonElement jsonElement = envObject.get(Constants.ENVIRONMENTS);
                    String oldObj = jsonElement.toString().substring(1, jsonElement.toString().length() - 1)
                            .concat(",");
                    jsonObject.addProperty(Constants.NAME, environment);
                    jsonObject.add(type, compJsonElement);
                    String newObj = jsonObject.toString();
                    envObject.add(Constants.ENVIRONMENTS,
                            parser.parse(Collections.singletonList(oldObj + newObj).toString()));
                } else {
                    components = jsonObject.get(type);
                }
                if (components == null) {
                    jsonObject.add(type, compJsonElement);
                } else {
                    allComponents = components.getAsJsonObject();
                    Set<Entry<String, JsonElement>> entrySet = compJsonElement.getAsJsonObject().entrySet();
                    Entry<String, JsonElement> entry = entrySet.iterator().next();
                    String key = entry.getKey();
                    //                  if (allComponents.get(key) == null) {
                    allComponents.add(key, entry.getValue());
                    //                  }
                }
            }

        } catch (FileNotFoundException e) {
            throw new PhrescoException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new PhrescoException(e);
                }
            }
        }
    }

    FileWriter writer = null;
    String json = gson.toJson(envObject);
    try {
        writer = new FileWriter(configFile);
        writer.write(json);
        writer.flush();
    } catch (IOException e) {
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException e) {
            throw new PhrescoException(e);
        }
    }
}

From source file:corelyzer.data.CRPreferences.java

public boolean readUIConfig(final File aFile) {
    try {//from   w w  w.j  a v a 2 s. c  o  m
        this.sessionHistory.clear();

        FileReader fr = new FileReader(aFile);
        BufferedReader br = new BufferedReader(fr);

        String line;
        while ((line = br.readLine()) != null) {
            String[] toks = line.split("=");

            // lockCoreSectionImage
            if (toks[0].trim().equalsIgnoreCase("lockCoreSectionImage")) {
                this.lockCoreSectionImage = toks[1].trim().equalsIgnoreCase("true");
            } else if (toks[0].trim().equalsIgnoreCase("usequaqua")) {
                this.useQuaqua = toks[1].trim().equalsIgnoreCase("true");
            } else if (toks[0].trim().equalsIgnoreCase("autocheckversion")) {
                this.autoCheckVersion = toks[1].trim().equalsIgnoreCase("true");
            } else if (toks[0].trim().equalsIgnoreCase("canvas_bgcolor_r")) {
                bgcolor[0] = Float.parseFloat(toks[1].trim());
            } else if (toks[0].trim().equalsIgnoreCase("canvas_bgcolor_g")) {
                bgcolor[1] = Float.parseFloat(toks[1].trim());
            } else if (toks[0].trim().equalsIgnoreCase("canvas_bgcolor_b")) {
                bgcolor[2] = Float.parseFloat(toks[1].trim());
            } else if (toks[0].trim().equalsIgnoreCase("autozoom")) {
                this.setAutoZoom(Boolean.parseBoolean(toks[1].trim()));
            } else if (toks[0].trim().equalsIgnoreCase("enableGrid")) {
                this.grid_show = toks[1].trim().equalsIgnoreCase("true");
                // now let's read values for grid configuration.
                line = br.readLine();
                this.grid_type = new Integer(line);
                line = br.readLine();
                this.grid_size = new Float(line);
                line = br.readLine();
                this.grid_thickness = new Integer(line);
                line = br.readLine();
                this.grid_r = new Float(line);
                line = br.readLine();
                this.grid_g = new Float(line);
                line = br.readLine();
                this.grid_b = new Float(line);
            } else if (toks[0].trim().toLowerCase().startsWith("sessionhst")) {
                String path = toks[1].trim();
                this.sessionHistory.add(path);
            } else {
                System.out.println("---> Ignore unknown UI config option");
            }
        }

        br.close();
        fr.close();

        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:com.photon.phresco.impl.HtmlApplicationProcessor.java

private List<Configuration> getConfiguration(File jsonFile, String envName, String componentName)
        throws PhrescoException {
    FileReader reader = null;
    try {/*from  ww w. j  av  a2s.c  om*/
        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();
            JsonArray jsonArray = value.getAsJsonArray();
            for (JsonElement jsonElement : jsonArray) {
                JsonObject asJsonObject = jsonElement.getAsJsonObject();
                JsonElement name = asJsonObject.get(Constants.NAME);
                if (name.getAsString().equals(envName)) {
                    JsonElement components = asJsonObject.get(Constants.COMPONENTS);
                    JsonObject asJsonObj = components.getAsJsonObject();
                    Set<Entry<String, JsonElement>> parentEntrySet = asJsonObj.entrySet();
                    for (Entry<String, JsonElement> entry1 : parentEntrySet) {
                        String key = entry1.getKey();
                        if (key.equalsIgnoreCase(componentName)) {
                            JsonObject valueJsonObj = entry1.getValue().getAsJsonObject();
                            Set<Entry<String, JsonElement>> valueEntrySet = valueJsonObj.entrySet();
                            for (Entry<String, JsonElement> valueEntry : valueEntrySet) {
                                String key1 = valueEntry.getKey();
                                JsonElement value1 = valueEntry.getValue();
                                properties.setProperty(key1, value1.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:com.atlauncher.data.Settings.java

/**
 * Loads the user servers added for checking
 *///from   ww  w.ja  v  a  2 s  .c om
private void loadCheckingServers() {
    LogManager.debug("Loading servers to check");
    this.checkingServers = new ArrayList<MinecraftServer>(); // Reset the list
    if (checkingServersFile.exists()) {
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(checkingServersFile);
        } catch (FileNotFoundException e) {
            logStackTrace(e);
            return;
        }

        this.checkingServers = Gsons.DEFAULT.fromJson(fileReader, MinecraftServer.LIST_TYPE);

        if (fileReader != null) {
            try {
                fileReader.close();
            } catch (IOException e) {
                logStackTrace("Exception while trying to close FileReader when loading servers for server "
                        + "checker" + " tool.", e);
            }
        }
    }
    LogManager.debug("Finished loading servers to check");
}

From source file:com.atlauncher.data.Settings.java

/**
 * Downloads and loads all external libraries used by the launcher as specified in the Configs/JSON/libraries.json
 * file./*from  ww w .  ja  va 2s. c om*/
 */
private void downloadExternalLibraries() {
    LogManager.debug("Downloading external libraries");

    FileReader fr = null;

    try {
        fr = new FileReader(new File(this.jsonDir, "libraries.json"));

        java.lang.reflect.Type type = new TypeToken<List<LauncherLibrary>>() {
        }.getType();

        this.launcherLibraries = Gsons.DEFAULT.fromJson(fr, type);
    } catch (Exception e) {
        logStackTrace(e);
    } finally {
        if (fr != null) {
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    ExecutorService executor = Executors.newFixedThreadPool(getConcurrentConnections());

    for (final LauncherLibrary library : this.launcherLibraries) {
        executor.execute(new Runnable() {

            @Override
            public void run() {
                Downloadable download = library.getDownloadable();

                if (download.needToDownload()) {
                    LogManager.info("Downloading library " + library.getFilename() + "!");
                    download.download(false);
                }
            }
        });
    }
    executor.shutdown();
    while (!executor.isTerminated()) {
    }

    for (LauncherLibrary library : this.launcherLibraries) {
        File file = library.getFile();

        if (library.shouldAutoLoad() && !Utils.addToClasspath(file)) {
            LogManager.error("Couldn't add " + file + " to the classpath!");
            if (library.shouldExitOnFail()) {
                LogManager.error("Library is necessary so launcher will exit!");
                System.exit(1);
            }
        }
    }

    LogManager.debug("Finished downloading external libraries");
}

From source file:com.mindcognition.mindraider.application.model.outline.OutlineCustodian.java

/**
 * TWiki import./*w ww  .j a  v a 2 s .c o  m*/
 * @param srcFileName
 */
private void twikiImport(String srcFileName, ProgressDialogJFrame progressDialogJFrame) throws Exception {
    logger.debug("=-> TWiki import: " + srcFileName);

    // DO NOT BUILD EXPANDED NOTEBOOK, but create new notebook, build URIs
    // and use notebook custodian
    // to add concepts into that notebook
    // o you must track path up to the root to know where to add parent

    // file reader and read line by line...
    // o from begin to the first ---++ store to the annotation of the newly
    // created notebook
    // o set label property to the name of the top level root ---+

    FileReader fileReader = new FileReader(srcFileName);
    BufferedReader bufferedReader = new BufferedReader(fileReader);

    // create new notebook in TWiki import folder
    String folderUri = MindRaider.labelCustodian.LABEL_TWIKI_IMPORT_URI;
    String notebookUri = null;
    MindRaider.labelCustodian.create("TWiki Import", MindRaider.labelCustodian.LABEL_TWIKI_IMPORT_URI);

    String[] parentConceptUris = new String[50];

    String notebookLabel, line;
    String lastConceptName = null;
    StringBuffer annotation = new StringBuffer();
    while ((line = bufferedReader.readLine()) != null) {

        // match for section
        if (Pattern.matches("^---[+]+ .*", line)) {
            // if it is root, take the label
            if (Pattern.matches("^---[+]{1} .*", line)) {
                notebookLabel = line.substring(5);
                logger.debug("LABEL: " + notebookLabel);

                notebookUri = MindRaiderVocabulary.getNotebookUri(Utils.toNcName(notebookLabel));
                String createdUri;

                while (MindRaiderConstants.EXISTS
                        .equals(createdUri = create(notebookLabel, notebookUri, null, false))) {
                    notebookUri += "_";
                }
                notebookUri = createdUri;
                MindRaider.labelCustodian.addOutline(folderUri, notebookUri);
                // set source TWiki file property
                activeOutlineResource.resource.addProperty(new SourceTwikiFileProperty(srcFileName));
                activeOutlineResource.save();
                logger.debug("Notebook created: " + notebookUri);
            } else {
                twikiImportProcessLine(progressDialogJFrame, notebookUri, parentConceptUris, lastConceptName,
                        annotation);
                lastConceptName = line;
            }
            logger.debug(" SECTION: " + line);
        } else {

            // read annotation of the current concept
            annotation.append(line);
            annotation.append("\n");
        }
    }
    // add the last opened section
    twikiImportProcessLine(progressDialogJFrame, notebookUri, parentConceptUris, lastConceptName, annotation);

    // close everything
    fileReader.close();

    // now refresh notebook outline
    ExplorerJPanel.getInstance().refresh();
    OutlineJPanel.getInstance().refresh();
    MindRaider.spidersGraph.renderModel();
    // note that back export to twiki button is enabled to according to
    // "TWiki source" property
    // of the active notebook
}

From source file:skoa.helpers.Graficos.java

/**Funcion que pasa fecha-valor de la linea a introducir en el fichero de referencia**/
private void incluirDatos(String datos) {
    String fecha = "", valor = "";
    int i = datos.indexOf("\t");
    fecha = datos.substring(0, i);/*w w  w  .j  ava 2s. c o m*/
    valor = datos.substring(i + 1);
    SimpleDateFormat formatoDelTexto = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    Date d = null;
    try {
        d = formatoDelTexto.parse(fecha);
    } catch (ParseException e1) {
        e1.printStackTrace();
    }
    File archivo = new File(ruta + "unificado.txt");
    FileReader fr = null;
    BufferedReader linea = null;
    String line;
    String ficheroTemporal = ruta + "diferenciaAplicada.txt";
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(ficheroTemporal, true)); //true, para guardar al final del fichero
        fr = new FileReader(archivo);
        linea = new BufferedReader(fr); //Se crea para leer las lineas
        String L;
        Boolean salir = false;
        int r = 0;
        while ((line = linea.readLine()) != null) { //Lectura del fichero
            L = "";
            if (salir)
                L = line;//break;
            else {
                String fechaR = "";
                int j = line.indexOf("\t");
                fechaR = line.substring(0, j);
                Date dR = null;
                dR = formatoDelTexto.parse(fechaR);
                r = d.compareTo(dR);
                if (r == 0) {
                    L = line + "\t" + valor; //fechas iguales, aade el valor del otro fichero.
                    salir = true;
                } else if (r < 0) {
                    L = fecha + "\t" + valor + "\n" + line;
                    salir = true;
                } else if (r > 0)
                    L = line; //si la fecha es mayor, se trata en la siguiente iteracion, si la hay.
            }
            bw.write(L + "\n");
        } //Fin while
        if (r > 0) { //Ultima linea, si es mayor, no se escribio en el bucle.
            L = fecha + "\t" + valor;
            bw.write(L + "\n");
        }
        bw.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != fr)
                fr.close(); //Se cierra si todo va bien.
            archivo.delete();
            File archivo2 = new File(ruta + "diferenciaAplicada.txt");
            File f = new File(ruta + "unificado.txt");
            archivo2.renameTo(f);
        } catch (Exception e2) { //Sino salta una excepcion.
            e2.printStackTrace();
        }
    }
}

From source file:com.ah.be.admin.adminOperateImpl.BeOperateHMCentOSImpl.java

public static BeLogServerInfo getLogServerInfo() {
    BeLogServerInfo oData = new BeLogServerInfo();

    File fConf = new File(BeAdminCentOSTools.AH_NMS_LOGSERVER_CONF_FILE);

    if (!fConf.exists()) {
        return oData;
    }/* ww  w  . ja  v a 2s. c o  m*/

    try {
        FileReader frConf = new FileReader(fConf);

        BufferedReader brConf = new BufferedReader(frConf);

        String strTmp;

        while ((strTmp = brConf.readLine()) != null) {
            strTmp = strTmp.trim();

            if ("".equals(strTmp)) {
                continue;
            }

            int iTmp = strTmp.indexOf(BeAdminCentOSTools.AH_NMS_LOGCONF_DEFAULT_FLAG);

            if (-1 != iTmp) {
                oData.setIsLogServer(false);

                brConf.close();

                frConf.close();

                return oData;
            }

            iTmp = strTmp.indexOf(BeAdminCentOSTools.AH_NMS_LOGCONF_NET_FLAG);

            if (-1 != iTmp) {
                brConf.close();

                frConf.close();

                return BeAdminCentOSTools.analyseNetSting(strTmp);
            }
        }

        brConf.close();

        frConf.close();

        return oData;
    } catch (Exception ex) {
        // add log
        DebugUtil.adminDebugWarn("BeAdminCentOSTools.getLogServerInfo() catch exception is: ", ex);

        return oData;
    }
}

From source file:com.photon.phresco.impl.HtmlApplicationProcessor.java

@Override
public void preBuild(ApplicationInfo appInfo) throws PhrescoException {
    FileReader reader = null;
    FileWriter writer = null;//from ww  w.ja  va2 s.  c o  m
    try {
        String rootModulePath = "";
        String subModuleName = "";
        if (StringUtils.isNotEmpty(appInfo.getRootModule())) {
            rootModulePath = Utility.getProjectHome() + appInfo.getRootModule();
            subModuleName = appInfo.getAppDirName();
        } else {
            rootModulePath = Utility.getProjectHome() + appInfo.getAppDirName();
        }
        ProjectInfo projectInfo = Utility.getProjectInfo(rootModulePath, subModuleName);
        File sourceFolderLocation = Utility.getSourceFolderLocation(projectInfo, rootModulePath, subModuleName);
        String dotPhrescoFolderPath = Utility.getDotPhrescoFolderPath(rootModulePath, subModuleName);
        File pluginInfoFile = new File(dotPhrescoFolderPath + File.separator + Constants.PACKAGE_INFO_XML);
        MojoProcessor mojoProcessor = new MojoProcessor(pluginInfoFile);
        Parameter defaultThemeParameter = mojoProcessor.getParameter(Constants.MVN_GOAL_PACKAGE,
                Constants.MOJO_KEY_DEFAULT_THEME);
        String appLevelConfigJson = getAppLevelConfigJson(sourceFolderLocation);
        if (defaultThemeParameter != null && new File(appLevelConfigJson).exists()) {
            reader = new FileReader(appLevelConfigJson);
            JsonParser parser = new JsonParser();
            Object obj = parser.parse(reader);
            JsonObject jsonObject = (JsonObject) obj;
            jsonObject.addProperty(Constants.MOJO_KEY_DEFAULT_THEME, defaultThemeParameter.getValue());
            Gson gson = new Gson();
            String json = gson.toJson(jsonObject);
            writer = new FileWriter(appLevelConfigJson);
            writer.write(json);
        }

        Parameter themesParameter = mojoProcessor.getParameter(Constants.MVN_GOAL_PACKAGE,
                Constants.MOJO_KEY_THEMES);
        if (themesParameter != null) {
            StringBuilder warConfigFilePath = new StringBuilder(dotPhrescoFolderPath).append(File.separator)
                    .append("war-config.xml");
            File warConfigFile = new File(warConfigFilePath.toString());
            WarConfigProcessor warConfigProcessor = new WarConfigProcessor(warConfigFile);
            List<String> includes = new ArrayList<String>();
            String value = themesParameter.getValue();
            if (StringUtils.isNotEmpty(value)) {
                includes.addAll(Arrays.asList(value.split(",")));
            }
            setFileSetIncludes(warConfigProcessor, "themesIncludeFile", includes);
        }
    } catch (PhrescoException e) {
        throw new PhrescoException(e);
    } catch (JAXBException e) {
        throw new PhrescoException(e);
    } catch (IOException e) {
        throw new PhrescoException(e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (writer != null) {
                writer.close();
            }
        } catch (IOException e) {
            throw new PhrescoException(e);
        }
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.validation.TraceFileValidator.java

private boolean validateTraceFile(final File traceFile, final QcContext context)
        throws IOException, ProcessorException {
    boolean valid = true;
    FileReader fReader = new FileReader(traceFile);
    BufferedReader bufferedReader = new BufferedReader(fReader);
    try {/*  w w w.  jav  a  2s .  co m*/
        final boolean barcodeMustExist = true;
        String line;
        int lineNum = 1;

        // Get barcode validity for all barcodes so that the validation can be batched when the standalone is being used
        final Map<String, Boolean> barcodeValidityMap = getBarcodeValidity(traceFile, barcodeMustExist,
                traceFile.getName(), context);

        while ((line = bufferedReader.readLine()) != null) {
            final String[] fields = line.split("\\t");
            if (fields.length < 2 || fields.length > 4) {
                throw new ProcessorException(new StringBuilder().append("Unknown format for file ")
                        .append(traceFile.getName())
                        .append(". Each line should have a trace ID and then an aliquot barcode, separated by a tab.")
                        .toString());
            } else {
                String traceId = fields[0];
                String barcode = fields[1];
                // make sure trace ID is an integer
                if (nonDigitPattern.matcher(traceId).matches() && lineNum > 1) {
                    // if not the first line, a non-integer is an error
                    context.addError(MessageFormat.format(MessagePropertyType.TRACE_FILE_VALIDATION_ERROR,
                            traceFile.getName(),
                            new StringBuilder().append(" line ").append(lineNum)
                                    .append(" contains an invalid trace ID: '").append(fields[0]).append("'")
                                    .toString()));
                    context.getArchive().setDeployStatus(Archive.STATUS_INVALID);
                    valid = false;
                }

                // if barcode not valid and not first line, is an error
                if (lineNum > 1) {

                    boolean barcodeIsValid;
                    if (context.isStandaloneValidator()) { // Retrieve the result from the Map of batched validation
                        barcodeIsValid = barcodeValidityMap.get(barcode);
                    } else {
                        barcodeIsValid = qcLiveBarcodeAndUUIDValidator.validate(barcode, context,
                                traceFile.getName(), barcodeMustExist);
                    }

                    if (!barcodeIsValid) {
                        context.addError(MessageFormat.format(MessagePropertyType.TRACE_FILE_VALIDATION_ERROR,
                                traceFile.getName(),
                                new StringBuilder().append(" line ").append(lineNum)
                                        .append(" contains an invalid barcode: ").append(fields[1])
                                        .toString()));
                        context.getArchive().setDeployStatus(Archive.STATUS_INVALID);
                        valid = false;
                    }
                }

                if (!barcodeTumorValidator.barcodeIsValidForTumor(barcode,
                        context.getArchive().getTumorType())) {
                    context.addError(MessageFormat.format(MessagePropertyType.TRACE_FILE_VALIDATION_ERROR,
                            traceFile.getName(),
                            new StringBuilder().append("File contains a barcode that does not belong to the ")
                                    .append(context.getArchive().getTumorType()).append(" disease set: ")
                                    .append(barcode).toString()));
                }
            }

            lineNum++;
        }

    } finally {
        bufferedReader.close();
        fReader.close();
        bufferedReader = null;
        fReader = null;
    }
    return valid;
}