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:com.adaptris.fs.StandardWorkerTest.java

@Test
public void testCheckNonExistent() throws Exception {
    File exists = Mockito.mock(File.class);
    Mockito.when(exists.exists()).thenReturn(true);
    try {/*from  ww w.j  a v a  2 s . c o  m*/
        FsWorker.checkNonExistent(exists);
        fail();
    } catch (FsException expected) {

    }
    File nonExistent = Mockito.mock(File.class);
    Mockito.when(nonExistent.canRead()).thenReturn(false);
    Mockito.when(nonExistent.exists()).thenReturn(false);
    Mockito.when(nonExistent.canWrite()).thenReturn(true);
    FsWorker.checkNonExistent(nonExistent);
}

From source file:com.wintindustries.pfserver.PFDefaultLibrary.FileServices.PFFileServiceLocal.PFFileServiceLocal.java

@Override
public synchronized boolean connect() throws PFFileServiceConnectionException {
    // check for read write acsess 

    File f = new File(config.getRootDirectoryURL());

    String path = config.getRootDirectoryURL() + "*";
    f.mkdirs();//from w ww  . j  av a  2 s . com
    String actions = "read,write";

    if (f.canWrite()) {
        System.out.println("File " + f.getPath() + " can be written");

        return true;
    } else if (f.canRead()) {
        System.out.println("File " + f.getPath() + " can be read");
        throw new PFFileServiceConnectionExceptionReadOnly("PATH: " + f.getPath());

    } else {
        System.out.println("File " + f.getPath() + " can not be read");
        throw new PFFileServiceConnectionExceptionAcsessDenied("PATH: " + f.getPath());

    }
    /*
    try {
        AccessController.checkPermission(new FilePermission(path, actions));
            
        System.out.println("You have read/write permition to use : " + path);
             return true;
            
    } catch (SecurityException e) {
       String actions2 = "read";
            
       try {
        AccessController.checkPermission(new FilePermission(path, actions));
            
        System.out.println("You have read permition to use : " + path);
             throw new PFFileServiceConnectionExceptionReadOnly(path);
                     
    } catch (SecurityException ex) {
            System.out.println("You have no permition to use : " + path);
            
            
             throw new  PFFileServiceConnectionExceptionAcsessDenied(ex.getLocalizedMessage());
    }
    }
      //  System.out.println("You have read/write permition to use : " + path);
       //    return false;
    */
}

From source file:net.sourceforge.dita4publishers.tools.ditadxpunpacker.DitaDxpUnpacker.java

/**
 * @throws Exception // ww w.  j  av  a  2  s  .c  om
 * 
 */
private void run() throws Exception {

    DitaDxpOptions dxpOptions = new DitaDxpOptions();
    handleCommonBosProcessorOptions(dxpOptions);

    String dxpFilepath = commandLine.getOptionValue(INPUT_OPTION_ONE_CHAR);
    File dxpFile = new File(dxpFilepath);
    checkExistsAndCanReadSystemExit(dxpFile);
    if (!dxpOptions.isQuiet())
        log.info("Processing DXP package \"" + dxpFile.getAbsolutePath() + "\"...");

    String outputDirpath = commandLine.getOptionValue(OUTPUT_OPTION_ONE_CHAR);
    File outputDir = new File(outputDirpath);
    if (outputDir.exists() && !outputDir.isDirectory()) {
        System.err.println("Output directory \"" + outputDirpath + "\" is not a directory.");
        System.exit(1);
    }

    outputDir.mkdirs();
    if (!outputDir.exists()) {
        System.err.println("Failed to create output directory \"" + outputDirpath + "\".");
        System.exit(1);
    }

    if (!outputDir.canWrite()) {
        System.err.println("Cannot write to output directory \"" + outputDirpath + "\".");
        System.exit(1);
    }

    String[] mapIds = commandLine.getOptionValues(MAPS_ID_OPTION_ONE_CHAR);
    if (mapIds != null && mapIds.length > 0) {
        for (String mapId : mapIds) {
            dxpOptions.addMapId(mapId);
        }
    }

    try {
        DitaDxpHelper.unpackDxpPackage(dxpFile, outputDir, dxpOptions, log);
    } catch (DitaDxpException e) {
        System.err.println("DITA DXP Error: " + e.getMessage());
    }

}

From source file:com.jivesoftware.os.filer.queue.store.TwoPhasedFileQueueImpl.java

/**
 * should only be called once/*from   w  w w.  j  a v a2 s.  c  o  m*/
 *
 * @param makeItThisMode
 * @throws IOException
 */
public void init(long makeItThisMode) throws IOException {
    synchronized (appendLock) {
        if (!(state == State.CLOSED || state == State.OFF)) {
            throw new RuntimeException("queue not in a valid state to open opened state=" + state);
        }
        state = State.OPENING;
        File queueFolder = queueFolder();
        ensureDirectory(new File(queueFolder, "."));
        if (!queueFolder.exists() || !queueFolder.canWrite() || !queueFolder.canRead()) {
            logger.error("we have a filesystem permissions issue!");
            throw new IOException("invalid permissions exsist:" + queueFolder.exists() + " canwrite:"
                    + queueFolder.canWrite() + " canread:" + queueFolder.canWrite() + " path:"
                    + pathToQueueFiles + " queueName:" + queueName + " queueFolder:" + queueFolder);
        }
        populateFullQueuesInBackground(queueFolder.listFiles(), makeItThisMode);
        appendingTo = new FileQueue(newQueueFile(queueFolder), hardFlush);

        state = State.OPENED;
    }
}

From source file:com.truthbean.core.web.kindeditor.FileUpload.java

@Override
public void service(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {

    final PageContext pageContext;
    HttpSession session = null;// w ww . jav  a2  s . co m
    final ServletContext application;
    final ServletConfig config;
    JspWriter out = null;
    final Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
        response.setContentType("text/html; charset=UTF-8");
        pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
        _jspx_page_context = pageContext;
        application = pageContext.getServletContext();
        config = pageContext.getServletConfig();
        session = pageContext.getSession();
        out = pageContext.getOut();
        _jspx_out = out;

        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");

        /**
         * KindEditor JSP
         *
         * JSP???? ??
         *
         */
        // ?
        String savePath = pageContext.getServletContext().getRealPath("/") + "resource/";

        String savePath$ = savePath;

        // ?URL
        String saveUrl = request.getContextPath() + "/resource/";

        // ???
        HashMap<String, String> extMap = new HashMap<>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

        // ?
        long maxSize = 10 * 1024 * 1024 * 1024L;

        response.setContentType("text/html; charset=UTF-8");

        if (!ServletFileUpload.isMultipartContent(request)) {
            out.println(getError(""));
            return;
        }
        // 
        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
            out.println(getError("?"));
            return;
        }
        // ??
        if (!uploadDir.canWrite()) {
            out.println(getError("??"));
            return;
        }

        String dirName = request.getParameter("dir");
        if (dirName == null) {
            dirName = "image";
        }
        if (!extMap.containsKey(dirName)) {
            out.println(getError("???"));
            return;
        }
        // 
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        List items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            if (!item.isFormField()) {
                // ?
                if (item.getSize() > maxSize) {
                    out.println(getError("??"));
                    return;
                }
                // ??
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if (!Arrays.asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                    out.println(getError("??????\n??"
                            + extMap.get(dirName) + "?"));
                    return;
                }

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                try {
                    File uploadedFile = new File(savePath, newFileName);
                    item.write(uploadedFile);
                } catch (Exception e) {
                    out.println(getError(""));
                    return;
                }

                JSONObject obj = new JSONObject();
                obj.put("error", 0);
                obj.put("url", saveUrl + newFileName);

                request.getSession().setAttribute("fileName", savePath$ + fileName);
                request.getSession().setAttribute("filePath", savePath + newFileName);
                request.getSession().setAttribute("fileUrl", saveUrl + newFileName);

                out.println(obj.toJSONString());
            }
        }

        out.write('\r');
        out.write('\n');
    } catch (IOException | FileUploadException t) {
        if (!(t instanceof javax.servlet.jsp.SkipPageException)) {
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0) {
                if (response.isCommitted()) {
                    out.flush();
                } else {
                    out.clearBuffer();
                }
            }
            if (_jspx_page_context != null) {
                _jspx_page_context.handlePageException(t);
            } else {
                throw new ServletException(t);
            }
        }
    } finally {
        _jspxFactory.releasePageContext(_jspx_page_context);
    }
}

From source file:com.zimbra.common.calendar.ZoneInfo2iCalendar.java

private static Params initParams(CommandLine cl)
        throws IOException, org.apache.commons.cli.ParseException, ParseException {
    Params params = new Params();
    if (cl.hasOption(OPT_HELP))
        return params;

    if (cl.hasOption(OPT_OUTPUT_FILE)) {
        String fname = cl.getOptionValue(OPT_OUTPUT_FILE);
        File file = new File(fname);
        File parent = file.getParentFile();
        if (parent == null)
            parent = new File(".");
        if (!parent.exists())
            throw new FileNotFoundException("Output directory " + parent.getAbsolutePath() + " doesn't exist");
        if (!parent.canWrite())
            throw new IOException("Permission denied on directory " + parent.getAbsolutePath());
        params.outputFile = file;// w ww  .j a  va 2 s  .  c o m
    }

    if (cl.hasOption(OPT_DATE)) {
        String dateStr = cl.getOptionValue(OPT_DATE);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = formatter.parse(dateStr);
        params.referenceDate = new GregorianCalendar();
        params.referenceDate.setTime(date);
    } else if (cl.hasOption(OPT_YEAR)) {
        String yearStr = cl.getOptionValue(OPT_YEAR);
        try {
            params.referenceDate = new GregorianCalendar(Integer.parseInt(yearStr), 1, 1);
        } catch (NumberFormatException e) {
            throw new org.apache.commons.cli.ParseException("Invalid year " + yearStr);
        }
    } else {
        params.referenceDate = new GregorianCalendar();
    }

    if (cl.hasOption(OPT_LAST_MODIFIED)) {
        String lastMod = cl.getOptionValue(OPT_LAST_MODIFIED);
        if (!lastMod.matches("\\d{8}T\\d{6}Z"))
            throw new org.apache.commons.cli.ParseException(
                    "--" + OPT_LAST_MODIFIED + " option must match the pattern YYYYMMDDThhmmssZ");
        params.lastModified = lastMod;
    } else {
        Calendar now = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        params.lastModified = String.format("%04d%02d%02dT%02d%02d%02dZ", now.get(Calendar.YEAR),
                now.get(Calendar.MONTH) + 1, now.get(Calendar.DAY_OF_MONTH), now.get(Calendar.HOUR_OF_DAY),
                now.get(Calendar.MINUTE), now.get(Calendar.SECOND));
    }

    if (cl.hasOption(OPT_OLD_TIMEZONES_FILE)) {
        params.oldTimezonesFileName = cl.getOptionValue(OPT_OLD_TIMEZONES_FILE);
    } else {
        params.oldTimezonesFileName = null;
    }

    if (cl.hasOption(OPT_EXTRA_DATA_FILE)) {
        File file = new File(cl.getOptionValue(OPT_EXTRA_DATA_FILE));
        if (!file.exists())
            throw new FileNotFoundException(
                    "Primary TZ list file " + file.getAbsolutePath() + " doesn't exist");
        if (!file.canRead())
            throw new IOException("Permission denied on file " + file.getAbsolutePath());
        params.extraDataFile = file;
    }

    List<File> sourceFiles = new ArrayList<File>();

    if (cl.hasOption(OPT_TZDATA_DIR)) {
        File dir = new File(cl.getOptionValue(OPT_TZDATA_DIR));
        if (!dir.exists())
            throw new FileNotFoundException("Source directory " + dir.getAbsolutePath() + " doesn't exist");
        if (!dir.canRead())
            throw new IOException("Permission denied on directory " + dir.getAbsolutePath());

        File files[] = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (!file.isFile())
                    continue;
                // Skip some known non data files: *.tab, *.sh and "factory".
                String name = file.getName();
                if (name.endsWith(".tab") || name.endsWith(".sh") || name.endsWith(".awk")
                        || name.endsWith(".pl") || (name.startsWith(".") || name.endsWith(".swp")) || // ignore editor temporary files
                        name.equalsIgnoreCase("CONTRIBUTING") || name.equalsIgnoreCase("Makefile")
                        || name.equalsIgnoreCase("NEWS") || name.equalsIgnoreCase("README")
                        || name.equalsIgnoreCase("LICENSE") || name.equalsIgnoreCase("Theory")
                        || name.equalsIgnoreCase("factory") || name.equalsIgnoreCase("leap-seconds.list")) {
                    continue;
                }
                if (!file.canRead())
                    throw new IOException("Permission denied on file " + file.getAbsolutePath());
                sourceFiles.add(file);
            }
        }
    }

    // Any leftover arguments are tzdata source filenames.
    String dataFiles[] = cl.getArgs();
    if (dataFiles != null) {
        for (String fname : dataFiles) {
            File file = new File(fname);
            if (!file.exists())
                throw new FileNotFoundException("Source file " + file.getAbsolutePath() + " doesn't exist");
            if (!file.canRead())
                throw new IOException("Permission denied on file " + file.getAbsolutePath());
            sourceFiles.add(file);
        }
    }

    if (sourceFiles.isEmpty())
        throw new org.apache.commons.cli.ParseException("No tzdata source files/directory specified");

    params.tzdataFiles = sourceFiles.toArray(new File[0]);

    return params;
}

From source file:com.adaptris.fs.StandardWorkerTest.java

@Test
public void testCheckWriteable() throws Exception {
    File nonExistent = Mockito.mock(File.class);
    Mockito.when(nonExistent.exists()).thenReturn(false);
    try {/*from w w  w  . j a v a2  s.  c  o  m*/
        FsWorker.checkWriteable(nonExistent);
        fail();
    } catch (FsException expected) {

    }
    File unreadable = Mockito.mock(File.class);
    Mockito.when(unreadable.canRead()).thenReturn(false);
    Mockito.when(unreadable.exists()).thenReturn(true);
    Mockito.when(unreadable.canWrite()).thenReturn(true);
    try {
        FsWorker.checkWriteable(unreadable);
        fail();
    } catch (FsException expected) {

    }

    File unWriteable = Mockito.mock(File.class);
    Mockito.when(unWriteable.canWrite()).thenReturn(false);
    Mockito.when(unWriteable.exists()).thenReturn(true);
    Mockito.when(unWriteable.canRead()).thenReturn(true);
    try {
        FsWorker.checkWriteable(unWriteable);
        fail();
    } catch (FsException expected) {

    }
    try {
        FsWorker.checkWriteable(null);
        fail();
    } catch (FsException | IllegalArgumentException expected) {

    }

}

From source file:fullThreadDump.java

public void writeDump(String file, String data) throws IOException {
    // choose our dump-file
    Writer writer = null;/* w ww . j a v a2s.  c o  m*/
    File dumpFile = null;
    String date = new SimpleDateFormat("MMddyyyy").format(new Date(System.currentTimeMillis()));
    try {
        File tmp = new File(file);
        if (tmp.exists() && !tmp.isDirectory() && tmp.canWrite()) {
            writer = new BufferedWriter(new FileWriter(tmp, true));
            writer.write(data);
        }
        if (tmp.isDirectory() && tmp.canWrite()) {
            dumpFile = new File(
                    file + File.separator + "threadDump." + Long.toString(System.currentTimeMillis()));
            writer = new BufferedWriter(new FileWriter(dumpFile, true));
            writer.write(data);
        } else {
            writer = new BufferedWriter(new FileWriter(tmp, true));
            writer.write(data);
        }
    } catch (IOException e) {
        System.out.print(e);
    } finally {
        writer.close();
    }
}

From source file:by.heap.remark.Main.java

private void checkOutput(CommandLine cl, Args result, List<String> error) {
    if (cl.hasOption('o')) {
        File output = new File(cl.getOptionValue('o')).getAbsoluteFile();
        result.output = output;/*from ww w.  jav  a 2s  .c o m*/
        if (!output.exists()) {
            // check for parent path
            File parent = output.getParentFile();
            if (parent.exists() && !parent.isDirectory()) {
                error.add("Output does is not a valid path.");
            } else {
                if (!parent.exists() && !parent.mkdirs()) {
                    error.add("Output path could not be created.");
                } else if (!parent.canWrite()) {
                    error.add("Output directory cannot be written to.");
                }
            }
        } else if (!output.isFile()) {
            error.add("Output file exists and is not a file");
        } else if (!output.canWrite()) {
            error.add("Output file cannot be written to.");
        }
    }
}