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:de.xplib.xdbm.util.Config.java

/**
 * //from   w ww  .j a  va 2s  .c o m
 */
private void readConfig() {

    File etc = new File("/etc");
    File xdbm = new File("/etc/xdbm");
    File home = new File(System.getenv("HOME") + "/.xdbm");

    boolean root = false;
    if (!etc.canWrite()) {
        if (!home.exists()) {
            home.mkdir();
        }
    } else {
        if (!xdbm.exists()) {
            xdbm.mkdir();
        }
        root = true;
    }

    File global = new File(xdbm.getAbsolutePath() + "/ui-config.xml");
    File user = new File(home.getAbsolutePath() + "/ui-config.xml");

    this.cfgFile = (root ? global : user);

    if (!global.exists() && !user.exists()) {
        return;
    }
    // if exist first read global
    if (global.exists()) {
        this.parseConfig(global);
    }
    // overwrite globals with user settings
    if (user.exists()) {
        this.parseConfig(user);
    }
}

From source file:seava.j4e.web.controller.ui.extjs.UiExtjsFrameController.java

/**
 * Handler for a frame html page./*from   w  w  w.  j a v  a2 s.co 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 {
        try {
            @SuppressWarnings("unused")
            ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication()
                    .getPrincipal();
        } catch (java.lang.ClassCastException e) {
            throw new BusinessException(ErrorCode.SEC_NOT_AUTHENTICATED, "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));

        String logo = this.getSettings().getParam(SysParam.CORE_LOGO_URL_EXTJS.name());

        if (logo != null && !logo.equals("")) {
            model.put("logo", logo);
        }

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

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

            DependencyLoader loader = this.getDependencyLoader(request);
            loader.resolveFrameDependencies(bundle, frameFQN, (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.viewName, model);
    } catch (Exception e) {
        this.handleManagedExceptionAsHtml(null, e, response);
        return null;
    }
}

From source file:eu.eubrazilcc.lvl.core.entrez.EntrezHelper.java

/**
 * Fetches the sequence identified by its accession id and saves it in the specified directory.
 * @param id - accession identifier./*  w  w w . ja v a 2s .  co  m*/
 * @param directory - the directory where the file will be saved.
 * @param format - the format that will be used to store the file.
 */
public void saveNucleotide(final String id, final File directory, final Format format) {
    checkArgument(isNotBlank(id), "Uninitialized or invalid Id");
    checkArgument(directory != null && (directory.isDirectory() || directory.mkdirs()) && directory.canWrite(),
            "Uninitialized or invalid directory");
    try {
        efetch(newArrayList(id), 0, 1, directory, format);
    } catch (Exception e) {
        LOGGER.error("Fetching nucleotide sequence failed", e);
    }
}

From source file:org.springsource.ide.eclipse.commons.internal.configurator.ui.ConfiguratorPreferencesPage.java

@Override
protected Control createContents(Composite parent) {
    Composite composite = new Composite(parent, SWT.NONE);
    GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite);

    Label label = new Label(composite, SWT.WRAP);
    label.setText("Configurable Extensions:");
    GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(label);

    extensionViewer = new TableViewer(composite, SWT.BORDER | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.SINGLE);
    extensionViewer.getTable().setHeaderVisible(true);
    extensionViewer.getTable().setLinesVisible(true);
    extensionViewer.setSorter(new ViewerSorter() {
        @SuppressWarnings("unchecked")
        @Override//from ww w .ja  v a  2s.c om
        public int compare(Viewer viewer, Object e1, Object e2) {
            String name1 = ((ConfigurableExtension) e1).getLabel();
            String name2 = ((ConfigurableExtension) e2).getLabel();
            return getComparator().compare(name1, name2);
        }
    });
    extensionViewer.setContentProvider(new IStructuredContentProvider() {

        Object[] elements;

        public void dispose() {
            // ignore
        }

        public Object[] getElements(Object inputElement) {
            return elements;
        }

        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
            this.elements = (Object[]) newInput;
        }
    });
    GridDataFactory.fillDefaults().grab(true, true).applyTo(extensionViewer.getControl());

    TableViewerColumn statusColumn = new TableViewerColumn(extensionViewer, SWT.LEFT);
    statusColumn.getColumn().setText("");
    statusColumn.getColumn().setToolTipText("Configured");
    statusColumn.getColumn().setWidth(20);
    statusColumn.setLabelProvider(new ColumnLabelProvider() {
        @Override
        public Image getImage(Object element) {
            if (((ConfigurableExtension) element).isConfigured()) {
                return CommonImages.getImage(CommonImages.COMPLETE);
            }
            return null;
        }

        @Override
        public String getText(Object element) {
            return "";
        }
    });

    TableViewerColumn extensionColumn = new TableViewerColumn(extensionViewer, SWT.LEFT);
    extensionColumn.getColumn().setText("Extension");
    extensionColumn.getColumn().setWidth(250);
    extensionColumn.setLabelProvider(new ColumnLabelProvider() {
        @Override
        public String getText(Object element) {
            return ((ConfigurableExtension) element).getLabel();
        }
    });
    TableViewerColumn locationColumn = new TableViewerColumn(extensionViewer, SWT.LEFT);
    locationColumn.getColumn().setText("Location");
    locationColumn.getColumn().setWidth(150);
    locationColumn.setLabelProvider(new ColumnLabelProvider() {
        @Override
        public String getText(Object element) {
            return ((ConfigurableExtension) element).getLocation();
        }
    });
    extensionViewer.setInput(elements.toArray());

    Composite buttonComposite = new Composite(composite, SWT.NONE);
    GridDataFactory.fillDefaults().grab(false, true).applyTo(buttonComposite);
    RowLayout layout = new RowLayout(SWT.VERTICAL);
    layout.fill = true;
    layout.marginLeft = 0;
    layout.marginTop = 0;
    layout.marginRight = 0;
    layout.marginBottom = 0;
    buttonComposite.setLayout(layout);

    configureButton = new Button(buttonComposite, SWT.NONE);
    configureButton.setText(" &Configure ");
    configureButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            ConfigurableExtension extension = getSelectedExtension(extensionViewer.getSelection());
            if (extension != null) {
                doConfigure(extension);
            }
        }
    });
    installButton = new Button(buttonComposite, SWT.NONE);
    installButton.setText(" &Install ");
    installButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            IStructuredSelection selection = (IStructuredSelection) extensionViewer.getSelection();
            ConfigurableExtension extension = (ConfigurableExtension) selection.getFirstElement();
            if (extension != null) {
                doInstall(extension);
            }
        }
    });

    Button refreshButton = new Button(buttonComposite, SWT.NONE);
    refreshButton.setText(" &Refresh ");
    refreshButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            doRefresh();
        }
    });

    extensionViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            updateSelection(event.getSelection());
        }
    });

    updateSelection(extensionViewer.getSelection());

    Group locationGroup = new Group(composite, SWT.NONE);
    GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(locationGroup);
    locationGroup.setText("Runtime Locations");
    GridLayoutFactory.swtDefaults().numColumns(3).applyTo(locationGroup);

    File systemLocation = importer.getSystemLocation();
    if (systemLocation != null) {
        label = new Label(locationGroup, SWT.WRAP);
        label.setText("Search path for runtimes:");
        GridDataFactory.fillDefaults().grab(true, false).hint(100, SWT.DEFAULT).span(3, 1).applyTo(label);
        searchLocationsLabel = new Label(locationGroup, SWT.NONE);
        GridDataFactory.fillDefaults().grab(true, false).hint(100, SWT.DEFAULT).span(3, 1)
                .applyTo(searchLocationsLabel);
    }

    useDefaultUserLocationButton = new Button(locationGroup, SWT.CHECK);
    GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(useDefaultUserLocationButton);
    useDefaultUserLocationButton.setText("Use Default");
    useDefaultUserLocationButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            userLocationText.setEnabled(!useDefaultUserLocationButton.getSelection());
            browseButton.setEnabled(!useDefaultUserLocationButton.getSelection());
            if (useDefaultUserLocationButton.getSelection()) {
                resetUserLocation();
            }
        }
    });

    label = new Label(locationGroup, SWT.WRAP);
    label.setText("Install Location:");

    userLocationText = new Text(locationGroup, SWT.BORDER);
    userLocationText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    userLocationText.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent event) {
            try {
                File file = new File(userLocationText.getText());
                if (!file.canWrite()) {
                    setErrorMessage(NLS.bind("''{0}'' is not writeable. Please select a different directory.",
                            userLocationText.getText()));
                    setInstallEnabled(false);
                } else {
                    setErrorMessage(null);
                    setInstallEnabled(true);
                }
            } catch (Exception e) {
                setErrorMessage(NLS.bind("''{0}'' is not a valid path.", userLocationText.getText()));
                setInstallEnabled(false);
            }
        }
    });

    browseButton = new Button(locationGroup, SWT.NONE);
    browseButton.setText("Directory...");
    browseButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            DirectoryDialog dialog = new DirectoryDialog(getShell());
            dialog.setMessage("Select the root directory for installing extensions.");
            String path = userLocationText.getText();
            path = path.replaceAll("\\\\", "/");
            dialog.setFilterPath(path);
            path = dialog.open();
            if (path == null || path.equals("")) { //$NON-NLS-1$
                return;
            }
            path = path.replaceAll("\\\\", "/");
            userLocationText.setText(path);
        }
    });

    initWidgets();

    return composite;
}

From source file:com.hp.mqm.clt.CliParserTest.java

@Test
public void testParser_outputFile() throws IOException, URISyntaxException {
    CliParser cliParser = new CliParser();
    File outputFile = new File(temporaryFolder.newFolder(), "testResults.xml");
    Settings settings = cliParser.parse(new String[] { "--started", "123456", "-a", "2", "--output-file",
            outputFile.getPath(), "-c", getClass().getResource("test.properties").toURI().getPath(),
            getClass().getResource("JUnit-minimalAccepted.xml").toURI().getPath() });
    Assert.assertEquals(Long.valueOf(123456), settings.getStarted());
    Assert.assertTrue(outputFile.canWrite());
    Assert.assertEquals("http://localhost:8080/qcbin", settings.getServer());
    Assert.assertEquals(Integer.valueOf(1001), settings.getSharedspace());
    Assert.assertEquals(Integer.valueOf(1002), settings.getWorkspace());
    Assert.assertEquals("admin", settings.getUser());
}

From source file:com.ikanow.infinit.e.application.handlers.polls.LogstashHarvestPollHandler.java

@Override
public void performPoll() {

    boolean isSlave = false;

    if (null == LOGSTASH_CONFIG) { // (static memory not yet initialized)
        try {/*www  .  j a  v  a  2  s. c o  m*/
            Thread.sleep(1000); // (extend the sleep time a bit)
        } catch (Exception e) {
        }
        return;
    }

    File logstashDirectory = new File(LOGSTASH_CONFIG);
    String logstashDirName = LOGSTASH_CONFIG;
    if (!logstashDirectory.isDirectory() || !logstashDirectory.canRead() || !logstashDirectory.canWrite()) {
        logstashDirectory = new File(LOGSTASH_CONFIG_DISTRIBUTED);
        logstashDirName = LOGSTASH_CONFIG_DISTRIBUTED;
        isSlave = true;
        if (!logstashDirectory.isDirectory() || !logstashDirectory.canRead() || !logstashDirectory.canWrite()) {
            try {
                Thread.sleep(10000); // (extend the sleep time a bit)
            } catch (Exception e) {
            }
            return;
        }
    }

    if (null == _props) {
        _props = new PropertiesManager();
        _appProps = new ApplicationProperties();
        _clusterName = _props.getElasticCluster();
    }
    boolean useHttpOutput = _appProps.useHttpOutput();
    if (null == _testOutputTemplate_stashed) {
        try {
            File testOutputTemplate = useHttpOutput ? new File(LOGSTASH_TEST_OUTPUT_TEMPLATE_STASHED_HTTP)
                    : new File(LOGSTASH_TEST_OUTPUT_TEMPLATE_STASHED_BINARY);
            InputStream inStream = null;
            try {
                inStream = new FileInputStream(testOutputTemplate);
                _testOutputTemplate_stashed = IOUtils.toString(inStream);
            } catch (Exception e) {// abandon ship!
                return;
            } finally {
                inStream.close();
            }
        } catch (Exception e) {// abandon ship!
            //DEBUG
            //e.printStackTrace();
            return;
        }
    } //TESTED
    if (null == _testOutputTemplate_live) {
        try {
            File testOutputTemplate = useHttpOutput ? new File(LOGSTASH_TEST_OUTPUT_TEMPLATE_LIVE_HTTP)
                    : new File(LOGSTASH_TEST_OUTPUT_TEMPLATE_LIVE_BINARY);
            InputStream inStream = null;
            try {
                inStream = new FileInputStream(testOutputTemplate);
                _testOutputTemplate_live = IOUtils.toString(inStream);
            } catch (Exception e) {// abandon ship!
                return;
            } finally {
                inStream.close();
            }
        } catch (Exception e) {// abandon ship!
            //DEBUG
            //e.printStackTrace();
            return;
        }
    } //TESTED

    // 0] Race condition protection: if we're still waiting for the last restart to happen then don't do anything else

    if (new File(LOGSTASH_RESTART_FILE).exists()) {
        //DEBUG
        //System.out.println("Waiting for last restart to occur");

        try {
            Thread.sleep(10000); // (extend the sleep time a bit)
        } catch (Exception e) {
        }
        return;
    } //TESTED

    // 1] Get the time of the most recent change

    File[] files = logstashDirectory.listFiles();
    long directoryTime = -1L;
    for (File toCheck : files) {
        if (toCheck.getName().endsWith(LOGSTASH_CONFIG_EXTENSION)) {
            directoryTime = toCheck.lastModified();
            break; // Get the time of the most recent change
        }
    } //TESTED

    //DEBUG
    //if (-1L != directoryTime) System.out.println("LAST CHANGE = " + new Date(directoryTime));

    // 2] Check vs the sources

    boolean modifiedConfiguration = false;
    for (;;) { // This is an inefficient but safe way of beating source publish races

        // Logstash type, not suspended
        BasicDBObject srcQuery = new BasicDBObject(SourcePojo.extractType_, "Logstash");
        // (need both suspended and active sources)
        srcQuery.put(SourcePojo.isApproved_, true);
        srcQuery.put(SourcePojo.harvestBadSource_, false);

        DBCursor dbc = DbManager.getIngest().getSource().find(srcQuery);
        List<SourcePojo> srcList = SourcePojo.listFromDb(dbc, SourcePojo.listType(),
                new SourcePojoSubstitutionDbMap());
        long mostRecentlyChangedSource = 0L;
        for (SourcePojo src : srcList) {
            // Some input checking:
            if (ignoreSource(src, isSlave)) {
                continue;
            }
            if ((null != src.getModified()) && (src.getModified().getTime() > directoryTime)) {

                //DEBUG
                //System.out.println("MODIFIED SRC=" + src.getModified() + ": " + src.getTitle());
                _logger.info("modified src mod=" + src.getModified() + " key=" + src.getKey() + " title="
                        + src.getTitle());

                if (src.getModified().getTime() > mostRecentlyChangedSource) {

                    boolean modified = !isSuspended(src);
                    if (!modified) { // check if corresponding file exists
                        if (new File(logstashDirName + src.getId() + LOGSTASH_CONFIG_EXTENSION).exists()) {
                            modified = true;
                            //DEBUG
                            //System.out.println("ACTIVE->SUSPENDED SRC=" + src.getModified() + ": " + src.getTitle());
                            _logger.info("active->suspended src mod=" + src.getModified() + " key="
                                    + src.getKey() + " title=" + src.getTitle());
                        }
                        //DEBUG
                        //else System.out.println("(...MODIFIED SUSPENDED SRC=" + src.getModified() + ": " + src.getTitle());
                        _logger.info("(...modified suspended src mod=" + src.getModified() + " key="
                                + src.getKey() + " title=" + src.getTitle());

                    } //TESTED
                    if (modified) {
                        mostRecentlyChangedSource = src.getModified().getTime();
                        // (don't break want the latest file time to set the file times)
                    }
                }
            }
        } //(end loop over sources)         

        // 3] Handle modified source(s)

        if (0 == mostRecentlyChangedSource) {
            break;
        } else {
            // Delete the directory
            cleanseDirectory(logstashDirectory);

            int numSources = 0;
            int numSourcesSuspended = 0;
            int numSourcesIgnored = 0;
            for (SourcePojo src : srcList) {
                numSources++;
                // Some input checking:
                if (ignoreSource(src, isSlave)) {
                    numSourcesIgnored++;
                    continue;
                }
                if (!isSuspended(src)) {
                    createConfigFileFromSource(src, mostRecentlyChangedSource, logstashDirName);
                } else {
                    numSourcesSuspended++;
                }
            } //TESTED
            _logger.info("Rebuilding logstash configurations for: source=" + numSources + " ignored="
                    + numSourcesIgnored + " suspended=" + numSourcesSuspended);

            modifiedConfiguration = true;

            // and now .... will recheck with this new time
            directoryTime = mostRecentlyChangedSource;
        }
    } //(end loop over source check)

    if (modifiedConfiguration) {
        try {
            _logger.info("Restarting logstash");

            new File(LOGSTASH_RESTART_FILE).createNewFile();
        } //TESTED
        catch (Exception e) {
            //DEBUG
            //e.printStackTrace();

        } // (should never happen)
    } //TESTED
}

From source file:de.uni_rostock.goodod.evaluator.OntologyTest.java

private void writeNormalizedOntologiesTo(Set<URI> URIs, OntologyCache cache, File directory) {
    if ((false == directory.isDirectory()) || (false == directory.canWrite())) {
        logger.warn("Cannot write to directory '" + directory + "'.");
        return;// w  w w  .j a  va2s  .co  m
    }
    logger.info("Writing normalized ontologies to" + directory);
    for (URI u : URIs) {
        try {
            writeNormalizedOntologyTo(u, cache.getOntologyAtURI(u).get(), directory);
        } catch (Throwable e) {
            logger.warn("Error writing ontology.", e);
        }
    }
}

From source file:de.ipbhalle.metfrag.main.CommandLineTool.java

/**
 * /*from w  ww  .  j  a  va 2  s. c  o  m*/
 * check file for existence etc.
 * 
 * @param filename
 * @param shouldBeWriteable
 * @return
 */
public static boolean checkForFile(String filename, boolean shouldBeReadable, boolean shouldBeWriteable) {
    File file = new File(filename);
    if (!file.exists()) {
        System.out.println("Error: Can not access file " + filename + ". Not found.");
        return false;
    } else if (!file.isFile()) {
        System.out.println("Error: Can not access file " + filename + ". No file.");
        return false;
    } else if (shouldBeReadable && !file.canRead()) {
        System.out.println("Error: Can not read file " + filename + ". No permissions.");
        return false;
    }
    if (shouldBeWriteable && !file.canWrite()) {
        System.out.println("Error: Can not write into file " + filename + ". No permissions.");
        return false;
    }
    return true;
}

From source file:net.daboross.bukkitdev.playerdata.PlayerHandlerImpl.java

void savePData(PlayerData pd) {
    if (pd == null) {
        return;/* w w  w .  j  av a 2s  .  c o m*/
    }
    File file = new File(dataFolder, pd.getUsername() + ".xml");
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException ex) {
            playerDataPlugin.getLogger().log(Level.SEVERE,
                    "Exception creating new file " + file.getAbsolutePath(), ex);
            return;
        }
    }
    if (file.canWrite()) {
        try {
            XMLParserFinder.save(pd, file);
        } catch (DXMLException ex) {
            playerDataPlugin.getLogger().log(Level.SEVERE,
                    "Exception saving data to file " + file.getAbsolutePath(), ex);
        }
    } else {
        playerDataPlugin.getLogger().log(Level.SEVERE, "Can\'t write to file {0}", file.getAbsolutePath());
    }
}

From source file:net.schweerelos.parrot.ui.GraphViewComponent.java

private void maybeSaveLayout() {
    if (layout instanceof PersistentLayout) {
        PersistentLayout<NodeWrapper, NodeWrapper> theLayout = (PersistentLayout<NodeWrapper, NodeWrapper>) layout;
        try {/* w w w .  j a v a  2 s.  c  o  m*/
            String filename = getLayoutFilename();
            File directory = new File(filename).getParentFile();
            if (!directory.canWrite()) {
                directory.mkdirs();
            }
            theLayout.persist(filename);
        } catch (IOException e) {
            // TODO #1 Auto-generated catch block
            e.printStackTrace();
        }
    }
}