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.apache.axis.handlers.JWSHandler.java

/**
 * If our path ends in the right file extension (*.jws), handle all the
 * work necessary to compile the source file if it needs it, and set
 * up the "proxy" RPC service surrounding it as the MessageContext's
 * active service./*from ww w. ja v  a  2 s.  c  o m*/
 *
 */
protected void setupService(MessageContext msgContext) throws Exception {
    // FORCE the targetService to be JWS if the URL is right.
    String realpath = msgContext.getStrProp(Constants.MC_REALPATH);
    String extension = (String) getOption(OPTION_JWS_FILE_EXTENSION);
    if (extension == null)
        extension = DEFAULT_JWS_FILE_EXTENSION;

    if ((realpath != null) && (realpath.endsWith(extension))) {
        /* Grab the *.jws filename from the context - should have been */
        /* placed there by another handler (ie. HTTPActionHandler)     */
        /***************************************************************/
        String jwsFile = realpath;
        String rel = msgContext.getStrProp(Constants.MC_RELATIVE_PATH);

        // Check for file existance, report error with
        // relative path to avoid giving out directory info.
        File f2 = new File(jwsFile);
        if (!f2.exists()) {
            throw new FileNotFoundException(rel);
        }

        if (rel.charAt(0) == '/') {
            rel = rel.substring(1);
        }

        int lastSlash = rel.lastIndexOf('/');
        String dir = null;

        if (lastSlash > 0) {
            dir = rel.substring(0, lastSlash);
        }

        String file = rel.substring(lastSlash + 1);

        String outdir = msgContext.getStrProp(Constants.MC_JWS_CLASSDIR);
        if (outdir == null)
            outdir = ".";

        // Build matching directory structure under the output
        // directory.  In other words, if we have:
        //    /webroot/jws1/Foo.jws
        //
        // That will be compiled to:
        //    .../jwsOutputDirectory/jws1/Foo.class
        if (dir != null) {
            outdir = outdir + File.separator + dir;
        }

        // Confirm output directory exists.  If not, create it IF we're
        // allowed to.
        // !!! TODO: add a switch to control this.
        File outDirectory = new File(outdir);
        if (!outDirectory.exists()) {
            outDirectory.mkdirs();
        }

        if (log.isDebugEnabled())
            log.debug("jwsFile: " + jwsFile);

        String jFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1)
                + "java";
        String cFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1)
                + "class";

        if (log.isDebugEnabled()) {
            log.debug("jFile: " + jFile);
            log.debug("cFile: " + cFile);
            log.debug("outdir: " + outdir);
        }

        File f1 = new File(cFile);

        /* Get the class */
        /*****************/
        String clsName = null;
        //clsName = msgContext.getStrProp(Constants.MC_RELATIVE_PATH);
        if (clsName == null)
            clsName = f2.getName();
        if (clsName != null && clsName.charAt(0) == '/')
            clsName = clsName.substring(1);

        clsName = clsName.substring(0, clsName.length() - extension.length());
        clsName = clsName.replace('/', '.');

        if (log.isDebugEnabled())
            log.debug("ClsName: " + clsName);

        /* Check to see if we need to recompile */
        /****************************************/
        if (!f1.exists() || f2.lastModified() > f1.lastModified()) {
            /* If the class file doesn't exist, or it's older than the */
            /* java file then recompile the java file.                 */
            /* Start by copying the *.jws file to *.java               */
            /***********************************************************/
            log.debug(Messages.getMessage("compiling00", jwsFile));
            log.debug(Messages.getMessage("copy00", jwsFile, jFile));
            FileReader fr = new FileReader(jwsFile);
            FileWriter fw = new FileWriter(jFile);
            char[] buf = new char[4096];
            int rc;
            while ((rc = fr.read(buf, 0, 4095)) >= 0)
                fw.write(buf, 0, rc);
            fw.close();
            fr.close();

            /* Now run javac on the *.java file */
            /************************************/
            log.debug("javac " + jFile);
            // Process proc = rt.exec( "javac " + jFile );
            // proc.waitFor();
            Compiler compiler = CompilerFactory.getCompiler();

            compiler.setClasspath(ClasspathUtils.getDefaultClasspath(msgContext));
            compiler.setDestination(outdir);
            compiler.addFile(jFile);

            boolean result = compiler.compile();

            /* Delete the temporary *.java file and check return code */
            /**********************************************************/
            (new File(jFile)).delete();

            if (!result) {
                /* Delete the *class file - sometimes it gets created even */
                /* when there are errors - so erase it so it doesn't       */
                /* confuse us.                                             */
                /***********************************************************/
                (new File(cFile)).delete();

                Document doc = XMLUtils.newDocument();

                Element root = doc.createElementNS("", "Errors");
                StringBuffer message = new StringBuffer("Error compiling ");
                message.append(jFile);
                message.append(":\n");

                List errors = compiler.getErrors();
                int count = errors.size();
                for (int i = 0; i < count; i++) {
                    CompilerError error = (CompilerError) errors.get(i);
                    if (i > 0)
                        message.append("\n");
                    message.append("Line ");
                    message.append(error.getStartLine());
                    message.append(", column ");
                    message.append(error.getStartColumn());
                    message.append(": ");
                    message.append(error.getMessage());
                }
                root.appendChild(doc.createTextNode(message.toString()));
                throw new AxisFault("Server.compileError", Messages.getMessage("badCompile00", jFile), null,
                        new Element[] { root });
            }
            ClassUtils.removeClassLoader(clsName);
            // And clean out the cached service.
            soapServices.remove(clsName);
        }

        ClassLoader cl = ClassUtils.getClassLoader(clsName);
        if (cl == null) {
            cl = new JWSClassLoader(clsName, msgContext.getClassLoader(), cFile);
        }

        msgContext.setClassLoader(cl);

        /* Create a new RPCProvider - this will be the "service"   */
        /* that we invoke.                                                */
        /******************************************************************/
        // Cache the rpc service created to handle the class.  The cache
        // is based on class name, so only one .jws/.jwr class can be active
        // in the system at a time.
        SOAPService rpc = (SOAPService) soapServices.get(clsName);
        if (rpc == null) {
            rpc = new SOAPService(new RPCProvider());
            rpc.setName(clsName);
            rpc.setOption(RPCProvider.OPTION_CLASSNAME, clsName);
            rpc.setEngine(msgContext.getAxisEngine());

            // Support specification of "allowedMethods" as a parameter.
            String allowed = (String) getOption(RPCProvider.OPTION_ALLOWEDMETHODS);
            if (allowed == null)
                allowed = "*";
            rpc.setOption(RPCProvider.OPTION_ALLOWEDMETHODS, allowed);
            // Take the setting for the scope option from the handler
            // parameter named "scope"
            String scope = (String) getOption(RPCProvider.OPTION_SCOPE);
            if (scope == null)
                scope = Scope.DEFAULT.getName();
            rpc.setOption(RPCProvider.OPTION_SCOPE, scope);

            rpc.getInitializedServiceDesc(msgContext);

            soapServices.put(clsName, rpc);
        }

        // Set engine, which hooks up type mappings.
        rpc.setEngine(msgContext.getAxisEngine());

        rpc.init(); // ??

        // OK, this is now the destination service!
        msgContext.setService(rpc);
    }

    if (log.isDebugEnabled()) {
        log.debug("Exit: JWSHandler::invoke");
    }
}

From source file:com.elevenpaths.googleindexretriever.GoogleSearch.java

public void loadKeywords() throws FileNotFoundException, IOException {
    FileReader file = new FileReader("keywords.txt");
    BufferedReader reader = new BufferedReader(file);
    String line;//ww w  .  java 2s  . c o m

    while ((line = reader.readLine()) != null) {
        if (!line.startsWith("#")) {
            keywords.add(line);
        }
    }

    reader.close();
    file.close();
}

From source file:org.apache.openjpa.lib.meta.ClassArgParser.java

/**
 * Returns the classes named in the given common format metadata file.
 *//*from  w  w  w.  java  2 s.  co m*/
private Collection<String> getFromMetaDataFile(File file) throws IOException {
    FileReader in = null;
    try {
        in = new FileReader(file);
        return getFromMetaData(in);
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException ioe) {
            }
    }
}

From source file:com.elevenpaths.googleindexretriever.GoogleSearch.java

public void loadSpamKeywords() throws FileNotFoundException, IOException {
    FileReader file = new FileReader("spamKeywords.txt");
    BufferedReader reader = new BufferedReader(file);
    String line;/*w  ww  . j a v  a  2 s .co  m*/

    while ((line = reader.readLine()) != null) {
        if (!line.startsWith("#")) {
            keywordsSpam.add(line);
        }
    }

    reader.close();
    file.close();
}

From source file:edu.ucsf.rbvi.CyAnimator.internal.io.LoadSessionListener.java

public void handleEvent(SessionLoadedEvent e) {
    // Reset CyAnimator
    FrameManager.reset();//w  w w.  ja  va 2 s .  co m

    // Get the session
    CySession session = e.getLoadedSession();
    /*
    System.out.println("Session: "+session);
    for (String s: session.getAppFileListMap().keySet()) {
       System.out.println(s+":");
       for (File f: session.getAppFileListMap().get(s)) {
    System.out.println("File: "+f);
       }
    }
    */
    if (!session.getAppFileListMap().containsKey("CyAnimator"))
        return;

    // System.out.println("We have animation information!");

    // Ask the user if they want to load the frames?
    //
    try {
        File frameListFile = session.getAppFileListMap().get("CyAnimator").get(0);
        FileReader reader = new FileReader(frameListFile);
        BufferedReader bReader = new BufferedReader(reader);
        JSONParser parser = new JSONParser();
        Object jsonObject = parser.parse(bReader);

        // For each root network, get the 
        if (jsonObject instanceof JSONArray) {
            for (Object obj : (JSONArray) jsonObject) {
                try {
                    FrameManager.restoreFramesFromSession(registrar, session, (JSONObject) obj);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        bReader.close();
        reader.close();
    } catch (FileNotFoundException fnf) {
        System.out.println("File not found exception: " + fnf.getMessage());
    } catch (IOException ioe) {
        System.out.println("IO exception: " + ioe.getMessage());
    } catch (ParseException pe) {
        System.out.println("Unable to parse JSON file: " + pe.getMessage());
        pe.printStackTrace();
    }

}

From source file:com.btoddb.chronicle.FileTestUtils.java

public Matcher<? super File> hasCount(final int count) {
    return new TypeSafeMatcher<File>() {
        String errorDesc;/*from   ww w .ja v  a 2  s  . c  o  m*/
        String expected;
        String got;

        @Override
        protected boolean matchesSafely(final File f) {
            FileReader fr = null;
            try {
                fr = new FileReader(f);
                return count == IOUtils.readLines(fr).size();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            } finally {
                if (null != fr) {
                    try {
                        fr.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

        @Override
        public void describeTo(final Description description) {
            description.appendText(errorDesc).appendValue(expected);
        }

        @Override
        protected void describeMismatchSafely(final File item, final Description mismatchDescription) {
            mismatchDescription.appendText("  was: ").appendValue(got);
        }
    };
}

From source file:com.ibm.iot.auto.bluemix.samples.ui.InputData.java

public List<CarProbe> getCarProbes() throws IOException, JSONException {
    List<CarProbe> carProbes = new ArrayList<CarProbe>();

    FileReader fileReader = null;
    try {/*w w w .j a  v  a 2s .co m*/
        fileReader = new FileReader(inputFile);
        JSONTokener jsonTokener = new JSONTokener(fileReader);
        JSONArray cars = new JSONArray(jsonTokener);
        for (int i = 0; i < cars.length(); i++) {
            JSONObject car = cars.getJSONObject(i);
            CarProbe carProbe = new CarProbe(car.getString("trip_id"), car.getString("timestamp"),
                    car.getDouble("heading"), car.getDouble("speed"), car.getDouble("longitude"),
                    car.getDouble("latitude"));
            carProbes.add(carProbe);
        }
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
    }
    Collections.sort(carProbes);

    return carProbes;
}

From source file:org.streamspinner.harmonica.application.CQGraphTerminal.java

private void show_open_hamql_dialog() {
    FileFilter filter = createFilter();

    JFileChooser jf = new JFileChooser("conf/query/");
    jf.setFileFilter(filter);/*  w  ww.  j a v  a2s. c  o  m*/

    jf.setDialogTitle("HamQL (SpinQL) ?J");

    int returnVal = jf.showOpenDialog(this);
    if (returnVal != JFileChooser.APPROVE_OPTION)
        return;

    File f = jf.getSelectedFile();

    try {
        FileReader reader = new FileReader(f);
        BufferedReader br = new BufferedReader(reader);

        StringBuilder buf = new StringBuilder();
        String tmp = null;
        while ((tmp = br.readLine()) != null) {
            buf.append(tmp + "\n");
        }
        br.close();
        reader.close();

        getJTextArea().setText(buf.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.eclipse.php.internal.ui.preferences.NewPHPManualSiteDialog.java

private String detectCHMLanguageSuffix(String chmFile) {
    StringBuilder suffix = new StringBuilder("::/"); //$NON-NLS-1$
    char[] buf = new char[8192];
    try {/*w ww.  j a v  a2  s  .  c o m*/
        FileReader r = new FileReader(chmFile);
        try {
            while (r.ready()) {
                r.read(buf);

                Matcher m = LANG_DETECT_PATTERN.matcher(new String(buf));
                if (m.find()) {
                    suffix.append(m.group(1));
                    break;
                }
            }
        } finally {
            r.close();
        }
    } catch (Exception e) {
    }
    return suffix.toString();
}

From source file:madkitgroupextension.export.Export.java

public Export(boolean _export_source, boolean _include_madkit, boolean _export_only_jar_file)
        throws IllegalAccessException, NumberFormatException, IOException {
    m_export_source = _export_source;//from  w ww  .j  av a2  s. c  o m
    m_include_madkit = _include_madkit;
    m_export_only_jar_file = _export_only_jar_file;

    File current_directory = new File(MadKitPath);
    if (!current_directory.exists())
        throw new IllegalAccessException("The Madkit path is invalid: " + MadKitPath);
    Pattern pattern = Pattern.compile("^madkit-.*\\.jar$");
    for (File f : current_directory.listFiles()) {

        if (f.isFile() && pattern.matcher(f.getName()).matches()) {
            m_madkit_jar_file = f;
            m_madkit_version = f.getName().substring(7, f.getName().lastIndexOf("."));
            break;
        }
    }
    if (m_madkit_jar_file == null)
        throw new IllegalAccessException("Impossible to found the MadKit jar file !");

    File f = new File("build.txt");
    if (f.exists()) {
        FileReader fr = new FileReader(f);
        BufferedReader bf = new BufferedReader(fr);
        MadKitGroupExtension.VERSION.setBuildNumber(Integer.parseInt(bf.readLine()));
        bf.close();
        fr.close();
    }
}