Example usage for java.io FileWriter write

List of usage examples for java.io FileWriter write

Introduction

In this page you can find the example usage for java.io FileWriter write.

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:TestSecurity.java

/**
 * put your documentation comment here//from   w ww .  j ava 2s  . co m
 * @param req
 * @param res
 * @exception ServletException, IOException
 */
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println("<HTML>");
    out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
    out.println("<BODY>");
    out.println("<BIG>Test Security</BIG>");
    try {
        out.println(h2o + "Information..." + h2c);
        out.println("  Security Manager: " + getSecurityManager().getClass().getName() + p);
        out.println("  ClassLoader: " + this.getClass().getClassLoader() + p);
        //            weblogic.utils.classloaders.GenericClassLoader gcl = (weblogic.utils.classloaders.GenericClassLoader)this.getClass().getClassLoader();
        //            gcl.setDebug( true );
        out.println("  CodeSource: " + this.getClass().getProtectionDomain().getCodeSource().getLocation() + p);
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    /*
     try
     {
     out.println( h2o + "Trying some dangerous J2EE calls..." + h2c );
     String hack = request.getParameter( "hack" );
     Cookie[] cookies = request.getCookies();
     out.println( " -- allowed -- " + p );
     int x = 1 + 2 + 3;
     out.println( hack );  // use it
     int y = 1 + 2 + 3;
     out.println( cookies );  // use it
     String m = "COOKIE: " + cookies[0]; // use it again
     cookies = new Cookie[10]; // reset it
     String n = "COOKIE: " + cookies[5]; // use it again
     }
     catch( Exception e ) { out.println( " -- rejected -- " + e.getMessage() + p ); }
     */
    try {
        out.println(h2o + "Attempting file write to d:/Java..." + h2c);
        File f = new File("d:/Java/blah.txt");
        FileWriter fw = new FileWriter(f);
        fw.write("test\n");
        fw.close();
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting file write to d:/Java/TestServlet..." + h2c);
        File f = new File("d:/Java/TestServlet/blah.txt");
        FileWriter fw = new FileWriter(f);
        fw.write("test\n");
        fw.close();
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting file read to c:/Ntdetect..." + h2c);
        File f = new File("c:/Ntdetect.com");
        FileReader fr = new FileReader(f);
        int c = fr.read();
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting file read to c:/weblogic/weblogic.properties..." + h2c);
        File f = new File("c:/weblogic/weblogic.properties");
        FileReader fr = new FileReader(f);
        int c = fr.read();
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting to connect to yahoo.com..." + h2c);
        Socket s = new Socket("yahoo.com", 8080);
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting to connect to hacker.com..." + h2c);
        Socket s = new Socket("hacker.com", 8080);
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting to listen on port 37337..." + h2c);
        ServerSocket s = new ServerSocket(37337);
        Socket c = s.accept();
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting to listen on port 7001..." + h2c);
        ServerSocket s = new ServerSocket(7001);
        Socket c = s.accept();
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    /*
     try
     {
     out.println( h2o + "Attempting native call..." + h2c );
     native0( 1 );
     out.println( " -- allowed -- " + p );
     }           
     catch( Exception e ) { out.println( " -- rejected -- " + e.getMessage() + p ); }
     */
    try {
        out.println(h2o + "Attempting exec..." + h2c);
        Runtime.getRuntime().exec("dir");
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting system exit..." + h2c);
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    out.println("</BODY></HTML>");
}

From source file:Validate.java

void validate(String[] args)
        throws FileNotFoundException, IOException, ParserConfigurationException, SAXException {
    File dir = new File(args[0]);

    // User may include a 2nd argument for the log file. 
    useLogFile = (args.length == 2);/*  w  w w.jav a  2s.  c  o m*/

    if (dir.isFile()) // Just checking one file.
    {
        parse(null, args[0]);
    } else if (dir.isDirectory()) // Checking the contents of a directory.
    {
        // Only interested in .xml files.
        XMLFileFilter filter = new XMLFileFilter();
        String[] files = dir.list(filter);
        for (int i = 0; i < files.length; i++) {
            parse(dir.toString(), files[i]); // All the work is done here.

            if (!useLogFile)
            // Write messages to screen after parsing each file.
            {
                System.out.print(buff.toString());
                buff = new StringBuffer();
            }
        }
    } else // Command-line argument is no good!
    {
        System.out.println(args[0] + " not found!");
        return;
    }
    // Provide user with a summary.
    buff.append("================SUMMARY=============================\n");
    if (numXMLFiles > 1)
        buff.append("Parsed " + numXMLFiles + " .xml files in " + args[0] + ".\n");
    if (numValidFiles > 1)
        buff.append(numValidFiles + " files are valid.\n");
    else if (numValidFiles == 1)
        buff.append(numValidFiles + " file is valid.\n");
    if (numInvalidFiles > 1)
        buff.append(numInvalidFiles + " files are not valid.\n");
    else if (numInvalidFiles == 1)
        buff.append(numInvalidFiles + " file is not valid.\n");
    if (numMalformedFiles > 1)
        buff.append(numMalformedFiles + " files are not well-formed.\n");
    else if (numMalformedFiles == 1)
        buff.append(numMalformedFiles + " file is not well-formed.\n");
    if (numFilesMissingDoctype > 1)
        buff.append(numFilesMissingDoctype + " files do not contain a DOCTYPE declaration.\n");
    else if (numFilesMissingDoctype == 1)
        buff.append(numFilesMissingDoctype + " file does not contain a DOCTYPE declaration.\n");

    if (!useLogFile)
        System.out.print(buff.toString());
    else {
        // If log file exists, append.
        FileWriter writer = new FileWriter(args[1], true);
        writer.write(new java.util.Date().toString() + "\n");
        writer.write(buff.toString());
        writer.close();
        System.out.println("Done with validation. See " + args[1] + ".");
    }
}

From source file:edu.duke.cabig.c3pr.ant.UseCaseTraceabilityReport.java

private File buildClasspathFile() throws IOException, BuildException {
    File cpFile = File.createTempFile("uctrace-classpath-", "");
    FileWriter fw = new FileWriter(cpFile);
    logger.debug("Writing classpath to " + cpFile);
    fw.write("-cp\n");
    fw.write(Utils.join(buildClasspath().iterator(), File.pathSeparator));
    fw.close();/* w ww .j a va  2s  .c  om*/
    logger.debug("Finished writing test cases list");
    return cpFile;
}

From source file:edu.missouri.bas.bluetooth.equivital.EquivitalRunnable.java

protected void writeToFile(File f, String toWrite) throws IOException {
    FileWriter fw = new FileWriter(f, true);
    fw.write(toWrite + '\n');
    fw.flush();//w  w w.  j a  va 2  s.  c  o  m
    fw.close();
}

From source file:de.pdark.dsmp.ProxyDownload.java

/**
 * Do the download./*w w w . ja  va 2  s .c o m*/
 * 
 * @throws IOException
 * @throws DownloadFailed
 */
public void download() throws IOException, DownloadFailed {
    if (!config.isAllowed(url)) {
        throw new DownloadFailed(
                "HTTP/1.1 " + HttpStatus.SC_FORBIDDEN + " Download denied by rule in DSMP config");
    }

    // If there is a status file in the cache, return it instead of trying it again
    // As usual with caches, this one is a key area which will always cause
    // trouble.
    // TODO There should be a simple way to get rid of the cached statuses
    // TODO Maybe retry a download after a certain time?
    File statusFile = new File(dest.getAbsolutePath() + ".status");
    if (statusFile.exists()) {
        try {
            FileReader r = new FileReader(statusFile);
            char[] buffer = new char[(int) statusFile.length()];
            int len = r.read(buffer);
            r.close();
            String status = new String(buffer, 0, len);
            throw new DownloadFailed(status);
        } catch (IOException e) {
            log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e);
        }
    }

    mkdirs();

    HttpClient client = new HttpClient();

    String msg = "";
    if (config.useProxy(url)) {
        Credentials defaultcreds = new UsernamePasswordCredentials(config.getProxyUsername(),
                config.getProxyPassword());
        AuthScope scope = new AuthScope(config.getProxyHost(), config.getProxyPort(), AuthScope.ANY_REALM);
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(config.getProxyHost(), config.getProxyPort());
        client.setHostConfiguration(hc);
        client.getState().setProxyCredentials(scope, defaultcreds);
        msg = "via proxy ";
    }
    log.info("Downloading " + msg + "to " + dest.getAbsolutePath());

    GetMethod get = new GetMethod(url.toString());
    get.setFollowRedirects(true);
    try {
        int status = client.executeMethod(get);

        log.info("Download status: " + status);
        if (0 == 1 && log.isDebugEnabled()) {
            Header[] header = get.getResponseHeaders();
            for (Header aHeader : header)
                log.debug(aHeader.toString().trim());
        }

        log.info("Content: " + valueOf(get.getResponseHeader("Content-Length")) + " bytes; "
                + valueOf(get.getResponseHeader("Content-Type")));

        if (status != HttpStatus.SC_OK) {
            // Remember "File not found"
            if (status == HttpStatus.SC_NOT_FOUND) {
                try {
                    FileWriter w = new FileWriter(statusFile);
                    w.write(get.getStatusLine().toString());
                    w.close();
                } catch (IOException e) {
                    log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e);
                }
            }
            throw new DownloadFailed(get);
        }

        File dl = new File(dest.getAbsolutePath() + ".new");
        OutputStream out = new BufferedOutputStream(new FileOutputStream(dl));
        IOUtils.copy(get.getResponseBodyAsStream(), out);
        out.close();

        File bak = new File(dest.getAbsolutePath() + ".bak");
        if (bak.exists())
            bak.delete();
        if (dest.exists())
            dest.renameTo(bak);
        dl.renameTo(dest);
    } finally {
        get.releaseConnection();
    }
}

From source file:edu.asu.bscs.csiebler.waypointdatabase.MainActivity.java

/**
 * @param v//from w  w w  .  ja v  a  2 s . c  om
 */
public void exportWaypoints(View v) {
    File sdCard = Environment.getExternalStorageDirectory();

    FileWriter fw = null;

    try {
        fw = new FileWriter(sdCard.getAbsolutePath() + "/waypoints.json");
        fw.write(getJsonResults().toString());
    } catch (IOException e) {
        Log.w(getClass().getSimpleName(), e.getMessage());
    } finally {
        try {
            if (fw != null) {
                fw.flush();
                fw.close();
            }
        } catch (IOException e) {
            Log.w(getClass().getSimpleName(), e.getMessage());
        }
    }
}

From source file:com.amalto.workbench.editors.XSDDriver.java

public File outputXSD(String src, String fileName) {
    File file = new File(fileName);
    try {//w w  w .  ja v  a2s.co m
        FileWriter writer = new FileWriter(file);
        writer.write(src);
        // System.out.println("OutputStreamWriter: "+writer.getEncoding());
        writer.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        log.error(e.getMessage(), e);
        return null;
    }

    return file;
}

From source file:com.axelor.apps.admin.service.AsciiDocExportService.java

public File export(File excelFile, File asciiDoc, String lang) {

    if (excelFile == null) {
        return null;
    }/*from www .j ava 2  s. com*/

    if (lang != null && lang.equals("fr")) {
        docIndex = 11;
        titleIndex = 6;
        menuIndex = 10;
    }

    try {
        FileInputStream inStream = new FileInputStream(excelFile);

        XSSFWorkbook workbook = new XSSFWorkbook(inStream);

        if (asciiDoc == null) {
            asciiDoc = File.createTempFile(excelFile.getName().replace(".xlsx", ""), ".txt");
        }

        FileWriter fw = new FileWriter(asciiDoc);

        fw.write("= Documentation\n:toc:");

        processSheet(workbook.iterator(), fw);

        fw.close();

        return asciiDoc;

    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:de.xirp.ui.util.HelpManager.java

/**
 * Writes the navigation HTML-file. The links for existing plugins
 * are added to the existing links of the standard program help.
 *//*from ww w. j ava  2  s  .  c om*/
private void createNavigationHTML() {
    StringBuilder naviPage = new StringBuilder();
    naviPage.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">") //$NON-NLS-1$
            .append(Constants.LINE_SEPARATOR);
    naviPage.append("<HTML>").append(Constants.LINE_SEPARATOR); //$NON-NLS-1$
    naviPage.append("<HEAD>").append(Constants.LINE_SEPARATOR); //$NON-NLS-1$
    naviPage.append("   <META HTTP-EQUIV=\"CONTENT-TYPE\" CONTENT=\"text/html; charset=windows-1252\">") //$NON-NLS-1$
            .append(Constants.LINE_SEPARATOR);
    naviPage.append("   <TITLE>nav frame</TITLE>").append(Constants.LINE_SEPARATOR); //$NON-NLS-1$
    naviPage.append("</HEAD>").append(Constants.LINE_SEPARATOR); //$NON-NLS-1$
    naviPage.append("<BODY>").append(Constants.LINE_SEPARATOR); //$NON-NLS-1$
    // naviPage.append("<UL>"+Constants.LINE_SEPARATOR);

    createXirpLinks(naviPage);
    createPluginLinks(naviPage);

    // naviPage.append("</UL>"+Constants.LINE_SEPARATOR);
    naviPage.append("</BODY>").append(Constants.LINE_SEPARATOR); //$NON-NLS-1$
    naviPage.append("</HTML>").append(Constants.LINE_SEPARATOR); //$NON-NLS-1$

    File f = new File(Constants.HELP_DIR + File.separator + "nav_frame.html"); //$NON-NLS-1$
    try {
        FileWriter fw = new FileWriter(f);
        fw.write(naviPage.toString());
        fw.close();

    } catch (FileNotFoundException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
    }
}

From source file:it.eng.spagobi.engines.talend.client.SpagoBITalendEngineClient_0_5_0.java

public boolean deployJob(JobDeploymentDescriptor jobDeploymentDescriptor, File executableJobFiles)
        throws EngineUnavailableException, AuthenticationFailedException, ServiceInvocationFailedException {

    HttpClient client;//from  w w w  .j av a  2 s.c o  m
    PostMethod method;
    File deploymentDescriptorFile;
    boolean result = false;

    client = new HttpClient();
    method = new PostMethod(getServiceUrl(JOB_UPLOAD_SERVICE));
    deploymentDescriptorFile = null;

    try {
        deploymentDescriptorFile = File.createTempFile("deploymentDescriptor", ".xml"); //$NON-NLS-1$ //$NON-NLS-2$
        FileWriter writer = new FileWriter(deploymentDescriptorFile);
        writer.write(jobDeploymentDescriptor.toXml());
        writer.flush();
        writer.close();

        Part[] parts = { new FilePart(executableJobFiles.getName(), executableJobFiles),
                new FilePart("deploymentDescriptor", deploymentDescriptorFile) }; //$NON-NLS-1$

        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        int status = client.executeMethod(method);
        if (status == HttpStatus.SC_OK) {
            if (method.getResponseBodyAsString().equalsIgnoreCase("OK")) //$NON-NLS-1$
                result = true;
        } else {
            throw new ServiceInvocationFailedException(
                    Messages.getString("SpagoBITalendEngineClient_0_5_0.serviceExcFailed") + JOB_UPLOAD_SERVICE, //$NON-NLS-1$
                    method.getStatusLine().toString(),
                    method.getResponseBodyAsString());
        }
    } catch (HttpException e) {
        throw new EngineUnavailableException(
                Messages.getString("SpagoBITalendEngineClient_0_5_0.protocolViolation") + e.getMessage()); //$NON-NLS-1$
    } catch (IOException e) {
        throw new EngineUnavailableException(
                Messages.getString("SpagoBITalendEngineClient_0_5_0.transportError") + e.getMessage()); //$NON-NLS-1$
    } finally {
        method.releaseConnection();
        if (deploymentDescriptorFile != null)
            deploymentDescriptorFile.delete();
    }

    return result;
}