List of usage examples for java.io File canRead
public boolean canRead()
From source file:org.sonarqube.shell.commands.ExportCommands.java
@VisibleForTesting Profile getProfile(String profile) { File path = new File(profile); Profile result = new Profile(); if (!(path.isFile() && path.canRead())) { consoleOutAndThrowsException(/*ww w.j a va 2 s. co m*/ String.format("Invalid path: '%s'. Please provide a valid path and try again.", path)); } try { Unmarshaller unmarshaller = context.getUnmarshaller(); result = unmarshaller.unmarshal(new StreamSource(path), Profile.class).getValue(); } catch (JAXBException e) { // do nothing because the profile will don't pass the validation } if (!result.isValid()) { consoleOutAndThrowsException(String.format( "Failed to parse the profile file: '%s'. Please provide a valid profile and try again.", path)); } consoleOut("Profile has been successfully loaded.\n" + result); return result; }
From source file:io.jenkins.blueocean.blueocean_git_pipeline.GitCloneReadSaveRequest.java
@Override byte[] read() throws IOException { try {//from w w w.j a v a2 s . co m GitClient git = cloneRepo(); try { // thank you test for how to use something... // https://github.com/jenkinsci/git-client-plugin/blob/master/src/test/java/org/jenkinsci/plugins/gitclient/GitClientTest.java#L1108 git.checkoutBranch(branch, "origin/" + branch); } catch (Exception e) { throw new RuntimeException("Branch not found: " + branch); } File f = new File(repositoryPath, filePath); if (f.canRead()) { return FileUtils.readFileToByteArray(f); } return null; } catch (InterruptedException ex) { throw new ServiceException.UnexpectedErrorException("Unable to read " + filePath, ex); } finally { cleanupRepo(); } }
From source file:gsn.wrappers.GPSGenerator.java
public boolean initialize() { AddressBean addressBean = getActiveAddressBean(); if (addressBean.getPredicateValue("rate") != null) { samplingRate = ParamParser.getInteger(addressBean.getPredicateValue("rate"), DEFAULT_SAMPLING_RATE); if (samplingRate <= 0) { logger.warn(/*from ww w . j a va 2 s . co m*/ "The specified >sampling-rate< parameter for the >MemoryMonitoringWrapper< should be a positive number.\nGSN uses the default rate (" + DEFAULT_SAMPLING_RATE + "ms )."); samplingRate = DEFAULT_SAMPLING_RATE; } } if (addressBean.getPredicateValue("picture") != null) { String picture = addressBean.getPredicateValue("picture"); File pictureF = new File(picture); if (!pictureF.isFile() || !pictureF.canRead()) { logger.warn("The GPSGenerator can't access the specified picture file. Initialization failed."); return false; } try { BufferedInputStream fis = new BufferedInputStream(new FileInputStream(pictureF)); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4 * 1024]; while (fis.available() > 0) outputStream.write(buffer, 0, fis.read(buffer)); fis.close(); this.picture = outputStream.toByteArray(); outputStream.close(); } catch (FileNotFoundException e) { logger.warn(e.getMessage(), e); return false; } catch (IOException e) { logger.warn(e.getMessage(), e); return false; } } else { logger.warn("The >picture< parameter is missing from the GPSGenerator wrapper."); return false; } ArrayList<DataField> output = new ArrayList<DataField>(); for (int i = 0; i < FIELD_NAMES.length; i++) output.add(new DataField(FIELD_NAMES[i], FIELD_TYPES_STRING[i], FIELD_DESCRIPTION[i])); outputStrcture = output.toArray(new DataField[] {}); return true; }
From source file:it.geosolutions.geobatch.settings.GBSettingsDAOXStreamImpl.java
public GBSettings find(String id) throws IOException { InputStream inStream = null;//from www.j a v a2s .com try { final File entityfile = new File(settingsDir, id + ".xml"); if (!entityfile.canRead()) { LOGGER.warn("Unreadable file " + entityfile); return null; } else if (entityfile.isDirectory()) { LOGGER.warn("File " + entityfile + " is a dir"); return null; } else { inStream = new FileInputStream(entityfile); XStream xstream = new XStream(); alias.setAliases(xstream); GBSettings obj = (GBSettings) xstream.fromXML(inStream); if (!id.equals(obj.getId())) { LOGGER.error("Mismatching id in settings (id:" + id + ")"); throw new RuntimeException("Mismatching id in settings (id:" + id + ")"); } if (LOGGER.isInfoEnabled()) { LOGGER.info("FOUND id:" + id + " obj:[" + obj + "]"); LOGGER.info(" at path " + entityfile + " -- absolute " + entityfile.getAbsolutePath()); } return obj; } } catch (Exception e) { throw new IOException("Unable to load settings with id:" + id + " (" + e.getMessage() + ")", e); } finally { IOUtils.closeQuietly(inStream); } }
From source file:nl.opengeogroep.filesetsync.client.plugin.SetFileXpathToHttpRequestHeaderPlugin.java
private void updateHeader(String header) { String file = null, xpathString = null, lastModified = null, lastValue = null; try {/* w w w . ja va 2 s.co m*/ Properties props = headers.get(header); if (props == null || !props.containsKey("file") || !props.containsKey("xpath")) { log.warn("Invalid configuration for header " + header + ", ignoring"); return; } file = props.getProperty("file"); xpathString = props.getProperty("xpath"); lastModified = props.getProperty("lastModified"); lastValue = props.getProperty("lastValue"); File f = new File(file); if (!f.exists() || !f.canRead()) { log.warn(String.format("Cannot read value for header \"%s\" from file \"%s\"", header, file)); return; } if (lastModified != null && lastModified.equals(f.lastModified() + "")) { log.trace("File for header value " + header + " was not modified, keeping value " + lastValue); return; } Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(f); XPath xpath = XPathFactory.newInstance().newXPath(); String value = xpath.evaluate(xpathString, doc); log.info(String.format("Value extracted from file \"%s\" using xpath \"%s\": %s", file, xpathString, value)); props.put("lastValue", value); props.put("lastModified", f.lastModified() + ""); } catch (Exception e) { log.error(String.format( "Error updating header %s, file=%s, xpathString=%s, lastModified=%s, lastValue=%s", header, file, xpathString, lastModified, lastValue), e); } }
From source file:edu.umn.msi.gx.mztosqlite.MzToSQLite.java
public final void parseOptions(String[] args) { Integer MAX_INPUTS = 100;/* w ww . j ava2 s . c o m*/ Parser parser = new BasicParser(); String dbOpt = "sqlite"; String inputFileOpt = "input"; String inputNameOpt = "name"; String inputIdOpt = "encoded_id"; String verboseOpt = "verbose"; String helpOpt = "help"; Options options = new Options(); options.addOption("s", dbOpt, true, "SQLite output file"); options.addOption("v", verboseOpt, false, "verbose"); options.addOption("h", helpOpt, false, "help"); options.addOption("i", inputFileOpt, verbose, "input file"); options.addOption("n", inputNameOpt, verbose, "name for input file"); options.addOption("e", inputIdOpt, verbose, "encoded id for input file"); options.addOption("f", inputIdOpt, verbose, "FASTA Search Database files"); options.getOption(inputFileOpt).setArgs(MAX_INPUTS); options.getOption(inputNameOpt).setArgs(MAX_INPUTS); options.getOption(inputIdOpt).setArgs(MAX_INPUTS); // create the parser try { // parse the command line arguments CommandLine cli = parser.parse(options, args); if (cli.hasOption(helpOpt)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar MzToSQLite.jar [options] [proteomics_data_file ...]", options); exit(0); } if (cli.hasOption(verboseOpt)) { verbose = true; } if (cli.hasOption(dbOpt)) { dbPath = cli.getOptionValue(dbOpt); mzSQLiteDB = new MzSQLiteDB(dbPath); try { mzSQLiteDB.createTables(); } catch (SqlJetException ex) { Logger.getLogger(MzToSQLite.class.getName()).log(Level.SEVERE, null, ex); } } List<String> argList = cli.getArgList(); if (argList != null) { for (String filePath : argList) { File inputFile = new File(filePath); if (inputFile.canRead()) { try { ProteomicsFormat format = ProteomicsFormat.getFormat(inputFile); switch (format) { case MZID: identFiles.put(filePath, format); break; case MZML: case MGF: case DTA: case MS2: case PKL: case MZXML: case XML_FILE: case MZDATA: case PRIDEXML: scanFiles.put(filePath, format); break; case FASTA: seqDbFiles.put(filePath, format); break; case PEPXML: case UNSUPPORTED: default: Logger.getLogger(MzToSQLite.class.getName()).log(Level.WARNING, "Unknown or unsupported format: {0}", filePath); break; } } catch (IOException ex) { Logger.getLogger(MzToSQLite.class.getName()).log(Level.SEVERE, null, ex); } } else { Logger.getLogger(MzToSQLite.class.getName()).log(Level.WARNING, "Unable to read {0}", filePath); } } } } catch (ParseException exp) { Logger.getLogger(MzToSQLite.class.getName()).log(Level.SEVERE, null, exp); } }
From source file:croche.maven.plugin.android.manifestv.CopyManifestMojo.java
/** * {@inheritDoc}//from w w w. j a v a2 s . co m * @see org.apache.maven.plugin.Mojo#execute() */ public void execute() throws MojoExecutionException, MojoFailureException { File sourceManifest = new File(this.manifestPath); if (!sourceManifest.canRead()) { throw new MojoFailureException("The manifest file: " + this.manifestPath + " set via the manifestPath configuration could not be read."); } File targetDir = new File(this.targetPath); if (!targetDir.canRead() && !targetDir.mkdirs()) { throw new MojoFailureException("The manifest targetPath: " + this.targetPath + " set via the targetPath configuration could not be read."); } File targetManifest = new File(targetDir, sourceManifest.getName()); OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(targetManifest, false)); LineIterator it = FileUtils.lineIterator(sourceManifest, this.encoding); Set<String> propNames = this.session.getExecutionProperties().stringPropertyNames(); Properties props = this.session.getExecutionProperties(); while (it.hasNext()) { String line = it.nextLine(); // substitute any properies if (line.indexOf("${") > 0) { for (String propName : propNames) { line = line.replace("${" + propName + "}", props.getProperty(propName)); if (line.indexOf("${") == -1) { break; } } } // special handling of the manifest version code String origVersionCode = "android:versionCode=\"" + this.replaceVersionCode + "\""; if (line.indexOf(origVersionCode) > -1) { String newVersionCode = this.session.getExecutionProperties() .getProperty("manifestVersionCode"); if (newVersionCode != null && newVersionCode.trim().length() > 0) { line = line.replace(origVersionCode, "android:versionCode=\"" + newVersionCode + "\""); } } // write line out to output file os.write(line.toString().getBytes(this.encoding)); os.write(IOUtils.LINE_SEPARATOR.getBytes(this.encoding)); } } catch (IOException ex) { throw new MojoFailureException( "Failed to iterate over the content of the manifest file: " + sourceManifest.getAbsolutePath(), ex); } finally { if (os != null) { try { os.flush(); } catch (IOException ex) { throw new MojoFailureException("The target manifest targetManifest: " + targetManifest.getAbsolutePath() + " could not written to due to an io error.", ex); } finally { IOUtils.closeQuietly(os); } } } }
From source file:ffx.potential.parsers.INTFileFilter.java
/** * <p>/*w w w . j a v a2 s .co m*/ * acceptDeep</p> * * @param parm a {@link java.io.File} object. * @return a boolean. */ public boolean acceptDeep(File parm) { try { if (parm == null || parm.isDirectory() || !parm.canRead()) { return false; } FileReader fr = new FileReader(parm); BufferedReader br = new BufferedReader(fr); if (!br.ready()) { // Empty File? return false; } // If the first token is not an integer this file is not // an Internal Coordinates File. String rawdata = br.readLine(); String header[] = rawdata.trim().split(" +"); if (header == null || header.length == 0) { return false; } try { Integer.parseInt(header[0]); } catch (Exception e) { return false; } // If the the first Atom line does not begin with an integer and // contain // three tokens, it is not an internal coordinate file. String firstAtom = br.readLine(); if (firstAtom == null) { return false; } br.close(); fr.close(); String data[] = firstAtom.trim().split(" +"); if (data == null || data.length != 3) { return false; } try { Integer.parseInt(data[0]); } catch (Exception e) { return false; } return true; } catch (Exception e) { return true; } }
From source file:hu.tvdr.serialport.serialport.java
public void SerialPortCall(File device, int baudrate, int flags) throws SecurityException, IOException { /* Check access permission */ if (!device.canRead() || !device.canWrite()) { try {/*w ww. j a v a2s . c o m*/ /* Missing read/write permission, trying to chmod the file */ Process su; su = Runtime.getRuntime().exec("/system/bin/su"); String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n"; su.getOutputStream().write(cmd.getBytes()); if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) { throw new SecurityException(); } } catch (Exception e) { e.printStackTrace(); throw new SecurityException(); } } mFd = open(device.getAbsolutePath(), baudrate, flags); if (mFd == null) { Log.e(TAG, "native open returns null"); throw new IOException(); } mFileInputStream = new FileInputStream(mFd); mFileOutputStream = new FileOutputStream(mFd); }
From source file:luceneprueba.Index.java
public void create() { try {/* www . j a v a 2 s. c o m*/ // Storing index in disk IndexWriterConfig config = new IndexWriterConfig(analyzer); try (IndexWriter iwriter = new IndexWriter(directory, config)) { Document doc; File dir = new File("files/input"); File[] files = dir.listFiles(); if (files == null) { //System.out.println("No existe la carpeta \'input\' dentro de la carpeta files."); return; } if (files.length == 0) { //System.out.println("No hay ningun archivo en la carpeta \'input\' para ser indexado"); return; } BufferedReader br; String fileContent; JSONArray jsonArray; JSONParser jsonParser = new JSONParser(); for (File file : files) { if (file.isFile() && file.canRead() && file.getName().endsWith(".txt")) { //System.out.println("Indexando el archivo: "+file.getName()); br = new BufferedReader(new FileReader(file)); fileContent = br.readLine(); jsonArray = (JSONArray) jsonParser.parse(fileContent); Iterator i = jsonArray.iterator(); while (i.hasNext()) { JSONObject json = (JSONObject) i.next(); doc = new Document(); doc.add(new TextField("movieId", file.getName().split(".txt")[0], Field.Store.YES)); doc.add(new TextField("path", file.toString(), Field.Store.YES)); doc.add(new TextField("title", (String) json.get("Title"), Field.Store.YES)); doc.add(new TextField("score", (String) json.get("Score"), Field.Store.YES)); doc.add(new TextField("review", (String) json.get("Review"), Field.Store.YES)); doc.add(new TextField("date", (String) json.get("Date"), Field.Store.YES)); doc.add(new TextField("genre", (String) json.get("Genre"), Field.Store.YES)); doc.add(new TextField("score", (String) json.get("Score"), Field.Store.YES)); iwriter.addDocument(doc); } br.close(); } } iwriter.close(); } } catch (IOException | ParseException e) { e.printStackTrace(); } }