Example usage for java.io File setWritable

List of usage examples for java.io File setWritable

Introduction

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

Prototype

public boolean setWritable(boolean writable) 

Source Link

Document

A convenience method to set the owner's write permission for this abstract pathname.

Usage

From source file:gda.device.detector.pixium.PixiumDetector.java

/**
 * Helper methods to create data directory using GDA file number tracking system. It uses the current file number to
 * create a data directory for EPICS to save images to. Important: it is the caller's responsibility to ensure the
 * current file number is not already exist to avoid data over-written.
 *
 * @return directory/* www.j  ava  2  s.  com*/
 * @throws IOException
 */
public File createMainFileStructure() throws IOException {

    // set up the filename which will be the base directory for data to be saved to
    File path = new File(PathConstructor.createFromDefaultProperty());
    NumTracker nt = new NumTracker(LocalProperties.get(LocalProperties.GDA_BEAMLINE_NAME));
    String filenumber = Long.toString(nt.getCurrentFileNumber()); // scan already increments file number
    File scanFolder = new File(path, filenumber);
    if (!scanFolder.isDirectory()) {
        scanFolder.mkdir();
    }
    if (!scanFolder.canWrite()) {
        scanFolder.setWritable(true);
    }

    return scanFolder;
}

From source file:org.fuin.esmp.EventStoreDownloadMojo.java

private void applyFileMode(final File file, final FileMode fileMode) throws MojoExecutionException {

    if (OS.isFamilyUnix() || OS.isFamilyMac()) {
        final String smode = fileMode.toChmodStringFull();
        final CommandLine cmdLine = new CommandLine("chmod");
        cmdLine.addArgument(smode);//  w w  w .j a v  a 2s.co m
        cmdLine.addArgument(file.getAbsolutePath());
        final Executor executor = new DefaultExecutor();
        try {
            final int result = executor.execute(cmdLine);
            if (result != 0) {
                throw new MojoExecutionException("Error # " + result + " while trying to set mode \"" + smode
                        + "\" for file: " + file.getAbsolutePath());
            }
        } catch (final IOException ex) {
            throw new MojoExecutionException(
                    "Error while trying to set mode \"" + smode + "\" for file: " + file.getAbsolutePath(), ex);
        }
    } else {
        file.setReadable(fileMode.isUr() || fileMode.isGr() || fileMode.isOr());
        file.setWritable(fileMode.isUw() || fileMode.isGw() || fileMode.isOw());
        file.setExecutable(fileMode.isUx() || fileMode.isGx() || fileMode.isOx());
    }
}

From source file:com.thinkbiganalytics.feedmgr.rest.controller.FeedRestController.java

@POST
@Path("/{feedId}/upload-file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)/* www  . j ava2s.com*/
@ApiOperation("Uploads a file to be ingested by a feed.")
@ApiResponses({ @ApiResponse(code = 200, message = "The file is ready to be ingested."),
        @ApiResponse(code = 500, message = "The file could not be saved.", response = RestResponseStatus.class) })
public Response uploadFile(@PathParam("feedId") String feedId,
        @FormDataParam("file") InputStream fileInputStream,
        @FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception {

    FeedMetadata feed = getMetadataService().getFeedById(feedId, false);
    // Derive path and file
    List<NifiProperty> properties = feed.getProperties();
    String dropzone = null;
    String regexFileFilter = null;

    for (NifiProperty property : properties) {

        if (property.getProcessorType().equals("org.apache.nifi.processors.standard.GetFile")) {
            if (property.getKey().equals("File Filter")) {
                regexFileFilter = property.getValue();
            } else if (property.getKey().equals("Input Directory")) {
                dropzone = property.getValue();
            }
        }
    }
    if (StringUtils.isEmpty(regexFileFilter) || StringUtils.isEmpty(dropzone)) {
        throw new IOException("Unable to upload file with empty dropzone and file");
    }
    File tempTarget = File.createTempFile("kylo-upload", "");
    String fileName = "";
    try {
        Generex fileNameGenerator = new Generex(regexFileFilter);
        fileName = fileNameGenerator.random();

        // Cleanup oddball characters generated by generex
        fileName = fileName.replaceAll("[^A-Za-z0-9\\.\\_\\+\\%\\-\\|]+", "\\.");
        java.nio.file.Path dropZoneTarget = Paths.get(dropzone, fileName);
        File dropZoneFile = dropZoneTarget.toFile();
        if (dropZoneFile.exists()) {
            throw new IOException("File with the name [" + fileName + "] already exists in [" + dropzone + "]");
        }

        Files.copy(fileInputStream, tempTarget.toPath(), StandardCopyOption.REPLACE_EXISTING);
        Files.move(tempTarget.toPath(), dropZoneTarget);

        // Set read, write
        dropZoneFile.setReadable(true);
        dropZoneFile.setWritable(true);

    } catch (AccessDeniedException e) {
        String errTemplate = "Permission denied attempting to write file [%s] to [%s]. Check with system administrator to ensure this application has write permissions to folder";
        String err = String.format(errTemplate, fileName, dropzone);
        log.error(err);
        throw new InternalServerErrorException(err);

    } catch (Exception e) {
        String errTemplate = "Unexpected exception writing file [%s] to [%s].";
        String err = String.format(errTemplate, fileName, dropzone);
        log.error(err);
        throw new InternalServerErrorException(err);
    }
    return Response.ok("").build();
}

From source file:com.krawler.portal.tools.ServiceBuilder.java

public void createModuleDef(com.krawler.utils.json.base.JSONArray jsonData, String classname) {
    String result = "";
    try {/*from w w w  . j av a2 s .  c  o  m*/

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();

        Document doc = docBuilder.parse((new ClassPathResource("logic/moduleEx.xml").getFile()));
        //Document doc = docBuilder.newDocument();
        NodeList modules = doc.getElementsByTagName("modules");
        Node modulesNode = modules.item(0);
        Element module_ex = doc.getElementById(classname);
        if (module_ex != null) {
            modulesNode.removeChild(module_ex);
        }
        Element module = doc.createElement("module");
        Element property_list = doc.createElement("property-list");
        module.setAttribute("class", "com.krawler.esp.hibernate.impl." + classname);
        module.setAttribute("type", "pojo");
        module.setAttribute("id", classname);
        for (int cnt = 0; cnt < jsonData.length(); cnt++) {
            Element propertyNode = doc.createElement("property");
            JSONObject jsonObj = jsonData.optJSONObject(cnt);

            propertyNode.setAttribute("name", jsonObj.optString("varname"));
            propertyNode.setAttribute("type", jsonObj.optString("modulename").toLowerCase());
            property_list.appendChild(propertyNode);

        }

        module.appendChild(property_list);
        modulesNode.appendChild(module);
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://localhost/dtds/module.dtd");
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        // create string from xml tree
        File outputFile = (new ClassPathResource("logic/moduleEx.xml").getFile());
        outputFile.setWritable(true);
        // StringWriter sw = new StringWriter();
        StreamResult sresult = new StreamResult(outputFile);

        DOMSource source = new DOMSource(doc);
        trans.transform(source, sresult);
        //       result  = sw.toString();

    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
    }
}

From source file:com.krawler.portal.tools.ServiceBuilder.java

public void createModuleDef(ArrayList list, String classname) {
    String result = "";
    try {/*from   w  w w. java 2 s.  c o  m*/

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();

        Document doc = docBuilder.parse((new ClassPathResource("logic/moduleEx.xml").getFile()));
        //Document doc = docBuilder.newDocument();
        NodeList modules = doc.getElementsByTagName("modules");
        Node modulesNode = modules.item(0);
        Element module_ex = doc.getElementById(classname);
        if (module_ex != null) {
            modulesNode.removeChild(module_ex);
        }
        Element module = doc.createElement("module");
        Element property_list = doc.createElement("property-list");
        module.setAttribute("class", "com.krawler.esp.hibernate.impl." + classname);
        module.setAttribute("type", "pojo");
        module.setAttribute("id", classname);
        for (int cnt = 0; cnt < list.size(); cnt++) {
            Element propertyNode = doc.createElement("property");
            Hashtable mapObj = (Hashtable) list.get(cnt);

            propertyNode.setAttribute("name", mapObj.get("name").toString());
            propertyNode.setAttribute("type", mapObj.get("type").toString().toLowerCase());
            property_list.appendChild(propertyNode);

        }

        module.appendChild(property_list);
        modulesNode.appendChild(module);
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://192.168.0.4/dtds/module.dtd");
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        // create string from xml tree
        File outputFile = (new ClassPathResource("logic/moduleEx.xml").getFile());
        outputFile.setWritable(true);
        // StringWriter sw = new StringWriter();
        StreamResult sresult = new StreamResult(outputFile);

        DOMSource source = new DOMSource(doc);
        trans.transform(source, sresult);
        //       result  = sw.toString();

    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
    } finally {
        // System.out.println(result);
        // return result;
    }
}

From source file:com.krawler.portal.tools.ServiceBuilder.java

public void createBusinessProcessforCRUD(String classname, String companyid) {
    try {//from   w w w.ja  v a  2s .  c  o  m
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.parse(new ClassPathResource("logic/businesslogicEx.xml").getFile());
        //Document doc = docBuilder.newDocument();
        NodeList businessrules = doc.getElementsByTagName("businessrules");
        Node businessruleNode = businessrules.item(0);
        Element processEx = doc.getElementById(classname + "_addNew");

        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }

        processEx = doc.getElementById(classname + "_delete");

        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }
        processEx = doc.getElementById(classname + "_edit");
        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }

        Element process = createBasicProcessNode(doc, classname, "createNewRecord", "_addNew", "createNew");
        businessruleNode.appendChild(process);
        process = createBasicProcessNode(doc, classname, "deleteRecord", "_delete", "deleteRec");
        businessruleNode.appendChild(process);
        process = createBasicProcessNode(doc, classname, "editRecord", "_edit", "editRec");
        businessruleNode.appendChild(process);

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://192.168.0.4/dtds/businesslogicEx.dtd");
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        // create string from xml tree
        File outputFile = (new ClassPathResource("logic/businesslogicEx.xml").getFile());
        outputFile.setWritable(true);
        // StringWriter sw = new StringWriter();
        StreamResult sresult = new StreamResult(outputFile);

        DOMSource source = new DOMSource(doc);
        trans.transform(source, sresult);

    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
    }

}

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

@SuppressWarnings("unchecked")
@Override// w w w.  ja  va 2  s .c  om
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:se.sics.kompics.p2p.experiment.dsl.SimulationScenario.java

/**
 * Transform.//from ww w  . ja  v  a  2 s  .  c  o m
 * 
 * @param main
 *            the main
 * @param directory
 *            the directory
 */
public final void transform(Class<? extends ComponentDefinition> main, String directory) {
    Properties p = new Properties();

    File dir = null;
    File file = null;
    try {
        dir = new File(directory);
        dir.mkdirs();
        dir.setWritable(true);
        file = File.createTempFile("scenario", ".bin", dir);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(this);
        oos.flush();
        oos.close();
        System.setProperty("scenario", file.getAbsolutePath());
        p.setProperty("scenario", file.getAbsolutePath());
        p.store(new FileOutputStream(file.getAbsolutePath() + ".properties"), null);
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        Loader cl = AccessController.doPrivileged(new PrivilegedAction<Loader>() {
            @Override
            public Loader run() {
                return new Loader();
            }
        });
        cl.addTranslator(ClassPool.getDefault(), new TimeInterceptor(dir));
        Thread.currentThread().setContextClassLoader(cl);
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
        cl.run(main.getCanonicalName(), null);
    } catch (Throwable e) {
        throw new RuntimeException("Exception caught during simulation", e);
    }
}

From source file:org.computeforcancer.android.client.Monitor.java

/**
 * Copies given file from APK assets to internal storage.
 * @param file name of file as it appears in assets directory
 * @param override define override, if already present in internal storage
 * @param executable set executable flag of file in internal storage
 * @return Boolean success//  ww  w .j a  va  2s .com
 */
private Boolean installFile(String file, Boolean override, Boolean executable) {
    Boolean success = false;
    byte[] b = new byte[1024];
    int count;

    // If file is executable, cpu architecture has to be evaluated
    // and assets directory select accordingly
    String source = "";
    if (executable)
        source = getAssestsDirForCpuArchitecture() + file;
    else
        source = file;

    try {
        if (Logging.ERROR)
            Log.d(Logging.TAG, "installing: " + source);

        File target = new File(boincWorkingDir + file);

        // Check path and create it
        File installDir = new File(boincWorkingDir);
        if (!installDir.exists()) {
            installDir.mkdir();
            installDir.setWritable(true);
        }

        if (target.exists()) {
            if (override)
                target.delete();
            else {
                if (Logging.DEBUG)
                    Log.d(Logging.TAG, "skipped file, exists and ovverride is false");
                return true;
            }
        }

        // Copy file from the asset manager to clientPath
        InputStream asset = getApplicationContext().getAssets().open(source);
        OutputStream targetData = new FileOutputStream(target);
        while ((count = asset.read(b)) != -1) {
            targetData.write(b, 0, count);
        }
        asset.close();
        targetData.flush();
        targetData.close();

        success = true; //copy succeeded without exception

        // Set executable, if requested
        Boolean isExecutable = false;
        if (executable) {
            target.setExecutable(executable);
            isExecutable = target.canExecute();
            success = isExecutable; // return false, if not executable
        }

        if (Logging.ERROR)
            Log.d(Logging.TAG,
                    "install of " + source + " successfull. executable: " + executable + "/" + isExecutable);

    } catch (IOException e) {
        if (Logging.ERROR)
            Log.e(Logging.TAG, "IOException: " + e.getMessage());
        if (Logging.ERROR)
            Log.d(Logging.TAG, "install of " + source + " failed.");
    }

    return success;
}

From source file:org.kepler.ssh.LocalExec.java

/**
 * Copies src file to dst file. If the dst file does not exist, it is
 * created//ww  w. j a v  a2  s.  c  o  m
 */
private void copyFile(File src, File dst) throws IOException {
    // see if source and destination are the same
    if (src.equals(dst)) {
        // do not copy
        return;
    }

    //System.out.println("copying " + src + " to " + dst);

    FileChannel srcChannel = new FileInputStream(src).getChannel();
    FileChannel dstChannel = new FileOutputStream(dst).getChannel();
    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
    srcChannel.close();
    dstChannel.close();

    /* hacking for non-windows */
    // set the permission of the target file the same as the source file
    if (_commandArr[0] == "/bin/sh") {

        String osName = StringUtilities.getProperty("os.name");
        if (osName.startsWith("Mac OS X")) {

            // chmod --reference does not exist on mac, so do the best
            // we can using the java file api
            // WARNING: this relies on the umask to set the group, world
            // permissions.
            dst.setExecutable(src.canExecute());
            dst.setWritable(src.canWrite());

        } else {

            String cmd = "chmod --reference=" + src.getAbsolutePath() + " " + dst.getAbsolutePath();
            try {
                ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
                ByteArrayOutputStream streamErr = new ByteArrayOutputStream();
                executeCmd(cmd, streamOut, streamErr);
            } catch (ExecException e) {
                log.warn("Tried to set the target file permissions the same as "
                        + "the source but the command failed: " + cmd + "\n" + e);
            }
        }
    }
}