Example usage for java.io File canWrite

List of usage examples for java.io File canWrite

Introduction

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

Prototype

public boolean canWrite() 

Source Link

Document

Tests whether the application can modify the file denoted by this abstract pathname.

Usage

From source file:net.nan21.dnet.core.web.controller.ui.extjs.UiExtjsFrameController.java

/**
 * Handler for a frame html page.//from  w w w. j  ava 2 s. c o  m
 * 
 * @param frame
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/{bundle}/{frameFQN}", method = RequestMethod.GET)
protected ModelAndView home(@PathVariable("frameFQN") String frame, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    try {
        @SuppressWarnings("unused")
        ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    } catch (java.lang.ClassCastException e) {
        throw new NotAuthorizedRequestException("Not authenticated");
    }

    Map<String, Object> model = new HashMap<String, Object>();
    this._prepare(model, request, response);

    String[] tmp = request.getPathInfo().split("/");
    String frameFQN = tmp[tmp.length - 1];
    String bundle = tmp[tmp.length - 2];
    String[] t = frameFQN.split("\\.");
    String frameName = t[t.length - 1];

    model.put("item", frameFQN);
    model.put("itemSimpleName", frameName);
    model.put("bundle", bundle);

    // get extensions
    model.put("extensions", getExtensionFiles(frameFQN, uiExtjsSettings.getUrlModules()));

    model.put("extensionsContent", getExtensionContent(frameFQN));

    if (Constants.PROP_WORKING_MODE_DEV.equalsIgnoreCase(this.getSettings().get(Constants.PROP_WORKING_MODE))) {

        List<String> listCmp = new ArrayList<String>();
        List<String> listTrl = new ArrayList<String>();

        DependencyLoader loader = this.getDependencyLoader();
        loader.resolveFrameDependencies(bundle, frameName, (String) model.get("shortLanguage"), listCmp,
                listTrl);

        model.put("frameDependenciesCmp", listCmp);
        model.put("frameDependenciesTrl", listTrl);

    } else {
        if (this.cacheFolderWritable == null) {
            synchronized (this) {
                if (this.cacheFolderWritable == null) {

                    if (this.cacheFolder == null) {
                        this.cacheFolder = this.getUiExtjsSettings().getCacheFolder();
                    }

                    File cf = new File(this.cacheFolder);
                    if (!cf.exists()) {

                        if (!cf.mkdirs()) {
                            throw new Exception("Cache folder " + this.cacheFolder
                                    + " does not exist and could not be created.");
                        }
                    }

                    if (!cf.isDirectory() || !cf.canWrite()) {
                        throw new Exception("Cache folder " + this.cacheFolder
                                + " is not writeable. Cannot pack and cache the frame dependencies for the configured `prod` working mode. ");
                    }
                    this.cacheFolderWritable = true;
                }
            }
        }
    }
    return new ModelAndView(this.jspName, model);
}

From source file:com.linkedin.restli.tools.snapshot.gen.RestLiSnapshotExporter.java

private GeneratorResult generateSnapshotFiles(String apiName, String outdir,
        Map<String, ResourceModel> rootResourceMap, DocsProvider docsProvider) throws IOException {
    SnapshotResult result = new SnapshotResult();

    final File outdirFile = new File(outdir);
    if (!outdirFile.exists()) {
        if (!outdirFile.mkdirs()) {
            throw new RuntimeException("Output directory '" + outdir + "' could not be created!");
        }//w  ww.  ja  v  a 2s  . co  m
    }
    if (!outdirFile.isDirectory()) {
        throw new RuntimeException("Output directory '" + outdir + "' is not a directory");
    }
    if (!outdirFile.canRead() || !outdirFile.canWrite()) {
        throw new RuntimeException("Output directory '" + outdir + "' must be writeable");
    }

    final ResourceModelEncoder encoder = new ResourceModelEncoder(docsProvider);

    final List<ResourceSchema> rootResourceNodes = new ArrayList<ResourceSchema>();
    for (Map.Entry<String, ResourceModel> entry : rootResourceMap.entrySet()) {
        final ResourceSchema rootResourceNode = encoder.buildResourceSchema(entry.getValue());
        rootResourceNodes.add(rootResourceNode);
    }

    for (ResourceSchema rootResourceNode : rootResourceNodes) {
        String fileName = rootResourceNode.getName();
        if (rootResourceNode.hasNamespace()) {
            final String namespace = rootResourceNode.getNamespace();
            fileName = namespace + "." + fileName;
        }
        if (apiName != null && !apiName.isEmpty()) {
            fileName = apiName + "-" + fileName;
        }

        File writtenFile = writeSnapshotFile(outdirFile, fileName, rootResourceNode);
        result.addModifiedFile(writtenFile);
        result.addTargetFile(writtenFile);
    }

    return result;
}

From source file:com.parse.ParseFileUtils.java

/**
 * Copies a file to a new location.//from  w ww.  jav  a 2 s.  com
 * <p>
 * This method copies the contents of the specified source file
 * to the specified destination file.
 * The directory holding the destination file is created if it does not exist.
 * If the destination file exists, then this method will overwrite it.
 * <p>
 * <strong>Note:</strong> Setting <code>preserveFileDate</code> to
 * {@code true} tries to preserve the file's last modified
 * date/times using {@link File#setLastModified(long)}, however it is
 * not guaranteed that the operation will succeed.
 * If the modification operation fails, no indication is provided.
 *
 * @param srcFile  an existing file to copy, must not be {@code null}
 * @param destFile  the new file, must not be {@code null}
 * @param preserveFileDate  true if the file date of the copy
 *  should be the same as the original
 *
 * @throws NullPointerException if source or destination is {@code null}
 * @throws IOException if source or destination is invalid
 * @throws IOException if an IO error occurs during copying
 * @throws IOException if the output file length is not the same as the input file length after the copy completes
 * @see #copyFileToDirectory(File, File, boolean)
 * @see #doCopyFile(File, File, boolean)
 */
public static void copyFile(final File srcFile, final File destFile, final boolean preserveFileDate)
        throws IOException {
    if (srcFile == null) {
        throw new NullPointerException("Source must not be null");
    }
    if (destFile == null) {
        throw new NullPointerException("Destination must not be null");
    }
    if (srcFile.exists() == false) {
        throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
    }
    if (srcFile.isDirectory()) {
        throw new IOException("Source '" + srcFile + "' exists but is a directory");
    }
    if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
        throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
    }
    final File parentFile = destFile.getParentFile();
    if (parentFile != null) {
        if (!parentFile.mkdirs() && !parentFile.isDirectory()) {
            throw new IOException("Destination '" + parentFile + "' directory cannot be created");
        }
    }
    if (destFile.exists() && destFile.canWrite() == false) {
        throw new IOException("Destination '" + destFile + "' exists but is read-only");
    }
    doCopyFile(srcFile, destFile, preserveFileDate);
}

From source file:com.htmlhifive.pitalium.core.io.FilePersister.java

/**
 * ??????????????<br>/*from   w  w w.  j av a 2s  .c om*/
 * ?????????
 * 
 * @param file ?
 * @return ?
 */
private File checkParentFileAvailable(File file) {
    File parent = file.getParentFile();
    if (!parent.exists() && !parent.mkdirs()) {
        throw new TestRuntimeException(String.format(Locale.US, "mkdir error \"%s\"", parent));
    }
    if (!parent.canWrite()) {
        throw new TestRuntimeException(String.format(Locale.US, "No write permission at \"%s\"", parent));
    }

    return file;
}

From source file:com.liferay.portal.configuration.ConfigurationImpl.java

protected void updateBasePath(ClassLoader classLoader, String name) {
    InputStream inputStream = null;

    try {/*from ww  w  .  ja  v a2  s .c  o  m*/
        URL url = classLoader.getResource(name + Conventions.PROPERTIES_EXTENSION);

        if (url == null) {
            return;
        }

        String protocol = url.getProtocol();

        if (!protocol.equals("file")) {
            return;
        }

        Properties properties = new Properties();

        inputStream = url.openStream();

        properties.load(inputStream);

        if (properties.containsKey("base.path")) {
            return;
        }

        String fileName = StringUtil.replace(url.getFile(), "%20", StringPool.SPACE);

        File file = new File(fileName);

        if (!file.exists() || !file.canWrite()) {
            if (_log.isWarnEnabled()) {
                _log.warn("Unable to write " + file);
            }

            return;
        }

        Writer writer = new FileWriter(file, true);

        StringBundler sb = new StringBundler(4);

        sb.append(StringPool.OS_EOL);
        sb.append(StringPool.OS_EOL);
        sb.append("base.path=");

        String basePath = url.getPath();

        int pos = basePath.lastIndexOf(StringPool.SLASH + name + Conventions.PROPERTIES_EXTENSION);

        if (pos != -1) {
            basePath = basePath.substring(0, pos);
        }

        sb.append(basePath);

        writer.write(sb.toString());

        writer.close();
    } catch (Exception e) {
        _log.error(e, e);
    } finally {
        StreamUtil.cleanUp(inputStream);
    }
}

From source file:me.neatmonster.spacertk.actions.FileActions.java

/**
 * Gets information about a File/* ww w.ja  v  a  2  s  .c  o m*/
 * @param file File to get information about
 * @return Information about a file
 */
@Action(aliases = { "getFileInformations", "fileInformations", "informations" })
public TreeMap<String, Object> getFileInformations(final String file) {
    final TreeMap<String, Object> fileInformations = new TreeMap<String, Object>();
    final File file_ = new File(file);
    if (file_.exists()) {
        fileInformations.put("Name", file_.getName());
        fileInformations.put("Path", file_.getPath());
        fileInformations.put("Size", file_.length());
        fileInformations.put("Execute", file_.canExecute());
        fileInformations.put("Read", file_.canRead());
        fileInformations.put("Write", file_.canWrite());
        fileInformations.put("IsDirectory", file_.isDirectory());
        fileInformations.put("IsFile", file_.isFile());
        fileInformations.put("IsHidden", file_.isHidden());
        final FileNameMap fileNameMap = URLConnection.getFileNameMap();
        fileInformations.put("Mime", fileNameMap.getContentTypeFor("file://" + file_.getPath()));
        return fileInformations;
    }
    return new TreeMap<String, Object>();
}

From source file:hivemall.topicmodel.ProbabilisticTopicModelBaseUDTF.java

protected void recordTrainSampleToTempFile(@Nonnull final String[] wordCounts) throws HiveException {
    if (iterations == 1) {
        return;/*from  ww  w . j av a  2 s .c o m*/
    }

    ByteBuffer buf = inputBuf;
    NioStatefulSegment dst = fileIO;

    if (buf == null) {
        final File file;
        try {
            file = File.createTempFile("hivemall_topicmodel", ".sgmt");
            file.deleteOnExit();
            if (!file.canWrite()) {
                throw new UDFArgumentException("Cannot write a temporary file: " + file.getAbsolutePath());
            }
            logger.info("Record training samples to a file: " + file.getAbsolutePath());
        } catch (IOException ioe) {
            throw new UDFArgumentException(ioe);
        } catch (Throwable e) {
            throw new UDFArgumentException(e);
        }
        this.inputBuf = buf = ByteBuffer.allocateDirect(1024 * 1024); // 1 MB
        this.fileIO = dst = new NioStatefulSegment(file, false);
    }

    // wordCounts length, wc1 length, wc1 string, wc2 length, wc2 string, ...
    int wcLengthTotal = 0;
    for (String wc : wordCounts) {
        if (wc == null) {
            continue;
        }
        wcLengthTotal += wc.length();
    }
    int recordBytes = SizeOf.INT + SizeOf.INT * wordCounts.length + wcLengthTotal * SizeOf.CHAR;
    int requiredBytes = SizeOf.INT + recordBytes; // need to allocate space for "recordBytes" itself

    int remain = buf.remaining();
    if (remain < requiredBytes) {
        writeBuffer(buf, dst);
    }

    buf.putInt(recordBytes);
    buf.putInt(wordCounts.length);
    for (String wc : wordCounts) {
        NIOUtils.putString(wc, buf);
    }
}

From source file:com.nary.io.FileUtils.java

private static List<Map<String, cfData>> createFileVector(List<File> files, File rootdir, boolean recurse) {
    if (files == null)
        return null;

    String rootDirString = rootdir.getAbsolutePath();
    List<Map<String, cfData>> resultVector = new ArrayList<Map<String, cfData>>();
    int rootprefix = 1 + rootDirString.length();

    for (int i = 0; i < files.size(); i++) {
        File f = files.get(i);
        Map<String, cfData> hm = new FastMap<String, cfData>();

        if (recurse) {
            // Make this a relative path
            hm.put("name", new cfStringData(f.getAbsolutePath().substring(rootprefix)));
            hm.put("directory", new cfStringData(rootDirString));
        } else {/* w  w  w  .j av a 2s . c  om*/
            hm.put("name", new cfStringData(f.getName()));
            hm.put("directory", new cfStringData(f.getParent()));
        }

        hm.put("size", new cfNumberData(f.length()));

        if (f.isDirectory()) {
            hm.put("type", new cfStringData("Dir"));
        } else {
            hm.put("type", new cfStringData("File"));
        }

        hm.put("datelastmodified", new cfDateData(f.lastModified()));

        StringBuilder attrs = new StringBuilder();

        if (!f.canWrite())
            attrs.append('R');

        if (f.isHidden())
            attrs.append('H');

        hm.put("attributes", new cfStringData(attrs.toString()));
        hm.put("mode", new cfStringData(""));

        resultVector.add(hm);
    }

    return resultVector;
}

From source file:com.slytechs.file.snoop.SnoopFileCapture.java

private void openFile(final File file, Filter<ProtocolFilterTarget> filter)
        throws IOException, FileFormatException {

    if (file.canRead() == false) {
        throw new FileNotFoundException(
                "File [" + file.getName() + "] is not readable, can not open in [" + mode.toString() + "]mode");
    }//from ww w .  j a  v  a  2 s .c o m

    if (mode.isAppend() || mode.isContent() || mode.isStructure()) {
        if (file.canWrite() == false) {
            throw new FileNotFoundException(
                    "File [" + file.getName() + "] is readonly, can not open in read-write mode");
        }
    }

    this.editor = new FileEditorImpl(file, this.mode, headerReader, ByteOrder.BIG_ENDIAN, filter, this);
    try {
        this.block = new SnoopBlockRecordImpl(this, this.editor);
    } finally {
        if (this.block == null) {
            /*
             * Make sure to close the editor in case any errors occured, otherwise
             * we could keep the file open until the VM terminates
             */
            this.editor.close();
        }
    }

    final Protocol dlt = SnoopDLT.asConst(block.getLinktype());
    setCaptureDevice(new DefaultCaptureDevice(dlt));

    if (logger.isDebugEnabled()) {
        logger.debug("edito=" + editor.getFlexRegion().toString());
    }

}

From source file:fr.gael.dhus.database.DatabasePostInit.java

/**
 * Recursively walk a directory tree and remove all the empty directory if
 * they are a part of {@link HierarchicalDirectoryNode} tree.
 *
 * @param aStartingDir is a valid directory, which can be read.
 *///from   w w w . java  2 s. c  o  m
private void cleanupIncoming(File starting_dir) {
    if (!starting_dir.isDirectory() && !starting_dir.canWrite()) {
        throw new IllegalParameterException("starting dir shall be a writable directory.");
    }
    File[] files = starting_dir.listFiles();
    for (File file : files) {

        if (incomingManager.isAnIncomingElement(file))
            cleanupIncoming(file);
    }
    // recheck the children list to know if this direct can be removed.
    files = starting_dir.listFiles();
    if (files.length == 0) {
        logger.info("deleting empty folder :" + starting_dir.getPath());
        starting_dir.delete();
    }
}