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.brewcrewfoo.performance.activities.PCSettings.java

@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
    String key = preference.getKey();
    if (key.equals("use_light_theme")) {
        mPreferences.edit().putBoolean("theme_changed", true).commit();
        finish();//from  w  ww . j a v a  2s.c o m
        return true;
    } else if (key.equals("visible_tabs")) {
        startActivity(new Intent(this, HideTabs.class));
        return true;
    } else if (key.equals("boot_mode")) {
        if (mInitd.isChecked()) {
            LayoutInflater factory = LayoutInflater.from(this);
            final View editDialog = factory.inflate(R.layout.prop_edit_dialog, null);
            final EditText tv = (EditText) editDialog.findViewById(R.id.vprop);
            final TextView tn = (TextView) editDialog.findViewById(R.id.nprop);
            tv.setText(mPreferences.getString("script_name", "99PC"));
            tn.setText("");
            tn.setVisibility(TextView.GONE);
            new AlertDialog.Builder(this).setTitle(getString(R.string.pt_script_name)).setView(editDialog)
                    .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String s = tv.getText().toString();
                            if ((s != null) && (s.length() > 0)) {
                                mPreferences.edit().putString("script_name", s).apply();
                            }
                            mInitd.setSummary(INIT_D + mPreferences.getString("script_name", "99PC"));
                            new BootClass(c, mPreferences).writeScript();
                        }
                    }).create().show();
        } else {
            final StringBuilder sb = new StringBuilder();
            sb.append("mount -o rw,remount /system;\n");
            sb.append("busybox rm ").append(INIT_D).append(mPreferences.getString("script_name", "99PC"))
                    .append(";\n");
            sb.append("mount -o ro,remount /system;\n");
            Helpers.shExec(sb, c, true);
        }
        return true;
    } else if (key.equals("int_sd")) {
        LayoutInflater factory = LayoutInflater.from(this);
        final View editDialog = factory.inflate(R.layout.prop_edit_dialog, null);
        final EditText tv = (EditText) editDialog.findViewById(R.id.vprop);
        final TextView tn = (TextView) editDialog.findViewById(R.id.nprop);
        tv.setText("");
        tn.setText(getString(R.string.info_auto_sd));

        new AlertDialog.Builder(this).setTitle(getString(R.string.pt_int_sd)).setView(editDialog)
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String s = tv.getText().toString();
                        if ((s != null) && (s.length() > 0)) {
                            if (s.endsWith("/")) {
                                s = s.substring(0, s.length() - 1);
                            }
                            if (!s.startsWith("/")) {
                                s = "/" + s;
                            }
                            final File dir = new File(s);
                            if (dir.exists() && dir.isDirectory() && dir.canRead() && dir.canWrite())
                                mPreferences.edit().putString("int_sd_path", s).apply();
                        } else {
                            mPreferences.edit().remove("int_sd_path").apply();
                        }
                        mIntSD.setSummary(mPreferences.getString("int_sd_path",
                                Environment.getExternalStorageDirectory().getAbsolutePath()));
                    }
                }).create().show();
    } else if (key.equals("ext_sd")) {
        LayoutInflater factory = LayoutInflater.from(this);
        final View editDialog = factory.inflate(R.layout.prop_edit_dialog, null);
        final EditText tv = (EditText) editDialog.findViewById(R.id.vprop);
        final TextView tn = (TextView) editDialog.findViewById(R.id.nprop);
        tv.setText("");
        tn.setText(getString(R.string.info_auto_sd));

        new AlertDialog.Builder(this).setTitle(getString(R.string.pt_ext_sd)).setView(editDialog)
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String s = tv.getText().toString();
                        if ((s != null) && (s.length() > 0)) {
                            if (s.endsWith("/")) {
                                s = s.substring(0, s.length() - 1);
                            }
                            if (!s.startsWith("/")) {
                                s = "/" + s;
                            }
                            final File dir = new File(s);
                            if (dir.exists() && dir.isDirectory() && dir.canRead() && dir.canWrite())
                                mPreferences.edit().putString("ext_sd_path", s).apply();
                        } else {
                            mPreferences.edit().remove("ext_sd_path").apply();
                        }
                        mExtSD.setSummary(mPreferences.getString("ext_sd_path", Helpers.extSD()));
                    }
                }).create().show();
    } else if (key.equals("br_op")) {
        startActivity(new Intent(this, BackupRestore.class));
    } else if (key.equals("version_info")) {
        if (isupdate && !NO_UPDATE) {
            LayoutInflater factory = LayoutInflater.from(this);
            final View editDialog = factory.inflate(R.layout.ver_dialog, null);
            final TextView msg = (TextView) editDialog.findViewById(R.id.msg);
            msg.setText(det);
            new AlertDialog.Builder(c).setView(editDialog).setTitle(getString(R.string.pt_update))
                    .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    })
                    .setPositiveButton(getString(R.string.btn_download), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (isDownloadManagerAvailable(c)) {
                                String url = URL + TAG + ".apk";
                                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                                //request.setDescription("");
                                request.setTitle(TAG + " " + ver);
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                                    request.allowScanningByMediaScanner();
                                    request.setNotificationVisibility(
                                            DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                }
                                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                        TAG + "-" + ver + ".apk");
                                DownloadManager manager = (DownloadManager) getSystemService(
                                        Context.DOWNLOAD_SERVICE);
                                manager.enqueue(request);
                            } else {
                                Toast.makeText(c, getString(R.string.no_download_manager), Toast.LENGTH_LONG)
                                        .show();
                            }
                        }
                    }).create().show();
        }
        return true;
    } else if (key.equals("pref_donate")) {
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(PAYPAL + PAYPAL_BTN)));
    }
    return false;
}

From source file:ddf.catalog.cache.impl.ResourceCache.java

public void setProductCacheDirectory(final String productCacheDirectory) {
    String newProductCacheDirectoryDir = "";

    if (!StringUtils.isEmpty(productCacheDirectory)) {
        String path = FilenameUtils.normalize(productCacheDirectory);
        File directory = new File(path);

        // Create the directory if it doesn't exist
        if ((!directory.exists() && directory.mkdirs())
                || (directory.isDirectory() && directory.canRead() && directory.canWrite())) {
            LOGGER.debug("Setting product cache directory to: {}", path);
            newProductCacheDirectoryDir = path;
        }/*from  www.  jav  a2s.  c o  m*/
    }

    // if productCacheDirectory is invalid or productCacheDirectory is
    // an empty string, default to the DEFAULT_PRODUCT_CACHE_DIRECTORY in <karaf.home>
    if (newProductCacheDirectoryDir.isEmpty()) {
        try {
            final File karafHomeDir = new File(System.getProperty(KARAF_HOME));

            if (karafHomeDir.isDirectory()) {
                final File fspDir = new File(karafHomeDir + File.separator + DEFAULT_PRODUCT_CACHE_DIRECTORY);

                // if directory does not exist, try to create it
                if (fspDir.isDirectory() || fspDir.mkdirs()) {
                    LOGGER.debug("Setting product cache directory to: {}", fspDir.getAbsolutePath());
                    newProductCacheDirectoryDir = fspDir.getAbsolutePath();
                } else {
                    LOGGER.warn(
                            "Unable to create directory: {}. Please check for proper permissions to create this folder. Instead using default folder.",
                            fspDir.getAbsolutePath());
                }
            } else {
                LOGGER.warn(
                        "Karaf home folder defined by system property {} is not a directory.  Using default folder.",
                        KARAF_HOME);
            }
        } catch (NullPointerException npe) {
            LOGGER.warn(
                    "Unable to create FileSystemProvider folder - {} system property not defined. Using default folder.",
                    KARAF_HOME);
        }
    }

    this.productCacheDirectory = newProductCacheDirectoryDir;

    LOGGER.debug("Set product cache directory to: {}", this.productCacheDirectory);
}

From source file:com.glaf.core.web.springmvc.MxDiskFileUploadJsonController.java

@RequestMapping
public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setContentType("text/html; charset=UTF-8");
    String businessKey = request.getParameter("businessKey");
    String serviceKey = request.getParameter("serviceKey");
    // ?/*from   w w w.  j ava  2s.  c o m*/
    LoginContext loginContext = RequestUtils.getLoginContext(request);
    String savePath = SystemProperties.getAppPath() + "/upload/" + loginContext.getUser().getId() + "/";
    // ?URL
    String saveUrl = request.getContextPath() + "/upload/" + loginContext.getUser().getId() + "/";
    if (StringUtils.isNotEmpty(serviceKey)) {
        saveUrl = saveUrl + serviceKey + "/";
    }
    // ???
    String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp", "swf" };
    // ?
    long maxSize = 10240000;

    String allowSize = CustomProperties.getString("upload.maxSize");
    if (StringUtils.isEmpty(allowSize)) {
        allowSize = SystemProperties.getString("upload.maxSize");
    }

    if (StringUtils.isNotEmpty(allowSize) && StringUtils.isNumeric(allowSize)) {
        maxSize = Long.parseLong(allowSize);
    }

    // 
    File uploadDir = new File(savePath);
    try {
        if (!uploadDir.exists()) {
            FileUtils.mkdirs(savePath);
        }
    } catch (Exception ex) {
    }

    if (!uploadDir.isDirectory()) {
        response.getWriter().write(getError("?"));
        return;
    }
    // ??
    if (!uploadDir.canWrite()) {
        response.getWriter().write(getError("??"));
        return;
    }

    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    Map<String, MultipartFile> fileMap = req.getFileMap();
    Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
    for (Entry<String, MultipartFile> entry : entrySet) {
        MultipartFile mFile = entry.getValue();
        if (mFile.getOriginalFilename() != null && mFile.getSize() > 0) {
            // ?
            if (mFile.getSize() > maxSize) {
                response.getWriter().write(getError("??"));
                return;
            }
            String fileName = mFile.getOriginalFilename();
            // ??
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            if (!Arrays.<String>asList(fileTypes).contains(fileExt)) {
                response.getWriter().write(getError("??????"));
                return;
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String newFileName = df.format(new Date()) + "_" + new Random().nextInt(10000) + "." + fileExt;
            try {
                DataFile dataFile = new BlobItemEntity();
                dataFile.setBusinessKey(businessKey);
                dataFile.setCreateBy(loginContext.getActorId());
                dataFile.setCreateDate(new Date());
                dataFile.setFileId(newFileName);
                dataFile.setLastModified(System.currentTimeMillis());
                dataFile.setName(fileName);
                if (StringUtils.isNotEmpty(serviceKey)) {
                    dataFile.setServiceKey(serviceKey);
                } else {
                    dataFile.setServiceKey("IMG_" + loginContext.getActorId());
                }
                dataFile.setFilename(fileName);
                dataFile.setType(fileExt);
                dataFile.setSize(mFile.getSize());
                dataFile.setStatus(1);
                blobService.insertBlob(dataFile);

                FileUtils.save(savePath + sp + newFileName, mFile.getInputStream());

            } catch (Exception ex) {
                ex.printStackTrace();
                response.getWriter().write(getError("?"));
                return;
            }

            JSONObject object = new JSONObject();
            object.put("error", 0);
            object.put("url", saveUrl + newFileName);
            response.getWriter().write(object.toString());
        }
    }
}

From source file:it.geosolutions.geobatch.geotiff.overview.GeotiffOverviewsEmbedder.java

public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events) throws ActionException {

    try {//from   w w w . j a v  a  2 s .c o  m
        // looking for file
        if (events.size() == 0)
            throw new IllegalArgumentException(
                    "GeotiffOverviewsEmbedder::execute(): Wrong number of elements for this action: "
                            + events.size());

        listenerForwarder.setTask("config");
        listenerForwarder.started();

        // //
        //
        // data flow configuration and dataStore name must not be null.
        //
        // //
        if (configuration == null) {
            final String message = "GeotiffOverviewsEmbedder::execute(): DataFlowConfig is null.";
            if (LOGGER.isErrorEnabled())
                LOGGER.error(message);
            throw new IllegalStateException(message);
        }

        // //
        //
        // check the configuration and prepare the overviews embedder
        //
        // //
        final int downsampleStep = configuration.getDownsampleStep();
        if (downsampleStep <= 0)
            throw new IllegalArgumentException(
                    "GeotiffOverviewsEmbedder::execute(): Illegal downsampleStep: " + downsampleStep);

        int numberOfSteps = configuration.getNumSteps();
        if (numberOfSteps <= 0)
            throw new IllegalArgumentException("Illegal numberOfSteps: " + numberOfSteps);

        final OverviewsEmbedder oe = new OverviewsEmbedder();
        oe.setDownsampleStep(downsampleStep);
        oe.setNumSteps(configuration.getNumSteps());
        // SG: this way we are sure we use the standard tile cache
        oe.setTileCache(JAI.getDefaultInstance().getTileCache());

        String scaleAlgorithm = configuration.getScaleAlgorithm();
        if (scaleAlgorithm == null) {
            LOGGER.warn("No scaleAlgorithm defined. Using " + SubsampleAlgorithm.Nearest + " as default");
            scaleAlgorithm = SubsampleAlgorithm.Nearest.name();
        } else {
            final SubsampleAlgorithm algorithm = SubsampleAlgorithm.valueOf(scaleAlgorithm);
            if (algorithm == null) {
                throw new IllegalStateException("Bad scaleAlgorithm defined [" + scaleAlgorithm + "]");
            }
        }
        oe.setScaleAlgorithm(scaleAlgorithm);
        oe.setTileHeight(configuration.getTileH());
        oe.setTileWidth(configuration.getTileW());

        /*
         * TODO check this is formally wrong! this should be done into the
         * configuration.
         */
        // add logger/listener
        if (configuration.isLogNotification())
            oe.addProcessingEventListener(new ProcessingEventListener() {

                public void exceptionOccurred(ExceptionEvent event) {
                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("GeotiffOverviewsEmbedder::execute(): " + event.getMessage(),
                                event.getException());
                }

                public void getNotification(ProcessingEvent event) {
                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("GeotiffOverviewsEmbedder::execute(): " + event.getMessage());
                    listenerForwarder.progressing((float) event.getPercentage(), event.getMessage());
                }
            });

        // The return
        Queue<FileSystemEvent> ret = new LinkedList<FileSystemEvent>();

        while (events.size() > 0) {

            // run
            listenerForwarder.progressing(0, "Embedding overviews");

            final FileSystemEvent event = events.remove();

            final File eventFile = event.getSource();
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Processing file " + eventFile);

            if (eventFile.exists() && eventFile.canRead() && eventFile.canWrite()) {
                /*
                 * If here: we can start retiler actions on the incoming
                 * file event
                 */

                if (eventFile.isDirectory()) {

                    final FileFilter filter = new RegexFileFilter(".+\\.[tT][iI][fF]([fF]?)");
                    final Collector collector = new Collector(filter);
                    final List<File> fileList = collector.collect(eventFile);
                    int size = fileList.size();
                    for (int progress = 0; progress < size; progress++) {

                        final File inFile = fileList.get(progress);

                        try {
                            oe.setSourcePath(inFile.getAbsolutePath());
                            oe.run();
                        } catch (UnsupportedOperationException uoe) {
                            listenerForwarder.failed(uoe);
                            if (LOGGER.isWarnEnabled())
                                LOGGER.warn("GeotiffOverviewsEmbedder::execute(): " + uoe.getLocalizedMessage(),
                                        uoe);
                        } catch (IllegalArgumentException iae) {
                            listenerForwarder.failed(iae);
                            if (LOGGER.isWarnEnabled())
                                LOGGER.warn("GeotiffOverviewsEmbedder::execute(): " + iae.getLocalizedMessage(),
                                        iae);
                        } finally {
                            listenerForwarder.setProgress((progress * 100) / ((size != 0) ? size : 1));
                            listenerForwarder.progressing();
                        }
                    }
                } else {
                    // file is not a directory
                    try {
                        oe.setSourcePath(eventFile.getAbsolutePath());
                        oe.run();
                    } catch (UnsupportedOperationException uoe) {
                        listenerForwarder.failed(uoe);
                        if (LOGGER.isWarnEnabled())
                            LOGGER.warn("GeotiffOverviewsEmbedder::execute(): " + uoe.getLocalizedMessage(),
                                    uoe);
                    } catch (IllegalArgumentException iae) {
                        listenerForwarder.failed(iae);
                        if (LOGGER.isWarnEnabled())
                            LOGGER.warn("GeotiffOverviewsEmbedder::execute(): " + iae.getLocalizedMessage(),
                                    iae);
                    } finally {
                        listenerForwarder.setProgress(100 / ((events.size() != 0) ? events.size() : 1));
                    }
                }

                // add the directory to the return
                ret.add(event);
            } else {
                final String message = "GeotiffOverviewsEmbedder::execute(): The passed file event refers to a not existent "
                        + "or not readable/writeable file! File: " + eventFile.getAbsolutePath();
                if (LOGGER.isWarnEnabled())
                    LOGGER.warn(message);

                throw new ActionException(this, message);

            }
        } // endwile
        listenerForwarder.completed();

        // return
        if (ret.size() > 0) {
            events.clear();
            return ret;
        } else {
            /*
             * If here: we got an error no file are set to be returned the
             * input queue is returned
             */
            return events;
        }
    } catch (Exception t) {
        final String message = "GeotiffOverviewsEmbedder::execute(): " + t.getLocalizedMessage();
        if (LOGGER.isErrorEnabled())
            LOGGER.error(message, t);
        final ActionException exc = new ActionException(this, message, t);
        listenerForwarder.failed(exc);
        throw exc;
    }
}

From source file:com.eryansky.common.web.servlet.kindeditor.FileUploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String dirName = request.getParameter("dir");
    if (dirName == null) {
        dirName = "image";
    }/*from w w w .  j a va 2 s.co m*/

    //?
    String uploadPath = getInitParameter("UPLOAD_PATH");
    if (StringUtils.isNotBlank(uploadPath)) {
        configPath = uploadPath;
    }

    if ("image".equals(dirName)) {

        //?
        Long size = Long.parseLong(getInitParameter("Img_MAX_SIZE"));
        if (size != null) {
            maxSize = size;
        }

        //(?gif, jpg, jpeg, png, bmp)
        String type = getInitParameter("Img_YPES");
        if (StringUtils.isNotBlank(type)) {
            extMap.put("image", type);
        }

    } else {
        //?
        Long size = Long.parseLong(getInitParameter("File_MAX_SIZE"));
        if (size != null) {
            maxSize = size;
        }

        if ("file".equals(dirName)) {
            //(doc, xls, ppt, pdf, txt, rar, zip)
            String type = getInitParameter("File_TYPES");
            if (StringUtils.isNotBlank(type)) {
                extMap.put("file", type);
            }
        }
    }

    if (StringUtils.isBlank(configPath)) {
        ServletUtils.renderText(getError("?!"), response);
        return;
    }

    //?
    String savePath = this.getServletContext().getRealPath("/") + configPath;

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

    if (!ServletFileUpload.isMultipartContent(request)) {
        ServletUtils.renderText(getError(""), response);
        return;
    }
    //
    File uploadDir = new File(savePath);
    if (!uploadDir.isDirectory()) {
        FileUtil.createDirectory(uploadDir.getPath());
        //         ServletUtils.rendText(getError("?"), response);
        //         return;
    }
    //??
    if (!uploadDir.canWrite()) {
        ServletUtils.renderText(getError("??"), response);
        return;
    }

    if (!extMap.containsKey(dirName)) {
        ServletUtils.renderText(getError("???"), response);
        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");

    try {
        List items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            long fileSize = item.getSize();
            if (!item.isFormField()) {
                //?
                if (item.getSize() > maxSize) {
                    ServletUtils.renderText(getError("??"), response);
                    return;
                }
                //??
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                    ServletUtils
                            .renderText(getError("??????\n??"
                                    + extMap.get(dirName) + "?"), response);
                    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) {
                    ServletUtils.renderText(getError(""), response);
                    return;
                }

                Map<String, Object> obj = Maps.newHashMap();
                obj.put("error", 0);
                obj.put("url", saveUrl + newFileName);
                ServletUtils.renderText(obj, response);
            }
        }
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }

}

From source file:com.lushapp.common.web.servlet.kindeditor.FileUploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String dirName = request.getParameter("dir");
    if (dirName == null) {
        dirName = "image";
    }/*  www .  jav a2s.c om*/

    //?
    String uploadPath = getInitParameter("UPLOAD_PATH");
    if (StringUtils.isNotBlank(uploadPath)) {
        configPath = uploadPath;
    }

    if ("image".equals(dirName)) {

        //?
        Long size = Long.parseLong(getInitParameter("Img_MAX_SIZE"));
        if (size != null) {
            maxSize = size;
        }

        //(?gif, jpg, jpeg, png, bmp)
        String type = getInitParameter("Img_YPES");
        if (StringUtils.isNotBlank(type)) {
            extMap.put("image", type);
        }

    } else {
        //?
        Long size = Long.parseLong(getInitParameter("File_MAX_SIZE"));
        if (size != null) {
            maxSize = size;
        }

        if ("file".equals(dirName)) {
            //(doc, xls, ppt, pdf, txt, rar, zip)
            String type = getInitParameter("File_TYPES");
            if (StringUtils.isNotBlank(type)) {
                extMap.put("file", type);
            }
        }
    }

    if (StringUtils.isBlank(configPath)) {
        WebUtils.renderText(response, getError("?!"));
        return;
    }

    //?
    String savePath = this.getServletContext().getRealPath("/") + configPath;

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

    if (!ServletFileUpload.isMultipartContent(request)) {
        WebUtils.renderText(response, getError(""));
        return;
    }
    //
    File uploadDir = new File(savePath);
    if (!uploadDir.isDirectory()) {
        FileUtil.createDirectory(uploadDir.getPath());
        //         ServletUtils.rendText(getError("?"), response);
        //         return;
    }
    //??
    if (!uploadDir.canWrite()) {
        WebUtils.renderText(response, getError("??"));
        return;
    }

    if (!extMap.containsKey(dirName)) {
        WebUtils.renderText(response, 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");

    try {
        List items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            long fileSize = item.getSize();
            if (!item.isFormField()) {
                //?
                if (item.getSize() > maxSize) {
                    WebUtils.renderText(response, getError("??"));
                    return;
                }
                //??
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                    WebUtils.renderText(response,
                            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) {
                    WebUtils.renderText(response, getError(""));
                    return;
                }

                Map<String, Object> obj = Maps.newHashMap();
                obj.put("error", 0);
                obj.put("url", saveUrl + newFileName);
                WebUtils.renderText(response, obj);
            }
        }
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }

}

From source file:net.sf.profiler4j.console.util.export.FilenameGenerator.java

/**
 * Generates a new filename and returns a corresponding File object.
 * <p>//ww  w. j  av a  2s . c  o  m
 * This method is synchronized, so that file generation does not suffer from
 * concurrency when many snapshots are taken.
 * 
 * @return a valid file object, never {@code null}
 * 
 * @throws FileNotFoundException in case a filename could not be generated from the pattern or
 * no file object could be created. 
 */
public synchronized File getValidFile() throws FileNotFoundException, IOException {
    if (!isValidPattern(pattern)) {
        throw new FileNotFoundException(MSG__INVALID_PATTERN);
    }

    // Get the next file name. If we don't have any placeholders to substitute,
    // the pattern is the filename already.
    String filename = pattern;
    if (pattern.contains(PLACEHOLDER__RUNNING_NUMBER)) {
        filename = generateNextFilename_withPlaceholderSubstitution(pattern);
    }

    // Create the file.
    // There is no deleting of the file in case of error, since only errors may occur
    // that would also prevent us from deleting the file.
    File nextFile = new File(filename);
    if (!nextFile.exists()) {
        try {
            nextFile.createNewFile();
        } catch (IOException exc) {
            throw new FileNotFoundException("Could not create file " + filename + ".");
        }
    }

    // Write-check.
    if (!nextFile.canWrite()) {
        throw new FileNotFoundException("Cannot write to file " + filename + ", no write permissions.");
    }

    return nextFile;
}

From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java

public boolean writeConfiguration(String homeDir, byte[] configurationContents) {
    File root = new File(homeDir);
    if (!root.isDirectory() || !root.canWrite()) {
        return false;
    }/*from  w w  w.  java 2 s  .  c o  m*/
    boolean written = true;
    try {
        ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(configurationContents));
        ZipEntry next = null;
        while ((next = input.getNextEntry()) != null) {
            File newFile = new File(root, next.getName());
            FileUtils.forceMkdir(newFile.getParentFile());

            FileOutputStream file = new FileOutputStream(newFile);
            IOUtils.copy(input, file);
            file.close();
            input.closeEntry();
        }
        input.close();
    } catch (IOException e) {
        log.error("Unable to write configuration files to " + root, e);
        written = false;
    }
    return written;
}

From source file:it.geosolutions.geobatch.geotiff.overview.GeotiffOverviewsEmbedderAction.java

@Override
public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events) throws ActionException {

    try {/*from   w  w w  .j a  v a  2 s. c o  m*/
        // looking for file
        if (events.size() == 0)
            throw new IllegalArgumentException(
                    "GeotiffOverviewsEmbedder::execute(): Wrong number of elements for this action: "
                            + events.size());

        listenerForwarder.setTask("config");
        listenerForwarder.started();

        // //
        //
        // data flow configuration and dataStore name must not be null.
        //
        // //
        if (configuration == null) {
            final String message = "GeotiffOverviewsEmbedder::execute(): DataFlowConfig is null.";
            if (LOGGER.isErrorEnabled())
                LOGGER.error(message);
            throw new IllegalStateException(message);
        }

        // //
        //
        // check the configuration and prepare the overviews embedder
        //
        // //
        final int downsampleStep = configuration.getDownsampleStep();
        if (downsampleStep <= 0)
            throw new IllegalArgumentException(
                    "GeotiffOverviewsEmbedder::execute(): Illegal downsampleStep: " + downsampleStep);

        int numberOfSteps = configuration.getNumSteps();
        if (numberOfSteps <= 0)
            throw new IllegalArgumentException("Illegal numberOfSteps: " + numberOfSteps);

        final OverviewsEmbedder oe = new OverviewsEmbedder();
        oe.setDownsampleStep(downsampleStep);
        oe.setNumSteps(configuration.getNumSteps());
        // SG: this way we are sure we use the standard tile cache
        oe.setTileCache(JAI.getDefaultInstance().getTileCache());

        String scaleAlgorithm = configuration.getScaleAlgorithm();
        if (scaleAlgorithm == null) {
            LOGGER.warn("No scaleAlgorithm defined. Using " + SubsampleAlgorithm.Nearest + " as default");
            scaleAlgorithm = SubsampleAlgorithm.Nearest.name();
        } else {
            final SubsampleAlgorithm algorithm = SubsampleAlgorithm.valueOf(scaleAlgorithm);
            if (algorithm == null) {
                throw new IllegalStateException("Bad scaleAlgorithm defined [" + scaleAlgorithm + "]");
            }
        }
        oe.setScaleAlgorithm(scaleAlgorithm);
        oe.setTileHeight(configuration.getTileH());
        oe.setTileWidth(configuration.getTileW());

        /*
         * TODO check this is formally wrong! this should be done into the
         * configuration.
         */
        // add logger/listener
        if (configuration.isLogNotification())
            oe.addProcessingEventListener(new ProcessingEventListener() {

                public void exceptionOccurred(ExceptionEvent event) {
                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("GeotiffOverviewsEmbedder::execute(): " + event.getMessage(),
                                event.getException());
                }

                public void getNotification(ProcessingEvent event) {
                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("GeotiffOverviewsEmbedder::execute(): " + event.getMessage());
                    listenerForwarder.progressing((float) event.getPercentage(), event.getMessage());
                }
            });

        // The return
        Queue<FileSystemEvent> ret = new LinkedList<FileSystemEvent>();

        while (events.size() > 0) {

            // run
            listenerForwarder.progressing(0, "Embedding overviews");

            final FileSystemEvent event = events.remove();

            final File eventFile = event.getSource();
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Processing file " + eventFile);

            if (eventFile.exists() && eventFile.canRead() && eventFile.canWrite()) {
                /*
                 * If here: we can start retiler actions on the incoming
                 * file event
                 */

                if (eventFile.isDirectory()) {

                    final FileFilter filter = new RegexFileFilter(".+\\.[tT][iI][fF]([fF]?)");
                    final Collector collector = new Collector(filter);
                    final List<File> fileList = collector.collect(eventFile);
                    int size = fileList.size();
                    for (int progress = 0; progress < size; progress++) {

                        final File inFile = fileList.get(progress);

                        try {
                            oe.setSourcePath(inFile.getAbsolutePath());
                            oe.run();
                        } catch (UnsupportedOperationException uoe) {
                            listenerForwarder.failed(uoe);
                            if (LOGGER.isWarnEnabled())
                                LOGGER.warn("GeotiffOverviewsEmbedder::execute(): " + uoe.getLocalizedMessage(),
                                        uoe);
                        } catch (IllegalArgumentException iae) {
                            listenerForwarder.failed(iae);
                            if (LOGGER.isWarnEnabled())
                                LOGGER.warn("GeotiffOverviewsEmbedder::execute(): " + iae.getLocalizedMessage(),
                                        iae);
                        } finally {
                            listenerForwarder.setProgress((progress * 100) / ((size != 0) ? size : 1));
                            listenerForwarder.progressing();
                        }
                    }
                } else {
                    // file is not a directory
                    try {
                        oe.setSourcePath(eventFile.getAbsolutePath());
                        oe.run();
                    } catch (UnsupportedOperationException uoe) {
                        listenerForwarder.failed(uoe);
                        if (LOGGER.isWarnEnabled())
                            LOGGER.warn("GeotiffOverviewsEmbedder::execute(): " + uoe.getLocalizedMessage(),
                                    uoe);
                    } catch (IllegalArgumentException iae) {
                        listenerForwarder.failed(iae);
                        if (LOGGER.isWarnEnabled())
                            LOGGER.warn("GeotiffOverviewsEmbedder::execute(): " + iae.getLocalizedMessage(),
                                    iae);
                    } finally {
                        listenerForwarder.setProgress(100 / ((events.size() != 0) ? events.size() : 1));
                    }
                }

                // add the directory to the return
                ret.add(event);
            } else {
                final String message = "GeotiffOverviewsEmbedder::execute(): The passed file event refers to a not existent "
                        + "or not readable/writeable file! File: " + eventFile.getAbsolutePath();
                if (LOGGER.isWarnEnabled())
                    LOGGER.warn(message);

                throw new ActionException(this, message);

            }
        } // endwile
        listenerForwarder.completed();

        // return
        if (ret.size() > 0) {
            events.clear();
            return ret;
        } else {
            /*
             * If here: we got an error no file are set to be returned the
             * input queue is returned
             */
            return events;
        }
    } catch (Exception t) {
        final String message = "GeotiffOverviewsEmbedder::execute(): " + t.getLocalizedMessage();
        if (LOGGER.isErrorEnabled())
            LOGGER.error(message, t);
        final ActionException exc = new ActionException(this, message, t);
        listenerForwarder.failed(exc);
        throw exc;
    }
}

From source file:FileErrorManager.java

/**
 * Performs the initialization for this object.
 *//*from  w ww  .  j  a v  a  2  s . c  o m*/
private void init() {
    if (next == null) {
        throw new NullPointerException(ErrorManager.class.getName());
    }

    File dir = this.emailStore;
    if (dir.getClass() != File.class) { //For security reasons.
        throw new IllegalArgumentException(dir.getClass().getName());
    }

    if (!dir.isDirectory()) {
        throw new IllegalArgumentException("File must be a directory.");
    }

    if (!dir.canWrite()) { //Can throw under a security manager.
        super.error(dir.getAbsolutePath(), new SecurityException("write"), ErrorManager.OPEN_FAILURE);
    }

    //For now, only absolute paths are allowed.
    if (!dir.isAbsolute()) {
        throw new IllegalArgumentException("Only absolute paths are allowed.");
    }

    if (!dir.canRead()) { //Can throw under a security manager.
        super.error(dir.getAbsolutePath(), new SecurityException("read"), ErrorManager.OPEN_FAILURE);
    }
}