Example usage for java.io File setReadOnly

List of usage examples for java.io File setReadOnly

Introduction

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

Prototype

public boolean setReadOnly() 

Source Link

Document

Marks the file or directory named by this abstract pathname so that only read operations are allowed.

Usage

From source file:net.audumla.climate.bom.BOMDataLoader.java

synchronized public BufferedReader getData(String conntype, String host, String location) {
    String tmpFileName = generateLocalFileName(conntype, host + "_" + location);
    boolean loadedRemote = false;
    if (cache.hasDataExpired(tmpFileName)) {
        try {//from w w  w .  j  a v  a2  s .c  o m
            File file = new File(new File(System.getProperty("java.io.tmpdir")), tmpFileName);

            if (conntype.equals(FTP)) {
                storeFTPFile(host, location, file);
            } else {
                storeHTTPFile(host, location, file);
            }
            cache.add(tmpFileName);
            loadedRemote = true;
        } catch (Exception ex) {
            throw new UnsupportedOperationException("Cannot load data from - " + location, ex);
        }
    }
    try {
        File file = new File(new File(System.getProperty("java.io.tmpdir")), tmpFileName);
        file.setReadOnly();
        FileReader fr = new FileReader(file);
        if (!loadedRemote) {
            LOG.info("Retrieved cached content - " + tmpFileName);
        }
        return new BufferedReader(fr);
    } catch (FileNotFoundException e) {
        throw new UnsupportedOperationException("Cannot load file - " + tmpFileName);
    }
}

From source file:com.l2jfree.loginserver.L2LoginIdentifier.java

private synchronized void load() {
    if (isLoaded())
        return;/*from   w w w. j a va 2 s.c  o  m*/

    File f = new File(System.getProperty("user.home", null), FILENAME);
    ByteBuffer bb = ByteBuffer.allocateDirect(8);

    if (!f.exists() || f.length() != 8) {
        _uid = getRandomUID();
        _loaded = true;
        _log.info("A new UID has been generated for this login server.");

        FileOutputStream fos = null;
        try {
            f.createNewFile();
            fos = new FileOutputStream(f);
            FileChannel fc = fos.getChannel();
            bb.putLong(getUID());
            bb.flip();
            fc.write(bb);
            fos.flush();
        } catch (IOException e) {
            _log.warn("Could not store login server's UID!", e);
        } finally {
            IOUtils.closeQuietly(fos);
            f.setReadOnly();
        }
    } else {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(f);
            FileChannel fc = fis.getChannel();
            fc.read(bb);
        } catch (IOException e) {
            _log.warn("Could not read stored login server's UID!", e);
        } finally {
            IOUtils.closeQuietly(fis);
        }

        if (bb.position() > 0) {
            bb.flip();
            _uid = bb.getLong();
        } else
            _uid = getRandomUID();
        _loaded = true;
    }
}

From source file:com.krawler.esp.servlets.importICSServlet.java

public static Calendar setUpICal(String url, String ID, int interval) throws ServiceException {
    Calendar calByUrl = null;//w  w w.ja  va  2  s.  c o m
    try {
        setSystemProperties();
        boolean fileCreated = false;

        File file = new File(
                StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator() + ID + ".ics");

        if (file.exists()) { // if this calendar file exists in the store?
            java.util.Calendar cal = java.util.Calendar.getInstance();
            cal.setTime(new Date());
            cal.add(java.util.Calendar.MINUTE, interval);
            if (new Date(file.lastModified()).before(cal.getTime())
                    || new Date(file.lastModified()).equals(cal.getTime())) { // if its older than given time?
                fileCreated = getICalFileFromURL(file, url, true);
                if (fileCreated) {
                    interval = interval * -1;
                    Tree.updateInternetCalendar(ID, interval, true);
                    file.setLastModified(new Date().getTime());
                }
            } else {
                fileCreated = true;
            }
        } else { // file does not exists. it has to be created.
            fileCreated = getICalFileFromURL(file, url, false);
            if (fileCreated)
                file.setLastModified(new Date().getTime());
        }
        if (fileCreated) {
            FileInputStream fip = new FileInputStream(file);
            CalendarBuilder cb = new CalendarBuilder(new CalendarParserImpl());
            calByUrl = cb.build(fip);
            fip.close();
            file.setReadOnly();
            if (!calByUrl.toString().contains(Organizer.ORGANIZER)) {
                Property p = new Organizer("MAILTO:calendar@deskera.com");
                calByUrl.getProperties().add(p);
            }
            calByUrl.validate();
        }
    } catch (FileNotFoundException e) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calFileEx, e);
    } catch (ValidationException e) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calValidationEx, e);
    } catch (ParserException e) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calParseEx, e);
    } catch (ConfigurationException e) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calFileEx, e);
    } catch (URISyntaxException e) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calURLEx, e);
    } catch (IOException e) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calIOEx, e);
    } catch (Exception e) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calIOEx, e);
    }
    return calByUrl;
}

From source file:com.athena.peacock.agent.netty.PeacockClientHandler.java

@SuppressWarnings("unchecked")
@Override/*from  ww w.  j a va2 s .  c o m*/
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.debug("channelRead0() has invoked.");

    logger.debug("[Client] Object => " + msg.getClass().getName());
    logger.debug("[Client] Contents => " + msg.toString());

    if (msg instanceof PeacockDatagram) {
        MessageType messageType = ((PeacockDatagram<?>) msg).getMessageType();

        if (messageType.equals(MessageType.COMMAND)) {
            ProvisioningResponseMessage response = new ProvisioningResponseMessage();
            response.setAgentId(((PeacockDatagram<ProvisioningCommandMessage>) msg).getMessage().getAgentId());
            response.setBlocking(((PeacockDatagram<ProvisioningCommandMessage>) msg).getMessage().isBlocking());

            ((PeacockDatagram<ProvisioningCommandMessage>) msg).getMessage().executeCommands(response);

            ctx.writeAndFlush(new PeacockDatagram<ProvisioningResponseMessage>(response));
        } else if (messageType.equals(MessageType.PACKAGE_INFO)) {
            ctx.writeAndFlush("Start OS Package collecting...");

            String packageFile = null;

            try {
                packageFile = PropertyUtil.getProperty(PeacockConstant.PACKAGE_FILE_KEY);
            } catch (Exception e) {
                // nothing to do.
            } finally {
                if (StringUtils.isEmpty(packageFile)) {
                    packageFile = "/peacock/agent/config/package.log";
                }
            }

            new PackageGatherThread(ctx, packageFile).start();
        } else if (messageType.equals(MessageType.INITIAL_INFO)) {
            machineId = ((PeacockDatagram<AgentInitialInfoMessage>) msg).getMessage().getAgentId();
            String packageCollected = ((PeacockDatagram<AgentInitialInfoMessage>) msg).getMessage()
                    .getPackageCollected();
            String softwareInstalled = ((PeacockDatagram<AgentInitialInfoMessage>) msg).getMessage()
                    .getSoftwareInstalled();

            String agentFile = null;
            String agentId = null;

            try {
                agentFile = PropertyUtil.getProperty(PeacockConstant.AGENT_ID_FILE_KEY);
            } catch (Exception e) {
                // nothing to do.
            } finally {
                if (StringUtils.isEmpty(agentFile)) {
                    agentFile = "/peacock/agent/.agent";
                }
            }

            File file = new File(agentFile);
            boolean isNew = false;

            try {
                agentId = IOUtils.toString(file.toURI());

                if (!agentId.equals(machineId)) {
                    isNew = true;
                }
            } catch (IOException e) {
                logger.error(agentFile + " file cannot read or saved invalid agent ID.", e);
            }

            if (isNew) {
                logger.info("New Agent-ID({}) will be saved.", machineId);

                try {
                    file.setWritable(true);
                    OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(file));
                    output.write(machineId);
                    file.setReadOnly();
                    IOUtils.closeQuietly(output);
                } catch (UnsupportedEncodingException e) {
                    logger.error("UnsupportedEncodingException has occurred : ", e);
                } catch (FileNotFoundException e) {
                    logger.error("FileNotFoundException has occurred : ", e);
                } catch (IOException e) {
                    logger.error("IOException has occurred : ", e);
                }
            }

            //   ?      ??   
            if (packageCollected != null && packageCollected.equals("N")) {
                if (!_packageCollected) {
                    _packageCollected = true;
                    String packageFile = null;

                    try {
                        packageFile = PropertyUtil.getProperty(PeacockConstant.PACKAGE_FILE_KEY);
                    } catch (Exception e) {
                        // nothing to do.
                    } finally {
                        if (StringUtils.isEmpty(packageFile)) {
                            packageFile = "/peacock/agent/config/package.log";
                        }
                    }

                    file = new File(packageFile);

                    if (!file.exists()) {
                        new PackageGatherThread(ctx, packageFile).start();
                    }
                }
            }

            if (softwareInstalled != null && softwareInstalled.equals("N")) {
                if (!_softwareCollected) {
                    _softwareCollected = true;
                    new SoftwareGatherThread(ctx).start();
                }
            }

            Scheduler scheduler = (Scheduler) AppContext.getBean("quartzJobScheduler");

            if (!scheduler.isStarted()) {
                scheduler.start();
            }
        }
    }
}

From source file:com.docdoku.client.data.MainModel.java

public File getFile(Component pParent, DocumentIteration pDocument, BinaryResource pBin) throws Exception {
    DocumentMaster docM = pDocument.getDocumentMaster();
    File folder = null;/*w  ww  . ja va  2 s  .  c  om*/
    boolean readOnly;
    if (!docM.isCheckedOut() || !docM.getCheckOutUser().equals(getUser())
            || !docM.getLastIteration().equals(pDocument)) {
        folder = new File(Config.getCacheFolder(docM), pDocument.getIteration() + "");
        readOnly = true;
    } else {
        folder = Config.getCheckOutFolder(docM);
        readOnly = false;
    }

    File localFile = new File(folder, pBin.getName());

    if (!localFile.exists()) {
        folder.mkdirs();
        try {
            Map<String, Object> ctxt = ((BindingProvider) mFileService).getRequestContext();
            try {
                if (ctxt.containsKey(Config.HTTP_CLIENT_STREAMING_CHUNK_SIZE)) {
                    DataHandler dh = mFileService.downloadFromDocument(getWorkspace().getId(),
                            pDocument.getDocumentMasterId(), pDocument.getDocumentMasterVersion(),
                            pDocument.getIteration(), pBin.getName());
                    downloadFile(pParent, localFile, (int) pBin.getContentLength(), dh.getInputStream());
                } else {
                    //workaround mode
                    downloadFileWithServlet(pParent, localFile, getServletURL(pDocument, pBin.getName()));
                }
            } catch (Exception ex) {
                if (ex.getCause() instanceof InterruptedIOException) {
                    throw ex;
                }
                if (ctxt.containsKey(Config.HTTP_CLIENT_STREAMING_CHUNK_SIZE)) {
                    System.out.println("Disabling chunked mode");
                    ctxt.remove(Config.HTTP_CLIENT_STREAMING_CHUNK_SIZE);
                    downloadFileWithServlet(pParent, localFile, getServletURL(pDocument, pBin.getName()));
                } else {
                    //we were already not using the chunked mode
                    //there's not much to do...
                    throw ex;
                }

            }
        } catch (WebServiceException pWSEx) {
            Throwable t = pWSEx.getCause();
            if (t instanceof Exception) {
                throw (Exception) t;
            } else {
                throw pWSEx;
            }
        }

        if (readOnly) {
            localFile.setReadOnly();
            localFile.deleteOnExit();
        } else {
            Prefs.storeDocInfo(docM, localFile.getName(), localFile.lastModified());
        }
    }

    return localFile;
}

From source file:nl.toolforge.karma.core.vc.cvsimpl.CVSRunner.java

/**
 * Helper method that add a new event to a module's history. When the history does not
 * exist yet (in case of a new module) it is newly created. When the history does exist
 * the event is added to the history.//from w w w.  j  a va 2 s  .co m
 *
 * @param module                  The module involved.
 * @param eventType               The type of {@link ModuleHistoryEvent}.
 * @param version                 The version that the module is promoted to.
 * @param datetime                The timestamp.
 * @param author                  The authentication of the person who has triggered the event.
 * @param comment                 The (optional) comment the author has given.
 * @throws CVSException           Thrown in case something goes wrong with CVS
 */
private void addModuleHistoryEvent(Module module, String eventType, Version version, Date datetime,
        String author, String comment) throws CVSException, ModuleHistoryException {
    ModuleHistoryFactory factory = ModuleHistoryFactory.getInstance(module.getBaseDir());
    ModuleHistory history = factory.getModuleHistory(module);

    if (history != null) {
        ModuleHistoryEvent event = new ModuleHistoryEvent();

        event.setType(eventType);
        event.setVersion(version);
        event.setDatetime(datetime);
        event.setAuthor(author);
        event.setComment(comment);

        history.addEvent(event);

        File cvsEntriesFile = new File(module.getBaseDir(), "CVS" + File.separator + "Entries");
        File historyFile = history.getHistoryLocation();

        boolean isCvsEntriesFileReadOnly = !cvsEntriesFile.canWrite();
        boolean isHistoryFileReadOnly = !historyFile.canWrite();

        try {
            if (isCvsEntriesFileReadOnly) {
                MyFileUtils.makeWriteable(cvsEntriesFile, false);
            }

            if (historyFile.exists()) { //history already exists. commit changes.
                if (isHistoryFileReadOnly) {
                    MyFileUtils.makeWriteable(historyFile, false);
                }

                history.save();

                //development line is null, since the history.xml is always committed in the HEAD.
                commit(null, module, new File(module.getBaseDir(), ModuleHistory.MODULE_HISTORY_FILE_NAME),
                        "History updated by Karma");
            } else { //history did not exist yet. add to CVS and commit it.
                history.save();

                add(module, new String[] { historyFile.getName() }, null);
            }
        } catch (IOException ioe) {
            logger.error("Error when making history.xml readonly/writeable", ioe);
        } catch (InterruptedException ie) {
            logger.error("Error when making history.xml readonly/writeable", ie);
        } finally {
            if (isCvsEntriesFileReadOnly) {
                cvsEntriesFile.setReadOnly();
            }

            if (isHistoryFileReadOnly) {
                historyFile.setReadOnly();
            }
        }
    } else {
        //history wel null. EN NU?! todo
        throw new OutOfTheBlueException("If this happens something rrreally went wrong with the history");
    }
}

From source file:org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabaseTest.java

public void testSetPasswordFileWithReadOnlyFile() {

    File testFile = createPasswordFile(0, 0);

    testFile.setReadOnly();

    try {/*www .j  a  v a  2  s  .c o m*/
        _database.setPasswordFile(testFile.toString());
    } catch (FileNotFoundException fnfe) {
        assertTrue(fnfe.getMessage().startsWith("Cannot read password file "));
    } catch (IOException e) {
        fail("Password File was not created." + e.getMessage());
    }
}

From source file:org.apache.solr.handler.dataimport.TestNonWritablePersistFile.java

@Test
@SuppressWarnings("unchecked")
public void testNonWritablePersistFile() throws Exception {
    // See SOLR-2551
    String configDir = h.getCore().getResourceLoader().getConfigDir();
    String filePath = configDir;/* ww  w .  j  a v  a 2s . com*/
    if (configDir != null && !configDir.endsWith(File.separator))
        filePath += File.separator;
    filePath += "dataimport.properties";
    File f = new File(filePath);

    try {
        // execute the test only if we are able to set file to read only mode
        assumeTrue("No dataimport.properties file", f.exists() || f.createNewFile());
        assumeTrue("dataimport.properties can't be set read only", f.setReadOnly());
        assumeFalse("dataimport.properties is still writable even though "
                + "marked readonly - test running as superuser?", f.canWrite());

        ignoreException("Properties is not writable");

        @SuppressWarnings("rawtypes")
        List parentRow = new ArrayList();
        parentRow.add(createMap("id", "1"));
        MockDataSource.setIterator(FULLIMPORT_QUERY, parentRow.iterator());

        @SuppressWarnings("rawtypes")
        List childRow = new ArrayList();
        childRow.add(createMap("desc", "hello"));
        MockDataSource.setIterator("select * from y where y.A='1'", childRow.iterator());

        runFullImport(dataConfig_delta);
        assertQ(req("id:1"), "//*[@numFound='0']");
    } finally {
        f.setWritable(true);
    }
}

From source file:org.atomserver.core.PhysicalStorageTest.java

public void testStorageErrors() throws Exception {
    File root = new File(System.getProperty("java.io.tmpdir"), "storage");
    try {//from  w  w  w .ja  v  a  2 s  .  c o m
        FileBasedContentStorage storage = new FileBasedContentStorage(root);

        EntryDescriptor my_1234_en = new BaseEntryDescriptor("widgets", "mine", "1234", Locale.ENGLISH, 0);
        File file = new File(root, "widgets/mine/12/1234/en/1234.xml.r0");
        FileUtils.writeStringToFile(file, "JUNK", "UTF-8");
        file.setReadOnly();
        try {
            storage.putContent("STUFF", my_1234_en);
            assertTrue("we expected an exception!", false);
        } catch (Exception e) {
            // do nothing, we expected this.
        }

        assertEquals("JUNK", storage.getContent(my_1234_en));

        // replacing the file with a directory is the easiest way I can think of to programmatically
        // make the getContent throw an exception - but in real life this would probably happen because
        // of permissions issues.
        FileUtils.forceDelete(file);
        file.mkdirs();
        try {
            String entryData = storage.getContent(my_1234_en);
            assertTrue("we expected an exception, not " + entryData + "!", false);
        } catch (Exception e) {
            // do nothing, we expected this.
        }

        FileUtils.forceDelete(file);
        FileUtils.writeStringToFile(file, "JUNK", "UTF-8");

        assertEquals("JUNK", storage.getContent(my_1234_en));

    } finally {
        FileUtils.deleteDirectory(root);
    }
}