Example usage for java.io File toString

List of usage examples for java.io File toString

Introduction

In this page you can find the example usage for java.io File toString.

Prototype

public String toString() 

Source Link

Document

Returns the pathname string of this abstract pathname.

Usage

From source file:org.openmrs.contrib.metadatarepository.service.impl.PackageManagerImpl.java

protected void saveFile(final String filename, byte[] file) throws IOException {

    // Create the directory if it doesn't exist
    File dirPath = new File(packagesStorageDir);

    if (!dirPath.exists()) {
        dirPath.mkdir();// ww w.j  ava  2s  .  c om
    }

    if (log.isDebugEnabled())
        log.debug("Saving file to " + dirPath.toString());

    // write the file to the file specified
    File packagedata = new File(dirPath, filename);
    FileOutputStream bos = null;
    try {
        bos = new FileOutputStream(packagedata);
        bos.write(file);
        bos.close();
    } catch (IOException e) {
        throw new APIException("error writing a file", e);
    } finally {
        try {
            if (bos != null) {
                bos.close();
            }
        } catch (IOException e) {
            // close quietly
            log.error(e);
        }
    }

}

From source file:com.scaleoutsoftware.soss.hserver.hadoop.DistributedCacheManager.java

/**
 * Utility method for creating a symlink and warning on errors.
 *
 * If link is null, does nothing.//from  w w w .  j av a2  s  .  c o  m
 */
private void symlink(File workDir, String target, String link) throws IOException {
    if (link != null) {
        link = workDir.toString() + Path.SEPARATOR + link;
        File flink = new File(link);

        //CODE CHANGE FROM ORIGINAL FILE, BUG FIX:
        //
        //If the cleanup of the previous job failed for some reason, we can have lingering symlink,
        //pointing to the obsolete file (in that case flink.exists() == true) or to non-existant
        //file(flink.exists() == false). In the second case, the original code tried to create symlink
        //anyway causing "already exists" error. In the first case, this method used to do nothing
        //without logging it, which effectively left the old symlink in place, leading to
        //elusive bugs.
        //
        //Changes:
        //1.Try delete symlink, and log if there was a symlink to delete (it means something wrong with cleanup)
        //2. Remove the if(!flink.exist()) check before creating symlink.
        if (flink.delete()) {
            LOG.warn(String.format("Symlink already existed, deleting: %s <- %s", target, link));
        }

        LOG.info(String.format("Creating symlink: %s <- %s", target, link));
        if (0 != FileUtil.symLink(target, link)) {
            LOG.warn(String.format("Failed to create symlink: %s <- %s", target, link));
        } else {
            symlinksCreated.add(new File(link));
        }

    }
}

From source file:ninja.eivind.hotsreplayuploader.files.tempwatcher.RecursiveTempWatcherTest.java

@Test
public void testGetChildCount() throws Exception {
    final File remainder = directories.getRemainder();
    if (!remainder.mkdirs()) {
        fail("Failed to create files.");
    }// w  w  w .  ja v a 2s .c  o m

    final String rootString = directories.getRoot().toString();
    final String remainderString = remainder.toString();
    final String difference = remainderString.replace(rootString, "").substring(1);

    final String remainderRegex = tempWatcher.getRemainderRegex();

    logger.info("Remainder string: {}", remainderString);
    logger.info("Root string: {}", rootString);
    logger.info("Difference string: {}", difference);
    logger.info("Splitting using regex string: {}", remainderRegex);
    final int expected = difference.split(remainderRegex).length;
    final int actual = tempWatcher.getChildCount();

    assertSame(String.format("Expecting %d children for tempwatcher", expected), expected, actual);
}

From source file:fr.inria.ucn.collectors.LlamaCollector.java

@Override
public void run(Context c, long ts) {
    try {//from   w ww.j ava 2  s .c  o  m
        String state = Environment.getExternalStorageState();
        File llamaAreas = new File(Environment.getExternalStorageDirectory() + "/Llama/Llama_Areas.txt");

        if (Environment.MEDIA_MOUNTED.equals(state) && llamaAreas.exists()) {
            JSONObject data = new JSONObject();
            data.put("source_file", llamaAreas.toString());

            BufferedReader in = null;
            try {
                in = new BufferedReader(new FileReader(llamaAreas), 1024);
                String line;
                JSONObject a = new JSONObject();
                while ((line = in.readLine()) != null) {
                    String[] tmp = line.trim().split("\\|");
                    JSONArray wifi = new JSONArray();
                    JSONArray cell = new JSONArray();
                    for (int i = 1; i < tmp.length; i++) {
                        String[] tmp2 = tmp[i].split("\\:");
                        if (tmp2[0].trim().equalsIgnoreCase("W")) {
                            wifi.put(tmp2[1].trim());
                        } else {
                            // FIXME: figure out what these values are ?!?
                            JSONObject cid = new JSONObject();
                            cid.put("1", Integer.parseInt(tmp2[0].trim()));
                            cid.put("2", Integer.parseInt(tmp2[1].trim()));
                            cid.put("3", Integer.parseInt(tmp2[2].trim()));
                            cell.put(cid);
                        }
                    }
                    JSONObject o = new JSONObject();
                    o.put("wifi_networks", wifi); // wifi networks associated to this area
                    o.put("cells", cell); // cell ids associated to this area
                    a.put(tmp[0].trim(), o);
                }
                data.put("locations", a);

                // done
                Helpers.sendResultObj(c, "llama_location", ts, data);

            } catch (FileNotFoundException e) {
                Log.w(Constants.LOGTAG, "Llama exports not available", e);
            } catch (IOException e) {
                Log.w(Constants.LOGTAG, "Llama exports not available", e);
            }

            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                }
        } else {
            Log.w(Constants.LOGTAG, "Llama exports not available, file=" + llamaAreas.toString() + ", exists="
                    + llamaAreas.exists());
        }

    } catch (JSONException jex) {
        Log.w(Constants.LOGTAG, "failed to create json object", jex);
    }
}

From source file:be.samey.io.ServerConn.java

public void connect() throws InterruptedException, IOException {

    /*----------------------------------------------------------------------
     1) create output directory/*from  w  ww  . ja  v  a 2  s .co m*/
     */
    //if the user clicked the checkbox to save the output, then the archive
    //downloaded from the server is saved in the directory specified by the
    //user. If the user does not want to save the output, then the archive
    //is downloaded to a temp folder.
    Path outPath;
    if (cyModel.getSaveFilePath() == null) {
        outPath = Files.createTempDirectory("Cev_archive");
    } else {
        outPath = cyModel.getSaveFilePath();
    }

    String fileExtension = ".tgz";
    String archiveName = cyModel.getTitle();

    Path archivePath = outPath.resolve(archiveName + fileExtension);
    //prevent overwriting the same file if the user forgot to change the
    //title
    if (Files.exists(archivePath)) {
        archivePath = outPath.resolve(archiveName + "_" + CyAppManager.getTimeStamp() + fileExtension);
    }

    /*----------------------------------------------------------------------
     2) Upload user files and settings, download response
     */
    //make multipart entity with user data and settings
    HttpEntity postEntity = makeEntity(cyModel.getBaits(), cyModel.getSpeciesNames(), cyModel.getSpeciesPaths(),
            cyModel.getPCutoff(), cyModel.getNCutoff(), cyModel.getOrthGroupNames(),
            cyModel.getOrthGroupPaths());

    //run the app on the server
    executeAppOnSever(CyModel.URL, postEntity, archivePath);

    /*----------------------------------------------------------------------
     4) Unpack files to temp dir
     */
    //create a temp folder to store the network files
    Path unpackPath = Files.createTempDirectory("Cev_netw");
    //unpack the network files
    Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.GZIP);
    File archive = archivePath.toFile();
    ArchiveStream stream = archiver.stream(archive);
    ArchiveEntry entry;

    Path sifPath = null;
    Path noaPath = null;
    Path edaPath = null;
    Path logPath = null;
    File netwFile;
    while ((entry = stream.getNextEntry()) != null) {
        netwFile = entry.extract(unpackPath.toFile());
        if (netwFile.toString().endsWith(".sif")) {
            sifPath = netwFile.toPath();
        }
        if (netwFile.toString().endsWith(".node.attr")) {
            noaPath = netwFile.toPath();
        }
        if (netwFile.toString().endsWith(".edge.attr")) {
            edaPath = netwFile.toPath();
        }
        if (netwFile.toString().endsWith("_log")) {
            logPath = netwFile.toPath();
        }
    }
    stream.close();

    /*----------------------------------------------------------------------
     5) update corestatus with network paths
     */
    //TODO: sanity checks
    cyModel.setSifPath(sifPath);
    cyModel.setNoaPath(noaPath);
    cyModel.setEdaPath(edaPath);
    cyModel.setLogPath(logPath);

}

From source file:apim.restful.importexport.APIService.java

/**
 * This service exports an API from API Manager for a given API ID
 * Meta information, API icon, documentation, WSDL and sequences are exported
 * This service generates a zipped archive which contains all the above mentioned resources
 * for a given API//w w w  . j a  va  2s .c  om
 *
 * @param name         Name of the API that needs to be exported
 * @param version      Version of the API that needs to be exported
 * @param providerName Provider name of the API that needs to be exported
 * @return Zipped API as the response to the service call
 */
@GET
@Path("/export-api")
@Produces("application/zip")
public Response exportAPI(@QueryParam("name") String name, @QueryParam("version") String version,
        @QueryParam("provider") String providerName, @Context HttpHeaders httpHeaders) {

    String userName;
    if (name == null || version == null || providerName == null) {
        log.error("Invalid API Information ");

        return Response.status(Response.Status.BAD_REQUEST).entity("Invalid API Information")
                .type(MediaType.APPLICATION_JSON).build();
    }
    log.info("Retrieving API for API-Id : " + name + "-" + version + "-" + providerName);
    APIIdentifier apiIdentifier;
    try {

        Response authorizationResponse = AuthenticatorUtil.authorizeUser(httpHeaders);
        if (!(Response.Status.OK.getStatusCode() == authorizationResponse.getStatus())) {
            return authorizationResponse;
        }

        userName = AuthenticatorUtil.getAuthenticatedUserName();
        //provider names with @ signs are only accepted
        String apiDomain = MultitenantUtils.getTenantDomain(providerName);
        String apiRequesterDomain = MultitenantUtils.getTenantDomain(userName);
        //Allows to export APIs created only in current tenant domain
        if (!apiDomain.equals(apiRequesterDomain)) {
            //not authorized to export requested API
            log.error("Not authorized to " + "export API :" + name + "-" + version + "-" + providerName);
            return Response.status(Response.Status.FORBIDDEN)
                    .entity("Not authorized to export API :" + name + "-" + version + "-" + providerName)
                    .type(MediaType.APPLICATION_JSON).build();
        }

        apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(providerName), name, version);

        //create temp location for storing API data to generate archive
        String currentDirectory = System.getProperty(APIImportExportConstants.TEMP_DIR);
        String createdFolders = File.separator
                + RandomStringUtils.randomAlphanumeric(APIImportExportConstants.TEMP_FILENAME_LENGTH)
                + File.separator;
        File exportFolder = new File(currentDirectory + createdFolders);
        APIExportUtil.createDirectory(exportFolder.getPath());
        String archiveBasePath = exportFolder.toString();

        APIExportUtil.setArchiveBasePath(archiveBasePath);

        Response apiResourceRetrievalResponse = APIExportUtil.retrieveApiToExport(apiIdentifier, userName);

        //Retrieve resources : thumbnail, meta information, wsdl, sequences and documents
        // available for the exporting API
        if (!(Response.Status.OK.getStatusCode() == apiResourceRetrievalResponse.getStatus())) {
            return apiResourceRetrievalResponse;
        }

        ArchiveGeneratorUtil.archiveDirectory(archiveBasePath);

        log.info("API" + name + "-" + version + " exported successfully");

        File file = new File(archiveBasePath + ".zip");
        Response.ResponseBuilder response = Response.ok(file);
        response.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
        return response.build();

    } catch (APIExportException e) {
        log.error("APIExportException occurred while exporting ", e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Internal Server Error")
                .type(MediaType.APPLICATION_JSON).build();
    }

}

From source file:no.uio.medicine.virsurveillance.charts.BoxAndWhiskerChart_AWT.java

/**
 * For testing from the command line.//from  www . j a v a 2s. c om
 *
 * @param args ignored.
 */
public void save2File(File outputFile) throws IOException {
    ChartUtilities cu = new ChartUtilities() {
    };
    ChartUtilities.saveChartAsPNG(outputFile, this.chartPanel.getChart(), 1200, 500);
    System.out.println("Saved at " + outputFile.toString() + " size = " + 1200 + "x" + 500);
}

From source file:gov.nasa.jpl.mudrod.ontology.process.LocalOntology.java

/**
 * Load the default <i>ontology</i> directory contained within Mudrod.
 * This contains at a minimum SWEET v2.3.
 *///  www .java  2s. c  o  m
@Override
public void load() {
    File ontDir = new File(LocalOntology.class.getClassLoader().getResource("ontology").getFile());

    //Fail if the input is not a directory.
    if (ontDir.isDirectory()) {
        List<String> owlFiles = new ArrayList<>();
        for (File owlFile : ontDir.listFiles()) {
            owlFiles.add(owlFile.toString());
        }
        //convert to correct iput for ontology loading.
        String[] owlArray = new String[owlFiles.size()];
        owlArray = owlFiles.toArray(owlArray);
        load(owlArray);
    }
}

From source file:de.jcup.egradle.core.VersionedFolderToUserHomeCopySupport.java

@Override
public boolean copyFrom(RootFolderProvider rootFolderProvider) throws IOException {
    File internalFolder = rootFolderProvider.getRootFolder();
    if (internalFolder == null) {
        /* has to be already logged by root folder provider */
        return false;
    }/*from  w w w . ja v  a2  s.  c  om*/
    if (!internalFolder.exists()) {
        throw new FileNotFoundException(
                "Did not find internal folder to copy from:" + internalFolder.toString());
    }
    copySupport.copyDirectories(internalFolder, targetFolder, true);
    return true;
}

From source file:com.cloudera.sqoop.mapreduce.JobBase.java

/**
 * Add the .jar elements of a directory to the DCache classpath,
 * nonrecursively./*ww w . j a  va  2 s  .  co  m*/
 */
private void addDirToCache(File dir, FileSystem fs, Set<String> localUrls) {
    if (null == dir) {
        return;
    }

    for (File libfile : dir.listFiles()) {
        if (libfile.exists() && !libfile.isDirectory() && libfile.getName().endsWith("jar")) {
            addToCache(libfile.toString(), fs, localUrls);
        }
    }
}