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:fr.irit.sparql.Proxy.SparqlProxy.java

public File writeKBFile(String dirPath, String fileName)
        throws SparqlQueryMalFormedException, SparqlEndpointUnreachableException {
    File ret = null;//from w w  w . jav  a 2 s. com
    HttpURLConnection connection = null;
    try {
        URL url = new URL(this.urlServer + "data?default");
        // Create connection
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        FileWriter f = new FileWriter(dirPath + fileName + ".owl");

        while ((line = reader.readLine()) != null) {
            f.write(line + "\n");
        }

        ret = new File("out/" + fileName + ".owl");
        reader.close();
        f.close();
    } catch (UnsupportedEncodingException ex) {
        throw new SparqlQueryMalFormedException("Encoding unsupported");
    } catch (MalformedURLException ex) {
        throw new SparqlQueryMalFormedException("Query malformed");
    } catch (IOException ex) {
        throw new SparqlEndpointUnreachableException(ex);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return ret;
}

From source file:io.spotnext.maven.mojo.TransformTypesMojo.java

@SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "false positive")
protected void logError(Throwable cause) {
    final String tempFolder = System.getProperty("java.io.tmpdir");
    final Path logFilePath = Paths.get(tempFolder, "spot-transform.types.log");
    final File logFile = logFilePath.toFile();

    if (logFile.canWrite()) {
        FileWriter writer = null;
        try {/*  ww  w. j a  v a2 s  .c  om*/
            writer = new FileWriter(logFile);
            writer.write(cause.getMessage());
            writer.write(ExceptionUtils.getStackTrace(cause));
        } catch (Exception e) {
            getLog().error("Can't log to separete error log file " + logFilePath.toString());
        } finally {
            CloseUtil.closeQuietly(writer);
        }
    }
}

From source file:de.codesourcery.eve.apiclient.cache.FilesystemResponseCacheTest.java

public void testGetDeletesCorruptCachefiles() throws Exception {

    final Properties properties = new Properties();
    properties.setProperty(FilesystemResponseCache.OPTION_WRITE_IMMEDIATELY, "true");

    cache.setCacheOptions(properties);//from  w w  w . ja v  a 2 s .c  o  m
    final APIQuery query = createQuery("/server/test.xml");
    InternalAPIResponse response = createMockResponse(1024);

    assertCacheDirNotContains(query);

    cache.put(query, response);

    assertCacheDirContains(query);

    final File file = cache.getFilenameForEntry(query);
    assertTrue(file.delete());

    final FileWriter writer = new FileWriter(file, false);
    writer.write("blubb");
    writer.close();

    FilesystemResponseCache cache2 = new FilesystemResponseCache(tmpDir, systemClock);

    InternalAPIResponse cached2 = cache2.get(query);
    assertNull(cached2);
    assertFalse(file.exists());
}

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

private File buildTestCasesListFile() throws IOException {
    File listFile = File.createTempFile("uctrace-tclist-", "");
    FileWriter fw = new FileWriter(listFile);
    logger.debug("Writing test cases list to " + listFile);

    logger.debug("Looking for tests in " + srcDir);
    for (File f : findJava(srcDir, new LinkedList<File>())) {
        fw.write(f.getAbsolutePath());
        fw.write("\n");
    }//w  w  w  .  ja va2s .  c om

    fw.close();
    logger.debug("Finished writing test cases list");
    return listFile;
}

From source file:de.codesourcery.eve.apiclient.cache.FilesystemResponseCacheTest.java

public void testPutOverwritesCorruptCachefiles() throws Exception {

    final Properties properties = new Properties();
    properties.setProperty(FilesystemResponseCache.OPTION_WRITE_IMMEDIATELY, "true");

    cache.setCacheOptions(properties);//from   ww  w  . j a  v  a 2s  . com
    final APIQuery query = createQuery("/server/test.xml");
    InternalAPIResponse response = createMockResponse(1024);

    assertCacheDirNotContains(query);

    cache.put(query, response);

    assertCacheDirContains(query);

    final File file = cache.getFilenameForEntry(query);
    assertTrue(file.delete());

    final FileWriter writer = new FileWriter(file, false);
    writer.write("blubb");
    writer.close();

    cache.put(query, response);

    FilesystemResponseCache cache2 = new FilesystemResponseCache(tmpDir, systemClock);

    InternalAPIResponse cached2 = cache2.get(query);
    assertNotNull(cached2);
    assertEquals(response.getPayload(), cached2.getPayload());
}

From source file:Enrichissement.GraphViz.java

/**
 * Writes the source of the graph in a file, and returns the written file
 * as a File object./*from   w  w w  . j a  v  a 2  s.  co m*/
 * @param str Source of the graph (in dot language).
 * @return The file (as a File object) that contains the source of the graph.
 */
private File writeDotSourceToFile(String str) throws java.io.IOException {
    File temp;
    try {
        File directory = new File(GraphViz.TEMP_DIR);
        temp = File.createTempFile("graph_", ".dot.tmp", directory);
        FileWriter fout = new FileWriter(temp);
        fout.write(str);
        fout.close();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Error: I/O error while writing the dot source to temp file!");
        return null;
    }
    return temp;
}

From source file:com.heliumv.api.cc.ClevercureApi.java

private void persistDatatype(String datatype, String ccdata, String fileSuffix) {
    try {/*from   w w w  .j  a  v  a2  s .c  o m*/
        File f = File.createTempFile("CC" + datatype + "_", fileSuffix != null ? ("_" + fileSuffix) : "_.xml");
        FileWriter fw = new FileWriter(f);
        fw.write(ccdata);
        fw.close();
        System.out.println("Stored osd data to file '" + f.getName() + "'.");
    } catch (IOException e) {
        System.out.println("Can't write to file " + e.getMessage());
    }
}

From source file:com.adaptris.core.services.ScriptingServiceTest.java

private File writeScript(boolean working) throws IOException {
    FileWriter fw = null;
    File result = null;/*  w ww.j  a  v a2  s. co  m*/
    try {
        File dir = new File(PROPERTIES.getProperty(KEY_SCRIPTING_BASEDIR, "./build/scripting"));
        dir.mkdirs();
        result = File.createTempFile("junit", ".script", dir);
        fw = new FileWriter(result);
        fw.write(working ? SCRIPT : "This will fail");
    } finally {
        IOUtils.closeQuietly(fw);
    }
    return result;
}

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

/**
 * Authenticate User for login./*from  w w  w.j  av  a 2s.c  o m*/
 *
 * @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:luceneGazateer.EntryData.java

public static void produceCandidates(String indexPath, String fileName, GeoNameResolver resolver)
        throws IOException {
    BufferedReader filereader = new BufferedReader(
            new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
    FileWriter ps = new FileWriter("output.txt", true);
    String line = "";
    String testString = "";
    String uri = "";
    while ((line = filereader.readLine()) != null) {
        String[] locArgs = line.split("\t");
        try {//w w w.j a va2s.  c o m
            uri = locArgs[0];
            testString = locArgs[1];
            System.out.println(testString);
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
            System.exit(-1);
        }

        ArrayList<EntryData> resolved = resolver.searchDocuments(indexPath, testString, globalDocType);

        resolved.sort(new Comparator<EntryData>() {
            @Override
            public int compare(EntryData e1, EntryData e2) {
                Double diff = e1.getScore() - e2.getScore();
                if (diff < 1e-6 && diff > -1e-6)
                    return 0;
                else if (diff > 0)
                    return -1;
                return 1;
            }
        });
        ps.write("{\"query_string\":{\"uri\":\"" + uri + "\",\"name\":\"" + testString + "\", \"candidates\":");
        ps.write("[");
        for (int i = 0; i < resolved.size(); i++) {
            //for(Map.Entry<String, Double> entry : candidatesEntryList){
            ps.write("{\"uri\":\"" + resolved.get(i).getId() + "\",");
            ps.write("\"name\":\"" + resolved.get(i).getName() + "\",");
            ps.write("\"score\":\"" + resolved.get(i).getScore() + "\"");

            if (i < resolved.size() - 1) {
                ps.write("},");
            } else {
                ps.write("}");
            }
            //System.out.println("\t" + entry.getValue() + "\t" + entry.getKey());
        }
        ps.write("]}}\n");
        ps.flush();

    }
}