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:org.codehaus.enunciate.modules.swagger.SwaggerDeploymentModule.java

@Override
public void doFreemarkerGenerate() throws IOException, TemplateException {
    EnunciateFreemarkerModel model = getModel();

    File artifactDir = new File(getGenerateDir(), getDir());
    model.setFileOutputDirectory(artifactDir);
    boolean upToDate = isUpToDate(artifactDir);
    if (!upToDate) {
        Map<String, Map<String, List<ResourceMethod>>> facetsToResourceMethods = new TreeMap<String, Map<String, List<ResourceMethod>>>();
        Map<String, String> facetsToDocs = new TreeMap<String, String>();
        for (RootResource rootResource : getModelInternal().getRootResources()) {
            for (ResourceMethod resourceMethod : rootResource.getResourceMethods(true)) {
                if (FacetFilter.accept(resourceMethod)) {
                    Set<Facet> facets = resourceMethod.getFacets();
                    if (facets != null) {
                        for (Facet facet : facets) {
                            if (facet.getName().equals(getGroupRestResources())) {
                                Map<String, List<ResourceMethod>> group = facetsToResourceMethods
                                        .get(facet.getValue());
                                if (group == null) {
                                    group = new TreeMap<String, List<ResourceMethod>>();
                                    facetsToResourceMethods.put(facet.getValue(), group);
                                }/*from   w  w w .  j av a 2  s  .c om*/
                                String subcontext = (String) resourceMethod.getMetaData()
                                        .get("defaultSubcontext");
                                if (subcontext == null) {
                                    subcontext = "/rest";
                                }
                                String fullpath = subcontext + resourceMethod.getFullpath();
                                List<ResourceMethod> methods = group.get(fullpath);
                                if (methods == null) {
                                    methods = new ArrayList<ResourceMethod>();
                                    group.put(fullpath, methods);
                                }
                                methods.add(resourceMethod);
                                facetsToDocs.put(facet.getValue(), facet.getDocumentation());
                            }
                        }
                    }
                }
            }
        }
        model.setVariable("uniqueContentTypes", new UniqueContentTypesMethod());
        model.put("datatypeNameFor", new DatatypeNameForMethod(model));
        model.put("facetsToResourceMethods", facetsToResourceMethods);
        model.put("facetsToDocs", facetsToDocs);
        model.put("swaggerDir", artifactDir.getName());
        buildBase(artifactDir);
        processTemplate(getTemplateURL(), model);
    } else {
        info("Skipping generation of Swagger since everything appears up-to-date...");
    }

    Set<File> jsonFilesToValidate = new HashSet<File>();
    gatherJsonFiles(jsonFilesToValidate, artifactDir);
    ObjectMapper mapper = new ObjectMapper();
    for (File file : jsonFilesToValidate) {
        FileReader reader = new FileReader(file);
        try {
            mapper.readTree(reader);
        } catch (JsonProcessingException e) {
            warn("Error processing %s.", file.getAbsolutePath());
            throw e;
        } finally {
            reader.close();
        }
    }

    //add the webapp fragment...
    BaseWebAppFragment webAppFragment = new BaseWebAppFragment(getName());
    webAppFragment.setBaseDir(getGenerateDir());
    ArrayList<WebAppComponent> filters = new ArrayList<WebAppComponent>();
    if (isApplyBaseUriFilter()) {
        WebAppComponent swaggerFilter = new WebAppComponent();
        swaggerFilter.setName("swagger-ui-filter");
        swaggerFilter.setClassname("org.codehaus.enunciate.webapp.IDLFilter");
        HashMap<String, String> initParams = new HashMap<String, String>();
        initParams.put("assumed-base-address", getModel().getBaseDeploymentAddress());
        initParams.put("match-prefix", "\"");
        initParams.put("content-type", "application/json");
        swaggerFilter.setInitParams(initParams);
        TreeSet<String> paths = new TreeSet<String>();

        for (File json : jsonFilesToValidate) {
            paths.add("/" + artifactDir.getName() + "/" + json.getName());
        }

        swaggerFilter.setUrlMappings(paths);
        filters.add(swaggerFilter);
    }

    webAppFragment.setFilters(filters);
    getEnunciate().addWebAppFragment(webAppFragment);

    getEnunciate().addArtifact(new FileArtifact(getName(), "swagger", artifactDir));
}

From source file:org.clipsmonitor.monitor2015.RescueGenMap.java

public int[] GetJsonMapDimension(File jsonMap) {

    try {//  w  w  w . j  ava 2  s  . com
        //converto il file in un oggetto JSON
        FileReader jsonreader = new FileReader(jsonMap);
        char[] chars = new char[(int) jsonMap.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());

        return new int[] { NumCellX, NumCellY };
    } catch (JSONException ex) {

        AppendLogMessage(ex.getMessage(), "error");
    } catch (IOException ex) {
        AppendLogMessage(ex.getMessage(), "error");
    } catch (NumberFormatException ex) {
        AppendLogMessage(ex.getMessage(), "error");
    }

    return null;
}

From source file:org.clipsmonitor.monitor2015.RescueGenMap.java

/**
 * Legge da un file Json e imposta gli attributi del robot  
 * @param jsonFile /*from w  w  w  . j a  v a2 s  .c om*/
 */

public void LoadJsonRobotParams(File jsonFile) {
    try {
        //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);
        agentposition = new int[] { json.getInt("robot_x"), json.getInt("robot_y") };
        defaultagentposition = new int[] { json.getInt("robot_x_default"), json.getInt("robot_y_default") };

        direction = json.getString("robot_direction");
        loaded = json.getString("robot_loaded");
        scene[agentposition[0]][agentposition[1]] += "+" + "agent_" + direction + "_" + loaded;
        defaulagentcondition = scene[agentposition[0]][agentposition[1]];
        move = clone(scene);
        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:com.netscape.cmstools.ca.CACertFindCLI.java

public void execute(String[] args) throws Exception {
    // Always check for "--help" prior to parsing
    if (Arrays.asList(args).contains("--help")) {
        printHelp();/*from   ww w  . j  av a 2  s. co  m*/
        return;
    }

    CommandLine cmd = parser.parse(options, args);

    String[] cmdArgs = cmd.getArgs();

    if (cmdArgs.length != 0) {
        throw new Exception("Too many arguments specified.");
    }

    CertSearchRequest searchData = null;
    String fileName = null;

    if (cmd.hasOption("input")) {
        fileName = cmd.getOptionValue("input");
        if (fileName == null || fileName.length() < 1) {
            throw new Exception("No file name specified.");
        }
    }

    if (fileName != null) {
        FileReader reader = null;
        try {
            reader = new FileReader(fileName);
            searchData = CertSearchRequest.valueOf(reader);

        } finally {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

    } else {
        searchData = new CertSearchRequest();
    }

    String s = cmd.getOptionValue("start");
    Integer start = s == null ? null : Integer.valueOf(s);

    s = cmd.getOptionValue("size");
    Integer size = s == null ? null : Integer.valueOf(s);

    addSearchAttribute(cmd, searchData);

    CACertClient certClient = certCLI.getCertClient();
    CertDataInfos certs = certClient.findCerts(searchData, start, size);

    MainCLI.printMessage(certs.getTotal() + " entries found");
    if (certs.getTotal() == 0)
        return;

    boolean first = true;

    Collection<CertDataInfo> entries = certs.getEntries();
    for (CertDataInfo cert : entries) {
        if (first) {
            first = false;
        } else {
            System.out.println();
        }

        CACertCLI.printCertInfo(cert);
    }

    MainCLI.printMessage("Number of entries returned " + certs.getEntries().size());
}

From source file:ke.co.tawi.babblesms.server.persistence.utils.DbFileUtils.java

/**
 * This is used to import the results of CSV text file to the database.
 *
 * @param sqlQuery//  w  w w .  j ava2s  .c om
 * @param fileLocation this should include the full path of the file e.g.
 * /tmp/myFile.csv
 *
 * @return whether the action was successful or not
 */
public boolean importCSVToDatabase(String sqlQuery, File fileLocation) {
    boolean success = false;

    FileReader fileReader;

    try (
            // Return a database connection that is not pooled
            // to enable the connection to be cast to BaseConnection
            Connection conn = dbCredentials.getJdbcConnection();) {

        String fileName = fileLocation.getName();
        if (!StringUtils.contains(fileName, "null")) {

            fileReader = new FileReader(fileLocation);

            CopyManager copyManager = new CopyManager((BaseConnection) conn);

            copyManager.copyIn(sqlQuery, fileReader);

            fileReader.close();

            success = true;
        }

    } catch (SQLException e) {
        logger.error(
                "SQLException while importing results of  '" + fileLocation + "' and SQL query: " + sqlQuery);
        logger.error(ExceptionUtils.getStackTrace(e));
        success = false;

    } catch (IOException e) {
        logger.error(
                "SQLException while importing results of  '" + fileLocation + "' and SQL query: " + sqlQuery);
        logger.error(ExceptionUtils.getStackTrace(e));
        success = false;
    }

    return success;
}

From source file:org.apache.metron.parsing.parsers.MetronGrok.java

/**
 * Add patterns to {@code Grok} from the given file.
 *
 * @param file : Path of the grok pattern
 * @throws Exception//w  w  w.  ja  v a 2  s . c o  m
 */
public void addPatternFromFile(String file) throws Exception {

    File f = new File(file);
    if (!f.exists()) {
        throw new Exception("Pattern not found");
    }

    if (!f.canRead()) {
        throw new Exception("Pattern cannot be read");
    }

    FileReader r = null;
    try {
        r = new FileReader(f);
        addPatternFromReader(r);
    } catch (FileNotFoundException e) {
        throw new Exception(e.getMessage());
    } catch (@SuppressWarnings("hiding") IOException e) {
        throw new Exception(e.getMessage());
    } finally {
        try {
            if (r != null) {
                r.close();
            }
        } catch (IOException io) {
            // TODO(anthony) : log the error
        }
    }
}

From source file:com.ephesoft.dcma.util.FileUtils.java

/**
 * To copy all XML files.// w  w w  .  j a  va2 s .c  o m
 * @param fromLoc {@link String}
 * @param toLoc {@link String}
 */
public static void copyAllXMLFiles(String fromLoc, String toLoc) {
    File inputFolder = new File(fromLoc);
    File outputFolder = new File(toLoc);
    File[] inputFiles = inputFolder.listFiles();
    for (int index = 0; index < inputFiles.length; index++) {
        if (inputFiles[index].getName().endsWith(EXTENSION_XML)) {
            FileReader input;
            FileWriter out;
            int character;
            try {
                input = new FileReader(inputFiles[index]);
                out = new FileWriter(outputFolder + File.separator + inputFiles[index].getName());
                character = input.read();
                while (character != -1) {
                    out.write(character);
                    character = input.read();
                }
                if (input != null) {
                    input.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (FileNotFoundException e) {
                LOGGER.error("Exception while reading files:" + e);
            } catch (IOException e) {
                LOGGER.error("Exception while copying files:" + e);
            }
        }
    }

}

From source file:org.ala.hbase.RepoDataLoader.java

/**
 * Scan through the supplied directories.
 *
 * @param dirs// w w  w. j  a  v  a  2s .c  o m
 */
public void scanDirectory(File[] dirs) {

    int filesRead = 0;
    int propertiesSynced = 0;

    for (File currentDir : dirs) {
        logger.info("Reading directory: " + currentDir.getAbsolutePath());
        Iterator<File> fileIterator = FileUtils.iterateFiles(currentDir, null, true);
        while (fileIterator.hasNext()) {
            File currentFile = fileIterator.next();
            if (currentFile.getName().equals(FileType.RDF.toString())) {
                filesRead++;
                String infosourceId = currentFile.getParentFile().getParentFile().getParentFile().getName();
                String infoSourceUid = infoSourceDAO.getUidByInfosourceId(String.valueOf(infosourceId));
                //read the dublin core in the same directory - determine if its an image
                try {
                    logger.info("Reading file: " + currentFile.getAbsolutePath());
                    FileReader reader = new FileReader(currentFile);
                    List<Triple> triples = TurtleUtils.readTurtle(reader);
                    //close the reader
                    reader.close();

                    String currentSubject = null;
                    List<Triple> splitBySubject = new ArrayList<Triple>();

                    String guid = null;
                    //iterate through triple, splitting the triples by subject
                    for (Triple triple : triples) {

                        if (currentSubject == null) {
                            currentSubject = triple.subject;
                        } else if (!currentSubject.equals(triple.subject)) {
                            //sync these triples
                            //                        /data/bie/1036/23/235332/rdf

                            guid = sync(currentFile, splitBySubject, infosourceId, infoSourceUid);
                            if (guid != null && guid.trim().length() > 0) {
                                propertiesSynced++;
                            }
                            //clear list
                            splitBySubject.clear();
                            currentSubject = triple.subject;
                        }
                        splitBySubject.add(triple);
                    }

                    //sort out the buffer
                    if (!splitBySubject.isEmpty()) {
                        guid = sync(currentFile, splitBySubject, infosourceId, infoSourceUid);
                        if (guid != null && guid.trim().length() > 0) {
                            propertiesSynced++;
                        }
                    }

                    if (gList && guid != null) {
                        guidOut.write((guid + "\n").getBytes());
                    }

                    guidList.add(guid);

                } catch (Exception e) {
                    logger.error("Error reading triples from file: '" + currentFile.getAbsolutePath() + "', "
                            + e.getMessage(), e);
                }
            }
        }
        logger.info("InfosourceId: " + currentDir.getName() + " - Files read: " + filesRead
                + ", files matched: " + propertiesSynced);
        totalFilesRead += filesRead;
        totalPropertiesSynced += propertiesSynced;
    }
}

From source file:library.memorymonitor.ProcfsBasedProcessTree.java

/**
 * Construct the ProcessInfo using the process' PID and procfs rooted at the
 * specified directory and return the same. It is provided mainly to assist
 * testing purposes.//from   ww w .j  a va 2  s  .  co m
 * 
 * Returns null on failing to read from procfs,
 *
 * @param pinfo ProcessInfo that needs to be updated
 * @param procfsDir root of the proc file system
 * @return updated ProcessInfo, null on errors.
 */
private static ProcessInfo constructProcessInfo(ProcessInfo pinfo, String procfsDir) {
    ProcessInfo ret = null;
    // Read "procfsDir/<pid>/stat" file
    BufferedReader in = null;
    FileReader fReader = null;
    try {
        File pidDir = new File(procfsDir, pinfo.getPid());
        fReader = new FileReader(new File(pidDir, PROCFS_STAT_FILE));
        in = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        // The process vanished in the interim!
        return ret;
    }

    ret = pinfo;
    try {
        String str = in.readLine(); // only one line
        Matcher m = PROCFS_STAT_FILE_FORMAT.matcher(str);
        boolean mat = m.find();
        if (mat) {
            // Set (name) (ppid) (pgrpId) (session) (utime) (stime) (vsize) (rss)
            pinfo.updateProcessInfo(m.group(2), m.group(3), Integer.parseInt(m.group(4)),
                    Integer.parseInt(m.group(5)), Long.parseLong(m.group(7)), new BigInteger(m.group(8)),
                    Long.parseLong(m.group(10)), Long.parseLong(m.group(11)));
        }
    } catch (IOException io) {
        LOG.warn("Error reading the stream " + io);
        ret = null;
    } finally {
        // Close the streams
        try {
            fReader.close();
            try {
                in.close();
            } catch (IOException i) {
                LOG.warn("Error closing the stream " + in);
            }
        } catch (IOException i) {
            LOG.warn("Error closing the stream " + fReader);
        }
    }

    return ret;
}

From source file:cs.ox.ac.uk.gsors.GroupPreferencesTest1.java

public String getStringFile(String input) throws IOException {
    // Read the content of the current program
    final FileReader fr = new FileReader(input);
    final StringBuilder sb = new StringBuilder();
    int ch = -1;/*  www.j  a  va 2s.  com*/
    while ((ch = fr.read()) >= 0) {
        sb.append((char) ch);
    }
    final String program = sb.toString();
    fr.close();
    return program;
}