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:edu.kit.dama.staging.util.DataOrganizationUtils.java

/**
 * Deserialize the provided from the provided file in which the tree was
 * written before using writeTreeToFile().
 *
 * @param pSource The file to read from.
 *
 * @return The tree or null if deserialization fails.
 *///from w ww . ja v a 2  s . c om
public static IFileTree readTreeFromFile(File pSource) {
    if (pSource == null) {
        throw new IllegalArgumentException("Argument 'pSource' must not be 'null'");
    }

    XStream x = new XStream();
    x.alias("fileTree", IFileTree.class);
    LOGGER.debug("Loading data organization tree to file {}", pSource.getPath());
    FileReader r = null;
    IFileTree result = null;
    try {
        r = new FileReader(pSource);
        result = (IFileTree) x.fromXML(r);
    } catch (FileNotFoundException fnfe) {
        LOGGER.error("Failed to read data organization tree.", fnfe);
    } finally {
        try {
            if (r != null) {
                r.close();
            }
        } catch (IOException ignored) {
        }
    }
    return result;
}

From source file:jGPIO.DTO.java

/**
 * @param args/*from   w  ww.  j  av  a  2  s.co  m*/
 */
public DTO() {
    // determine the OS Version
    try {
        FileReader procVersion = new FileReader("/proc/version");

        char[] buffer = new char[100];
        procVersion.read(buffer);
        procVersion.close();
        String fullVersion = new String(buffer);

        String re1 = "(Linux)"; // Word 1
        String re2 = "( )"; // Any Single Character 1
        String re3 = "(version)"; // Word 2
        String re4 = "( )"; // Any Single Character 2
        String re5 = "(\\d+)"; // Integer Number 1
        String re6 = "(\\.)"; // Any Single Character 3
        String re7 = "(\\d+)"; // Integer Number 2
        String re8 = "(\\.)"; // Any Single Character 4
        String re9 = "(\\d+)"; // Integer Number 3

        Pattern p = Pattern.compile(re1 + re2 + re3 + re4 + re5 + re6 + re7 + re8 + re9,
                Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher m = p.matcher(fullVersion);
        if (m.find()) {
            Integer linuxMajor = Integer.parseInt(m.group(5));
            Integer linuxMinor = Integer.parseInt(m.group(7));

            if (linuxMajor >= 3 && linuxMinor >= 8) {
                requireDTO = true;
            }
        }

    } catch (FileNotFoundException e) {
        System.out.println("Couldn't read the /proc/version. Please check for why it doesn't exist!\n");
        System.exit(1);
    } catch (IOException e) {
        System.out.println("Couldn't read in from /proc/version. Please cat it to ensure it is valid\n");
    }

    // no DTO generation required, so we'll exit and the customer can check
    // for requireDTO to be false
    if (!requireDTO) {
        System.out.println("No need for DTO");
        return;
    }
    // load the file containing the GPIO Definitions from the property file
    try {
        definitionFile = System.getProperty("gpio_definition");
        // No definition file, try an alternative name
        if (definitionFile == null) {
            System.getProperty("gpio_definitions");
        }
        if (definitionFile == null) {
            // Still no definition file, try to autodetect it.
            definitionFile = autoDetectSystemFile();
        }
        JSONParser parser = new JSONParser();
        System.out.println("Using GPIO Definitions file: " + definitionFile);
        pinDefinitions = (JSONArray) parser.parse(new FileReader(definitionFile));
    } catch (NullPointerException NPE) {
        System.out.println(
                "Could not read the property for gpio_definition, please set this since you are on Linux kernel 3.8 or above");
        System.exit(-1);
    } catch (FileNotFoundException e) {
        System.out.println("Could not read the GPIO Definitions file");
        e.printStackTrace();
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(-1);
    }

}

From source file:com.photon.phresco.framework.rest.api.LoginService.java

/**
 * Authenticate User for login.//from   w w w.jav a 2  s  .c  om
 *
 * @param credentials the credentials
 * @return the response
 */
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticate(@Context HttpServletRequest request, @Context HttpServletResponse response,
        Credentials credentials) {
    User user = null;
    ResponseInfo<User> responseData = new ResponseInfo<User>();

    try {
        user = doLogin(credentials);
        if (user == null) {
            status = RESPONSE_STATUS_FAILURE;
            errorCode = PHR110001;
            ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, null, null, status,
                    errorCode);
            return Response.status(Status.OK).entity(finalOuptut).header("Access-Control-Allow-Origin", "*")
                    .build();
        }
        if (!user.isPhrescoEnabled()) {
            status = RESPONSE_STATUS_FAILURE;
            errorCode = PHR110002;
            ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, null, null, status,
                    errorCode);
            return Response.status(Status.OK).entity(finalOuptut).header("Access-Control-Allow-Origin", "*")
                    .build();
        }

        List<Customer> customers = user.getCustomers();
        //Collections.sort(customers, sortCusNameInAlphaOrder());

        File tempPath = new File(Utility.getPhrescoTemp() + File.separator + "user.json");
        String userId = user.getId();
        JSONObject userjson = new JSONObject();
        JSONParser parser = new JSONParser();
        String customerId = "photon";
        if (tempPath.exists()) {
            FileReader reader = new FileReader(tempPath);
            userjson = (JSONObject) parser.parse(reader);
            customerId = (String) userjson.get(userId);
            reader.close();
        }
        userjson.put(userId, customerId);

        List<String> customerList = new ArrayList<String>();
        for (Customer c : customers) {
            customerList.add(c.getId());
        }

        if ((StringUtils.isEmpty(customerId) || "photon".equals(customerId))
                && customerList.contains("photon")) {
            customerId = "photon";
        }

        FileWriter writer = new FileWriter(tempPath);
        writer.write(userjson.toString());
        writer.close();

        ServiceManager serviceManager = CONTEXT_MANAGER_MAP.get(credentials.getUsername());
        UserPermissions userPermissions = FrameworkUtil.getUserPermissions(serviceManager, user);
        user.setPermissions(userPermissions);

        status = RESPONSE_STATUS_SUCCESS;
        successCode = PHR100001;
        ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, null, user, status, successCode);
        request.getSession().setAttribute("user", user);
        return Response.ok(finalOuptut).header("Access-Control-Allow-Origin", "*").build();
    } catch (PhrescoWebServiceException e) {
        if (e.getResponse().getStatus() == 204) {
            status = RESPONSE_STATUS_ERROR;
            errorCode = PHR110003;
            ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, e, null, status, errorCode);
            return Response.status(Status.OK).entity(finalOuptut).header("Access-Control-Allow-Origin", "*")
                    .build();
        } else {
            status = RESPONSE_STATUS_ERROR;
            errorCode = PHR110004;
            ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, e, null, status, errorCode);
            return Response.status(Status.OK).entity(finalOuptut).header("Access-Control-Allow-Origin", "*")
                    .build();
        }
    } catch (IOException e) {
        status = RESPONSE_STATUS_ERROR;
        errorCode = PHR110005;
        ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, e, null, status, errorCode);
        return Response.status(Status.OK).entity(finalOuptut).header("Access-Control-Allow-Origin", "*")
                .build();
    } catch (ParseException e) {
        status = RESPONSE_STATUS_ERROR;
        errorCode = PHR110006;
        ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, e, null, status, errorCode);
        return Response.status(Status.OK).entity(finalOuptut).header("Access-Control-Allow-Origin", "*")
                .build();
    } catch (PhrescoException e) {
        status = RESPONSE_STATUS_ERROR;
        errorCode = PHR110007;
        ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, e, null, status, errorCode);
        return Response.status(Status.OK).entity(finalOuptut).header("Access-Control-Allow-Origin", "*")
                .build();
    }
}

From source file:guineu.modules.filter.report.areaVSheight.ReportTask.java

/**
 * Read the file with the name of the samples in order
 * @throws java.lang.Exception/*from w  w w  . j  a  va2s .com*/
 */
private void readFile() throws Exception {
    FileReader fr = null;
    try {
        fr = new FileReader(new File(fileName));
    } catch (Exception e) {
        throw e;
    }
    CsvReader reader = new CsvReader(fr);
    String splitRow[];
    while (reader.readRecord()) {
        splitRow = reader.getValues();
        this.sampleNames.add(splitRow[0]);
    }
    reader.close();
    fr.close();
}

From source file:com.sun.faban.harness.webclient.Uploader.java

private String getRunIdTimestamp(String runId, String dir) {
    char[] cBuf = null;
    String[] status = new String[2];
    int length = -1;
    try {/*from  w  w w  .ja v  a 2s.  c o  m*/
        FileReader reader = new FileReader(dir + runId + '/' + Config.RESULT_INFO);
        cBuf = new char[128];
        length = reader.read(cBuf);
        reader.close();
    } catch (IOException e) {
        // Do nothing, length = -1.
    }
    String content = new String(cBuf, 0, length);
    int idx = content.indexOf('\t');
    if (idx != -1) {
        status[0] = content.substring(0, idx).trim();
        status[1] = content.substring(++idx).trim();
    } else {
        status[0] = content.trim();
    }
    return status[1];
}

From source file:com.openedit.util.FileUtils.java

public void replace(File inFile, String inKey, String inNewKey) throws Exception {
    FileReader filereader = new FileReader(inFile);
    StringWriter out = new StringWriter();
    new OutputFiller().fill(filereader, out);
    filereader.close();
    String readstring = out.toString();
    readstring = readstring.replace(inKey, inNewKey);
    FileWriter filewriter = new FileWriter(inFile);
    new OutputFiller().fill(new StringReader(readstring), filewriter);
    filewriter.close();//w w  w . j a v a 2  s  . co m
}

From source file:ServerConfigurations.server.AdminConfiguration.Controller.java

public void loadConfiguration() throws IOException {
    XStream xstream = new XStream();
    xstream.setClassLoader(Controller.configurations.getClass().getClassLoader());
    xstream.setClassLoader(ServerConfiguration.class.getClassLoader());
    xstream.setClassLoader(ServerConfigurationProperty.class.getClassLoader());
    xstream.setClassLoader(Template.class.getClassLoader());
    xstream.setClassLoader(TemplateProperty.class.getClassLoader());
    xstream.processAnnotations(ServerConfigurations.class);
    FileReader fileReader = new FileReader(this.configFilePath);
    ServerConfigurations configurations = (ServerConfigurations) xstream.fromXML(fileReader);
    fileReader.close();

    // Copy the values, because we need it on the original shared (bean),
    // which is a singleton
    if (configurations.getConfigurations() != null) {
        for (ServerConfiguration configuration : configurations.getConfigurations()) {
            Controller.configurations.setConfiguration(configuration);
        }/*from  w w  w.j ava 2  s  .  c  o  m*/
    }
    if (configurations.getTemplates() != null) {
        for (Template template : configurations.getTemplates()) {
            Controller.configurations.setTemplate(template);
        }
    }
    saveConfiguration();
}

From source file:org.apache.wsrp4j.persistence.xml.driver.PersistentHandlerImpl.java

/**
 * Restores a single XML file into the persistentDataObject. The filename
 * used is the filename stored in the PersistentFileInformation, contained
 * in the PersistentDataObject./*from  w  ww. j a  v  a  2s .  co  m*/
 *
 * @param persistentDataObject
 * @return PersistentDataObjct
 *
 * @throws WSRPException
 */
public PersistentDataObject restore(PersistentDataObject persistentDataObject) throws WSRPException {

    String MN = "restore";

    if (log.isDebugEnabled()) {
        log.debug(Utility.strEnter(MN));
    }

    Mapping mapping = null;
    Unmarshaller unmarshaller = null;

    try {

        PersistentInformationXML persistentInformation = (PersistentInformationXML) persistentDataObject
                .getPersistentInformation();

        if (persistentInformation.getMappingFileName() != null) {

            mapping = new Mapping();
            mapping.loadMapping(persistentInformation.getMappingFileName());
            unmarshaller = new Unmarshaller(mapping);
        }

        File file = new File(persistentInformation.getFilename());

        if (file.isFile()) {

            FileReader fileReader = new FileReader(file);

            try {

                ((PersistentDataObjectXML) persistentDataObject).unMarshalFile(fileReader, unmarshaller);
                fileReader.close();

                Object o = persistentDataObject.getLastElement();
                int hashCode = o.hashCode();
                String code = new Integer(hashCode).toString();
                _filenameMap.put(code, file.getAbsolutePath());

                if (log.isDebugEnabled()) {
                    log.debug("File: " + file.getAbsolutePath() + " added with hashCode = " + code);
                }

            } catch (Exception e) {

                // could not restore a single file from persistent store
                WSRPXHelper.throwX(log, ErrorCodes.RESTORE_OBJECT_ERROR, e);
            }

        }

    } catch (Exception e) {

        // castor persistent failure
        WSRPXHelper.throwX(log, ErrorCodes.RESTORE_OBJECT_ERROR, e);
    }

    if (log.isDebugEnabled()) {
        log.debug(Utility.strExit(MN));
    }

    return persistentDataObject;

}

From source file:org.crawler.LinkExtractor.java

private void loadExistingLinks(String imap) throws Exception {
    crawledLinks = new HashMap<>();

    FileReader fr = new FileReader(imap);
    BufferedReader br = new BufferedReader(fr);
    String line = null;//from  w ww.ja va  2 s.c  om

    while ((line = br.readLine()) != null) {
        String[] tokens = line.split("\\t");
        int questionId = Integer.parseInt(tokens[0]);
        crawledLinks.put(questionId, new Integer(questionId));
    }

    if (br != null)
        br.close();
    if (fr != null)
        fr.close();
}

From source file:mi.RankInfo.java

void loadRefs() throws Exception {
    String refFileName = prop.getProperty("mi.ref.out");
    FileReader fr = new FileReader(refFileName);
    BufferedReader br = new BufferedReader(fr);

    String line;// w  ww .ja v a 2  s .  co  m
    int i = 0;
    while ((line = br.readLine()) != null) {
        this.r[i] = new FloatByteRcd(i, line);
        i++;
    }
    br.close();
    fr.close();
}