Example usage for java.io File setWritable

List of usage examples for java.io File setWritable

Introduction

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

Prototype

public boolean setWritable(boolean writable) 

Source Link

Document

A convenience method to set the owner's write permission for this abstract pathname.

Usage

From source file:edu.isi.wings.ontapi.jena.KBAPIJena.java

@Override
public boolean delete() {
    writeLock.lock();/*  w w  w .  j  a v  a2s .  c  o m*/
    try {
        if (this.url == null)
            return false;

        if (this.usetdb && tdbstore != null) {
            tdbstore.removeNamedModel(this.url);
            TDB.sync(tdbstore);
            return true;
        } else {
            // Delete the file
            String fileuri = LocationMapper.get().altMapping(this.url);
            try {
                File f = new File(new URL(fileuri).getFile());
                f.setWritable(true);
                f.delete();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    } finally {
        writeLock.unlock();
    }
}

From source file:io.realm.RealmTest.java

public void testGetInstanceFileNoWritePermissionThrows() throws IOException {
    String REALM_FILE = "readonly.realm";
    File folder = getContext().getFilesDir();
    File realmFile = new File(folder, REALM_FILE);
    if (realmFile.exists()) {
        realmFile.delete(); // Reset old test data
    }//from w w  w  . j  av a  2s  .  c o  m

    assertTrue(realmFile.createNewFile());
    assertTrue(realmFile.setWritable(false));

    try {
        Realm.getInstance(new RealmConfiguration.Builder(folder).name(REALM_FILE).build());
        fail("Trying to open a read-only file should fail");
    } catch (RealmIOException expected) {
    }
}

From source file:playRepository.GitRepository.java

public boolean move(String srcProjectOwner, String srcProjectName, String desrProjectOwner,
        String destProjectName) {
    repository.close();//from   w w w.  ja va2  s.c om
    WindowCacheConfig config = new WindowCacheConfig();
    config.install();

    File srcGitDirectory = new File(getGitDirectory(srcProjectOwner, srcProjectName));
    File destGitDirectory = new File(getGitDirectory(desrProjectOwner, destProjectName));
    File srcGitDirectoryForMerging = new File(getDirectoryForMerging(srcProjectOwner, srcProjectName));
    File destGitDirectoryForMerging = new File(getDirectoryForMerging(desrProjectOwner, destProjectName));
    srcGitDirectory.setWritable(true);
    srcGitDirectoryForMerging.setWritable(true);

    try {
        if (srcGitDirectory.exists()) {
            org.apache.commons.io.FileUtils.moveDirectory(srcGitDirectory, destGitDirectory);
            play.Logger.debug(
                    "[Transfer] Move from: " + srcGitDirectory.getAbsolutePath() + "to " + destGitDirectory);
        } else {
            play.Logger.warn("[Transfer] Nothing to move from: " + srcGitDirectory.getAbsolutePath());
        }

        if (srcGitDirectoryForMerging.exists()) {
            org.apache.commons.io.FileUtils.moveDirectory(srcGitDirectoryForMerging,
                    destGitDirectoryForMerging);
            play.Logger.debug("[Transfer] Move from: " + srcGitDirectoryForMerging.getAbsolutePath() + "to "
                    + destGitDirectoryForMerging);
        } else {
            play.Logger.warn("[Transfer] Nothing to move from: " + srcGitDirectoryForMerging.getAbsolutePath());
        }
        return true;
    } catch (IOException e) {
        play.Logger.error("[Transfer] Move Failed", e);
        return false;
    }
}

From source file:lc.kra.servlet.FileManagerServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *///from   w w w. j a va2  s  . c  o m
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Files files = null;
    File file = null, parent;
    String path = request.getParameter("path"), type = request.getContentType(),
            search = request.getParameter("search"), mode;

    if (path == null || !(file = new File(path)).exists())
        files = new Roots();
    else if (request.getParameter("zip") != null) {
        File zipFile = File.createTempFile(file.getName() + "-", ".zip");
        if (file.isFile())
            ZipUtil.addEntry(zipFile, file.getName(), file);
        else if (file.isDirectory())
            ZipUtil.pack(file, zipFile);
        downloadFile(response, zipFile, permamentName(zipFile.getName()), "application/zip");
    } else if (request.getParameter("delete") != null) {
        if (file.isFile())
            file.delete();
        else if (file.isDirectory()) {
            java.nio.file.Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    java.nio.file.Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    java.nio.file.Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    } else if ((mode = request.getParameter("mode")) != null) {
        boolean add = mode.startsWith("+");
        if (mode.indexOf('r') > -1)
            file.setReadable(add);
        if (mode.indexOf('w') > -1)
            file.setWritable(add);
        if (mode.indexOf('x') > -1)
            file.setExecutable(add);
    } else if (file.isFile())
        downloadFile(response, file);
    else if (file.isDirectory()) {
        if (search != null && !search.isEmpty())
            files = new Search(file.toPath(), search);
        else if (type != null && type.startsWith("multipart/form-data")) {
            for (Part part : request.getParts()) {
                String name;
                if ((name = partFileName(part)) == null) //retrieves <input type="file" name="...">, no other (e.g. input) form fields
                    continue;
                if (request.getParameter("unzip") == null)
                    try (OutputStream output = new FileOutputStream(new File(file, name))) {
                        copyStream(part.getInputStream(), output);
                    }
                else
                    ZipUtil.unpack(part.getInputStream(), file);
            }
        } else
            files = new Directory(file);
    } else
        throw new ServletException("Unknown type of file or folder.");

    if (files != null) {
        final PrintWriter writer = response.getWriter();
        writer.println(
                "<!DOCTYPE html><html><head><style>*,input[type=\"file\"]::-webkit-file-upload-button{font-family:monospace}</style></head><body>");
        writer.println("<p>Current directory: " + files + "</p><pre>");
        if (!(files instanceof Roots)) {
            writer.print(
                    "<form method=\"post\"><label for=\"search\">Search Files:</label> <input type=\"text\" name=\"search\" id=\"search\" value=\""
                            + (search != null ? search : "")
                            + "\"> <button type=\"submit\">Search</button></form>");
            writer.print(
                    "<form method=\"post\" enctype=\"multipart/form-data\"><label for=\"upload\">Upload Files:</label> <button type=\"submit\">Upload</button> <button type=\"submit\" name=\"unzip\">Upload & Unzip</button> <input type=\"file\" name=\"upload[]\" id=\"upload\" multiple></form>");
            writer.println();
        }
        if (files instanceof Directory) {
            writer.println("+ <a href=\"?path=" + URLEncoder.encode(path, ENCODING) + "\">.</a>");
            if ((parent = file.getParentFile()) != null)
                writer.println("+ <a href=\"?path=" + URLEncoder.encode(parent.getAbsolutePath(), ENCODING)
                        + "\">..</a>");
            else
                writer.println("+ <a href=\"?path=\">..</a>");
        }

        for (File child : files.listFiles()) {
            writer.print(child.isDirectory() ? "+ " : "  ");
            writer.print("<a href=\"?path=" + URLEncoder.encode(child.getAbsolutePath(), ENCODING)
                    + "\" title=\"" + child.getAbsolutePath() + "\">" + child.getName() + "</a>");
            if (child.isDirectory())
                writer.print(" <a href=\"?path=" + URLEncoder.encode(child.getAbsolutePath(), ENCODING)
                        + "&zip\" title=\"download\">&#8681;</a>");
            if (search != null && !search.isEmpty())
                writer.print(" <a href=\"?path="
                        + URLEncoder.encode(child.getParentFile().getAbsolutePath(), ENCODING)
                        + "\" title=\"go to parent folder\">&#128449;</a>");
            writer.println();
        }
        writer.print("</pre></body></html>");
        writer.flush();
    }
}

From source file:io.snappydata.hydra.cluster.SnappyTest.java

protected synchronized void generateConfig(String fileName) {
    File file = null;
    try {/* w  w w.j  a v a2s .  c  o  m*/
        String path = productConfDirPath + sep + fileName;
        log().info("File Path is ::" + path);
        file = new File(path);

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        } else if (file.exists()) {
            if (isStopMode)
                return;
            file.setWritable(true);
            //file.delete();
            Files.delete(Paths.get(path));
            Log.getLogWriter().info(fileName + " file deleted");
            file.createNewFile();
        }
    } catch (IOException e) {
        String s = "Problem while creating the file : " + file;
        throw new TestException(s, e);
    }
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

public void perforceSync(RepoDetail repodetail, String baseDir, String projectName, String flag)
        throws ConnectionException, RequestException {
    String url = repodetail.getRepoUrl();
    String userName = repodetail.getUserName();
    String password = repodetail.getPassword();
    String stream = repodetail.getStream();
    try {// w  w  w .j a v  a 2 s . c  o  m
        IOptionsServer server = ServerFactory.getOptionsServer("p4java://" + url, null, null);
        server.connect();
        server.setUserName(userName);
        if (password != "") {
            server.login(password);
        }
        IClient client = new Client();
        client.setName(projectName);
        if (flag.equals("update")) {
            String[] rootArr = baseDir.split(projectName);
            String root = rootArr[0].substring(0, rootArr[0].length() - 1);
            client.setRoot(root);
        } else {
            client.setRoot(baseDir);
        }
        client.setServer(server);
        server.setCurrentClient(client);
        ClientViewMapping tempMappingEntry = new ClientViewMapping();
        tempMappingEntry.setLeft(stream + "/...");
        tempMappingEntry.setRight("//" + projectName + "/...");
        ClientView clientView = new ClientView();
        clientView.addEntry(tempMappingEntry);
        try {
            String[] arr = repodetail.getStream().split("//");
            String[] arr1 = arr[1].split("/");
            client.setStream("//" + arr1[0] + "/" + arr1[1]);
            client.setClientView(clientView);
            client.setOptions(new ClientOptions("noallwrite clobber nocompress unlocked nomodtime normdir"));
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new RequestException();
        }
        if (client != null) {
            List<IFileSpec> syncList = client.sync(FileSpecBuilder.makeFileSpecList(stream + "/..."),
                    new SyncOptions());
            for (IFileSpec fileSpec : syncList) {
                if (fileSpec != null) {
                    if (fileSpec.getOpStatus() == FileSpecOpStatus.VALID) {

                    } else {
                        System.err.println(fileSpec.getStatusMessage());
                    }
                }
            }
        }
        IOFileFilter filter = new IOFileFilter() {
            @Override
            public boolean accept(File arg0, String arg1) {
                return true;
            }

            @Override
            public boolean accept(File arg0) {
                return true;
            }
        };
        Iterator<File> iterator = FileUtils.iterateFiles(new File(baseDir), filter, filter);
        while (iterator.hasNext()) {
            File file = iterator.next();
            file.setWritable(true);
        }

    } catch (RequestException rexc) {
        System.err.println(rexc.getDisplayString());
        rexc.printStackTrace();
        throw new RequestException();
    } catch (P4JavaException jexc) {
        System.err.println(jexc.getLocalizedMessage());
        jexc.printStackTrace();
        throw new ConnectionException();
    } catch (Exception exc) {
        System.err.println(exc.getLocalizedMessage());
        exc.printStackTrace();
    }

}

From source file:io.realm.RealmTests.java

@Test
public void getInstance_writeProtectedFile() throws IOException {
    String REALM_FILE = "readonly.realm";
    File folder = configFactory.getRoot();
    File realmFile = new File(folder, REALM_FILE);
    assertFalse(realmFile.exists());// w w  w  . j av a 2 s .c o m
    assertTrue(realmFile.createNewFile());
    assertTrue(realmFile.setWritable(false));

    thrown.expect(RealmIOException.class);
    Realm.getInstance(new RealmConfiguration.Builder(folder).name(REALM_FILE).build());
}

From source file:graphene.rest.ws.impl.UDSessionRSImpl.java

private String saveSessionToFile(final String rootName, final String sessionData) {

    String response = "{ id: \"TBD\", error:\"no error\" }";
    String errormsg = null;/*w w w  . j a  v  a  2 s  .  c o m*/

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final OutputStreamWriter writer = new OutputStreamWriter(outputStream);

    // DEBUG
    logger.debug("saveSessionToFile: sessionData received =");
    logger.debug(sessionData);

    // Create the file on the Web Server
    File filedir = null;
    File file = null;

    // sessionId has this format:
    // userId + "_" + sessionname + "_" + new Date().getTime()).toString()

    String basepath = null;

    // sessionData should contain the following at the beginning
    // {
    // name: "xxx", - Name of the session
    // userId: "yyy", - unique user id for the associated user
    // lastUpdated: "zzz", - Date and timestamp (in milliseconds) when the
    // session was saved by the user
    // sessionActions: ....

    final int indxName = sessionData.indexOf("name");
    final int indxuserId = sessionData.indexOf("userId");
    final int indxDate = sessionData.indexOf("lastUpdated");
    final int indxAfterDate = sessionData.indexOf("sessionActions");
    if ((indxName < 0) || (indxuserId < 0) || (indxDate < 0) || (indxAfterDate < 0)) {
        errormsg = "saveSessionToFile: Invalid session data was received, unable to save it.";
        logger.error(errormsg);
        response = "{ id: \"-1\", error:\"" + errormsg + "\" }";
        return response;
    }

    String sessionName = sessionData.substring(indxName + 5, indxuserId - 1);
    sessionName = sessionName.replace("\"", "");
    sessionName = sessionName.replace(",", "");
    sessionName = sessionName.trim();

    String userId = sessionData.substring(indxuserId + 7, indxDate - 1);
    userId = userId.replace("\"", "");
    userId = userId.replace(",", "");
    userId = userId.trim();

    String lastUpdated = sessionData.substring(indxDate + 12, indxAfterDate - 1);
    lastUpdated = lastUpdated.replace("\"", "");
    lastUpdated = lastUpdated.replace(",", "");
    lastUpdated = lastUpdated.trim();

    if (servletContext != null) {
        basepath = servletContext.getRealPath("/");
    }

    // TODO the file should be placed under the webserver's dir
    if (basepath == null) {
        // TODO - handle case if the Server is Linux instead of Windows
        basepath = "C:/Windows/Temp"; // Temp hack
    }

    try {
        writer.write(sessionData);
    } catch (final IOException e) {
        errormsg = "saveSessionToFile: Server Exception writing session JSON data";
        logger.error(errormsg);
        logger.error(e.getMessage());
        response = "{ id: \"-1\", error:\"" + errormsg + "\" }";
        return response;
    }

    try {
        writer.close();
        outputStream.flush();
        outputStream.close();
    } catch (final java.io.IOException e) {
        errormsg = "saveSessionToFile: I/O Exception when attempting to close output after write. Details "
                + e.getMessage();
        logger.error(errormsg);
        logger.error(e.getMessage());
        response = "{ id: \"-1\", error:\"" + errormsg + "\" }";
        return response;
    }

    // Files are written as:
    // <basepath>/UDS/<userId>/<sessionname>_<date>
    final String serverPathName = basepath + "/" + rootName + "/" + userId;
    final String serverfileName = sessionName + "_" + lastUpdated + ".txt";

    // DEBUG
    logger.debug(
            "saveSessionToFile: serverPathName = " + serverPathName + ", serverfileName = " + serverfileName);

    try {
        filedir = new File(serverPathName);
        filedir.setWritable(true);
        filedir.mkdirs();

        file = new File(serverPathName + "/" + serverfileName);
        final FileOutputStream fout = new FileOutputStream(file);
        fout.write(outputStream.toByteArray());
        fout.close();
        // String finalPath = file.toURI().toString();
        // finalPath = finalPath.replace("file:/", ""); // remove leading

    } catch (final Exception fe) {
        errormsg = "saveSessionToFile: Failed to create file for session data. Details: "
                + fe.getLocalizedMessage();
        logger.error(errormsg);
        response = "{ id: \"-1\", error:\"" + errormsg + "\" }";
        return response;
    }

    // set the unique id of the response
    final String sessionId = createSessionId(userId, sessionName, lastUpdated);

    response = "{ id: \"" + sessionId + "\", error:\"no error\" }";
    return response;
}

From source file:editeurpanovisu.EditeurPanovisu.java

private void sauveHistoFichiers() throws IOException {
    File fichConfig = new File(
            EditeurPanovisu.repertConfig.getAbsolutePath() + File.separator + "derniersprojets.cfg");
    if (!fichConfig.exists()) {
        fichConfig.createNewFile();//from   w  ww . ja v a  2 s.c o m
    }
    fichConfig.setWritable(true);
    String contenuFichier = "";
    for (int i = 0; i < nombreHistoFichiers; i++) {
        contenuFichier += histoFichiers[i] + "\n";
    }
    FileWriter fw = null;
    try {
        fw = new FileWriter(fichConfig);
    } catch (IOException ex) {
        Logger.getLogger(ConfigDialogController.class.getName()).log(Level.SEVERE, null, ex);
    }
    BufferedWriter bw = new BufferedWriter(fw);
    try {
        bw.write(contenuFichier);
    } catch (IOException ex) {
        Logger.getLogger(ConfigDialogController.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        bw.close();
    } catch (IOException ex) {
        Logger.getLogger(ConfigDialogController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:editeurpanovisu.EditeurPanovisu.java

/**
 *
 *///w  w  w. j a  v  a2s  . co m
private void modeleSauver() throws IOException {
    File fichTemplate;
    FileChooser repertChoix = new FileChooser();
    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("fichier Modle panoVisu (*.tpl)",
            "*.tpl");
    repertChoix.getExtensionFilters().add(extFilter);
    File repert = new File(repertAppli + File.separator + "templates");
    if (!repert.exists()) {
        repert.mkdirs();
    }
    repertChoix.setInitialDirectory(repert);
    fichTemplate = repertChoix.showSaveDialog(null);

    if (fichTemplate != null) {
        String contenuFichier = gestionnaireInterface.getTemplate();
        fichTemplate.setWritable(true);
        FileWriter fw = new FileWriter(fichTemplate);
        try (BufferedWriter bw = new BufferedWriter(fw)) {
            bw.write(contenuFichier);
        }
        Dialogs.create().title("Sauvegarde du fichier de Modle")
                .message("Votre modle  bien t sauvegard").showInformation();
    }

}