List of usage examples for java.io File canRead
public boolean canRead()
From source file:edu.uiuc.ncsa.myproxy.MyProxyLogon.java
private static String getDir(String path) { if (path == null) return null; File f = new File(path); if (f.isDirectory() && f.canRead()) { return f.getAbsolutePath(); }/* www . jav a 2 s. co m*/ return null; }
From source file:com.floragunn.searchguard.util.SecurityUtil.java
public static boolean setSystemPropertyToAbsoluteFilePathFromClassPath(final String property, final String fileNameFromClasspath) { if (System.getProperty(property) == null) { File jaasConfigFile = null; final URL jaasConfigURL = SecurityUtil.class.getClassLoader().getResource(fileNameFromClasspath); if (jaasConfigURL != null) { try { jaasConfigFile = new File(URLDecoder.decode(jaasConfigURL.getFile(), "UTF-8")); } catch (final UnsupportedEncodingException e) { return false; }/*from w w w.j a v a 2 s . c o m*/ if (jaasConfigFile.exists() && jaasConfigFile.canRead()) { System.setProperty(property, jaasConfigFile.getAbsolutePath()); log.debug("Load " + fileNameFromClasspath + " from {} ", jaasConfigFile.getAbsolutePath()); return true; } else { log.error("Cannot read from {}, maybe the file does not exists? ", jaasConfigFile.getAbsolutePath()); } } else { log.error("Failed to load " + fileNameFromClasspath); } } else { log.warn("Property " + property + " already set to " + System.getProperty(property)); } return false; }
From source file:com.meltmedia.cadmium.servlets.guice.CadmiumListener.java
public static File sharedContextRoot(Properties configProperties, ServletContext context, Logger log) { File sharedContentRoot = null; if (configProperties.containsKey(BASE_PATH_ENV)) { sharedContentRoot = new File(configProperties.getProperty(BASE_PATH_ENV)); if (!sharedContentRoot.exists() || !sharedContentRoot.canRead() || !sharedContentRoot.canWrite()) { if (!sharedContentRoot.mkdirs()) { sharedContentRoot = null; }//from w ww . ja va 2 s . c om } } if (sharedContentRoot == null) { log.warn("Could not access cadmium content root. Using the tempdir."); sharedContentRoot = (File) context.getAttribute("javax.servlet.context.tempdir"); configProperties.setProperty(BASE_PATH_ENV, sharedContentRoot.getAbsoluteFile().getAbsolutePath()); } return sharedContentRoot; }
From source file:net.pms.logging.LoggingConfigFileLoader.java
/** * Loads the (optional) Logback configuration file. * * <p>/*w w w.j ava 2 s . c o m*/ * It loads the file defined in the {@code project.logback} property * (use {@code [PROFILE_DIR]} to specify profile folder) and (re-)initializes Logback with this file. * </p> * * <p> * If failed (file not found or unreadable) it tries to load {@code logback.xml} from the current directory. * </p> * * <p> * If running headless, then the alternative config file defined in {@code project.logback.headless} is tried. * </p> * * <p> * If no config file worked, then nothing is loaded and * Logback will use the {@code logback.xml} file on the classpath as a default. If * this doesn't exist then a basic console appender is used as fallback. * </p> * * <strong>Note:</strong> Any error messages generated while parsing the * config file are dumped only to {@code stdout}. */ public static void load() { // Note: Do not use any logging method in this method! // Any status output needs to go to the console. File logFile = null; if (PMS.isHeadless()) { final String logFilePath = replace( PropertiesUtil.getProjectProperties().get("project.logback.headless"), "[PROFILE_DIR]", configuration.getProfileDirectory()); if (isNotBlank(logFilePath)) { logFile = new File(logFilePath); } } else { final String logFilePath = replace(PropertiesUtil.getProjectProperties().get("project.logback"), "[PROFILE_DIR]", configuration.getProfileDirectory()); if (isNotBlank(logFilePath)) { logFile = new File(logFilePath); } } if (logFile == null || !logFile.canRead()) { // Now try configs from the app folder. if (PMS.isHeadless()) { logFile = new File("logback.headless.xml"); } else { logFile = new File("logback.xml"); } } if (!logFile.canRead()) { // No problem, the internal logback.xml is used. return; } // Now get logback to actually use the config file ILoggerFactory ilf = LoggerFactory.getILoggerFactory(); if (!(ilf instanceof LoggerContext)) { // Not using LogBack. // Can't configure the logger, so just exit return; } LoggerContext lc = (LoggerContext) ilf; try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); // the context was probably already configured by // default configuration rules lc.reset(); configurator.doConfigure(logFile); // Save the filepath after loading the file filepath = logFile.getAbsolutePath(); } catch (JoranException je) { // StatusPrinter will handle this je.printStackTrace(); } for (Logger logger : lc.getLoggerList()) { Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders(); while (it.hasNext()) { Appender<ILoggingEvent> ap = it.next(); if (ap instanceof FileAppender) { FileAppender<ILoggingEvent> fa = (FileAppender<ILoggingEvent>) ap; logFilePaths.put(fa.getName(), fa.getFile()); } } } StatusPrinter.printInCaseOfErrorsOrWarnings(lc); }
From source file:cz.cas.lib.proarc.common.config.AppConfiguration.java
/** * checks file/folder parameters/*from w w w . java 2 s . com*/ * @return {@code true} iff {@code f} exists */ private static boolean checkFile(File f, boolean mustExist, Boolean expectDirectory, Boolean expectCanRead, Boolean expextCanWrite) throws IOException { if (f.exists()) { if (expectDirectory != null) { if (expectDirectory && !f.isDirectory()) { throw new IOException(String.format("Not a folder: '%s'!", f)); } else if (!expectDirectory && f.isDirectory()) { throw new IOException(String.format("Not a file: '%s'!", f)); } } if (expectCanRead != null) { if (expectCanRead != f.canRead()) { throw new IOException( String.format("Invalid read permission (=%s) for: '%s'!", !expectCanRead, f)); } } if (expextCanWrite != null) { if (expextCanWrite != f.canWrite()) { throw new IOException( String.format("Invalid write permission (=%s) for: '%s'!", !expextCanWrite, f)); } } return true; } else if (mustExist) { if (expectDirectory != null && expectDirectory) { throw new FileNotFoundException(String.format("Folder '%s' not founf!", f)); } else { throw new FileNotFoundException(String.format("File '%s' not founf!", f)); } } return false; }
From source file:MailHandlerDemo.java
/** * Used debug problems with the logging.properties. The system property * java.security.debug=access,stack can be used to trace access to the * LogManager reset.// w ww . j a va2 s. co m * * @param prefix a string to prefix the output. * @param err any PrintStream or null for System.out. */ @SuppressWarnings("UseOfSystemOutOrSystemErr") private static void checkConfig(String prefix, PrintStream err) { if (prefix == null || prefix.trim().length() == 0) { prefix = "DEBUG"; } if (err == null) { err = System.out; } try { err.println(prefix + ": java.version=" + System.getProperty("java.version")); err.println(prefix + ": LOGGER=" + LOGGER.getLevel()); err.println(prefix + ": JVM id " + ManagementFactory.getRuntimeMXBean().getName()); err.println(prefix + ": java.security.debug=" + System.getProperty("java.security.debug")); SecurityManager sm = System.getSecurityManager(); if (sm != null) { err.println(prefix + ": SecurityManager.class=" + sm.getClass().getName()); err.println(prefix + ": SecurityManager classLoader=" + toString(sm.getClass().getClassLoader())); err.println(prefix + ": SecurityManager.toString=" + sm); } else { err.println(prefix + ": SecurityManager.class=null"); err.println(prefix + ": SecurityManager.toString=null"); err.println(prefix + ": SecurityManager classLoader=null"); } String policy = System.getProperty("java.security.policy"); if (policy != null) { File f = new File(policy); err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath()); err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath()); err.println(prefix + ": length=" + f.length()); err.println(prefix + ": canRead=" + f.canRead()); err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified())); } LogManager manager = LogManager.getLogManager(); String key = "java.util.logging.config.file"; String cfg = System.getProperty(key); if (cfg != null) { err.println(prefix + ": " + cfg); File f = new File(cfg); err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath()); err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath()); err.println(prefix + ": length=" + f.length()); err.println(prefix + ": canRead=" + f.canRead()); err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified())); } else { err.println(prefix + ": " + key + " is not set as a system property."); } err.println(prefix + ": LogManager.class=" + manager.getClass().getName()); err.println(prefix + ": LogManager classLoader=" + toString(manager.getClass().getClassLoader())); err.println(prefix + ": LogManager.toString=" + manager); err.println(prefix + ": MailHandler classLoader=" + toString(MailHandler.class.getClassLoader())); err.println( prefix + ": Context ClassLoader=" + toString(Thread.currentThread().getContextClassLoader())); err.println(prefix + ": Session ClassLoader=" + toString(Session.class.getClassLoader())); err.println(prefix + ": DataHandler ClassLoader=" + toString(DataHandler.class.getClassLoader())); final String p = MailHandler.class.getName(); key = p.concat(".mail.to"); String to = manager.getProperty(key); err.println(prefix + ": TO=" + to); if (to != null) { err.println(prefix + ": TO=" + Arrays.toString(InternetAddress.parse(to, true))); } key = p.concat(".mail.from"); String from = manager.getProperty(key); if (from == null || from.length() == 0) { Session session = Session.getInstance(new Properties()); InternetAddress local = InternetAddress.getLocalAddress(session); err.println(prefix + ": FROM=" + local); } else { err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, false))); err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, true))); } synchronized (manager) { final Enumeration<String> e = manager.getLoggerNames(); while (e.hasMoreElements()) { final Logger l = manager.getLogger(e.nextElement()); if (l != null) { final Handler[] handlers = l.getHandlers(); if (handlers.length > 0) { err.println(prefix + ": " + l.getClass().getName() + ", " + l.getName()); for (Handler h : handlers) { err.println(prefix + ":\t" + toString(prefix, err, h)); } } } } } } catch (Throwable error) { err.print(prefix + ": "); error.printStackTrace(err); } err.flush(); }
From source file:biz.bokhorst.xprivacy.Util.java
public static String importProLicense(File licenseFile) { // Get imported license file name String importedLicense = getUserDataDirectory(Process.myUid()) + File.separator + LICENSE_FILE_NAME; File out = new File(importedLicense); // Check if license file exists if (licenseFile.exists() && licenseFile.canRead()) { try {/*from w ww . j a v a 2 s. c om*/ // Import license file Util.log(null, Log.WARN, "Licensing: importing " + out.getAbsolutePath()); InputStream is = null; is = new FileInputStream(licenseFile.getAbsolutePath()); try { OutputStream os = null; try { os = new FileOutputStream(out.getAbsolutePath()); byte[] buffer = new byte[1024]; int read; while ((read = is.read(buffer)) != -1) os.write(buffer, 0, read); os.flush(); } finally { if (os != null) os.close(); } } finally { if (is != null) is.close(); } // Protect imported license file setPermissions(out.getAbsolutePath(), 0700, Process.myUid(), Process.myUid()); // Remove original license file licenseFile.delete(); } catch (FileNotFoundException ignored) { } catch (Throwable ex) { Util.bug(null, ex); } } return (out.exists() && out.canRead() ? importedLicense : null); }
From source file:com.openkm.util.impexp.RepositoryImporter.java
/** * Import documents from filesystem into document repository (recursive). *//*from w ww . j a va 2 s.co m*/ private static ImpExpStats importDocumentsHelper(String token, File fs, String fldPath, boolean metadata, boolean history, boolean uuid, Writer out, InfoDecorator deco) throws FileNotFoundException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException, ExtensionException, AutomationException { log.debug("importDocumentsHelper({}, {}, {}, {}, {}, {}, {}, {})", new Object[] { token, fs, fldPath, metadata, history, uuid, out, deco }); long begin = System.currentTimeMillis(); File[] files = fs.listFiles(new RepositoryImporter.NoVersionFilenameFilter()); ImpExpStats stats = new ImpExpStats(); FolderModule fm = ModuleManager.getFolderModule(); MetadataAdapter ma = MetadataAdapter.getInstance(token); ma.setRestoreUuid(uuid); Gson gson = new Gson(); for (int i = 0; i < files.length; i++) { String fileName = files[i].getName(); if (!fileName.endsWith(Config.EXPORT_METADATA_EXT)) { if (files[i].isDirectory()) { Folder fld = new Folder(); boolean api = false; int importedFolder = 0; log.info("Directory: {}", files[i]); try { if (metadata) { // Read serialized folder metadata File jsFile = new File(files[i].getPath() + Config.EXPORT_METADATA_EXT); log.info("Folder Metadata: {}", jsFile.getPath()); if (jsFile.exists() && jsFile.canRead()) { FileReader fr = new FileReader(jsFile); FolderMetadata fmd = gson.fromJson(fr, FolderMetadata.class); fr.close(); // Apply metadata fld.setPath(fldPath + "/" + fileName); fmd.setPath(fld.getPath()); ma.importWithMetadata(fmd); if (out != null) { out.write(deco.print(files[i].getPath(), files[i].length(), null)); out.flush(); } } else { log.warn("Unable to read metadata file: {}", jsFile.getPath()); api = true; } } else { api = true; } if (api) { fld.setPath(fldPath + "/" + fileName); fm.create(token, fld); FileLogger.info(BASE_NAME, "Created folder ''{0}''", fld.getPath()); if (out != null) { out.write(deco.print(files[i].getPath(), files[i].length(), null)); out.flush(); } } importedFolder = 1; } catch (ItemExistsException e) { log.warn("ItemExistsException: {}", e.getMessage()); if (out != null) { out.write(deco.print(files[i].getPath(), files[i].length(), "ItemExists")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", fld.getPath()); } catch (JsonParseException e) { log.warn("JsonParseException: {}", e.getMessage()); if (out != null) { out.write(deco.print(files[i].getPath(), files[i].length(), "Json")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", fld.getPath()); } ImpExpStats tmp = importDocumentsHelper(token, files[i], fld.getPath(), metadata, history, uuid, out, deco); // Stats stats.setOk(stats.isOk() && tmp.isOk()); stats.setSize(stats.getSize() + tmp.getSize()); stats.setMails(stats.getMails() + tmp.getMails()); stats.setDocuments(stats.getDocuments() + tmp.getDocuments()); stats.setFolders(stats.getFolders() + tmp.getFolders() + importedFolder); } else { log.info("File: {}", files[i]); if (fileName.endsWith(".eml") || fileName.endsWith(".msg")) { log.info("Mail: {}", files[i]); ImpExpStats tmp = importMail(token, fldPath, fileName, files[i], metadata, out, deco); // Stats stats.setOk(stats.isOk() && tmp.isOk()); stats.setSize(stats.getSize() + tmp.getSize()); stats.setMails(stats.getMails() + tmp.getMails()); } else { log.info("Document: {}", files[i]); ImpExpStats tmp = importDocument(token, fs, fldPath, fileName, files[i], metadata, history, out, deco); // Stats stats.setOk(stats.isOk() && tmp.isOk()); stats.setSize(stats.getSize() + tmp.getSize()); stats.setDocuments(stats.getDocuments() + tmp.getDocuments()); } } } } log.trace("importDocumentsHelper.Time: {}", System.currentTimeMillis() - begin); log.debug("importDocumentsHelper: {}", stats); return stats; }
From source file:com.ikon.util.impexp.RepositoryImporter.java
/** * Import mail./*from w ww .j a v a 2s.c om*/ */ private static ImpExpStats importMail(String token, File fs, String fldPath, String fileName, File fDoc, String metadata, Writer out, InfoDecorator deco) throws IOException, PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException { FileInputStream fisContent = new FileInputStream(fDoc); MetadataAdapter ma = MetadataAdapter.getInstance(token); MailModule mm = ModuleManager.getMailModule(); Properties props = System.getProperties(); props.put("mail.host", "smtp.dummydomain.com"); props.put("mail.transport.protocol", "smtp"); ImpExpStats stats = new ImpExpStats(); int size = fisContent.available(); Mail mail = new Mail(); Gson gson = new Gson(); boolean api = false; try { // Metadata if (metadata.equals("JSON")) { // Read serialized document metadata File jsFile = new File(fDoc.getPath() + Config.EXPORT_METADATA_EXT); log.info("Document Metadata File: {}", jsFile.getPath()); if (jsFile.exists() && jsFile.canRead()) { FileReader fr = new FileReader(jsFile); MailMetadata mmd = gson.fromJson(fr, MailMetadata.class); mail.setPath(fldPath + "/" + fileName); mmd.setPath(mail.getPath()); IOUtils.closeQuietly(fr); log.info("Mail Metadata: {}", mmd); // Apply metadata ma.importWithMetadata(mmd); // Add attachments Session mailSession = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(mailSession, fisContent); mail = MailUtils.messageToMail(msg); mail.setPath(fldPath + "/" + mmd.getName()); MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser()); FileLogger.info(BASE_NAME, "Created document ''{0}''", mail.getPath()); log.info("Created document '{}'", mail.getPath()); } else { log.warn("Unable to read metadata file: {}", jsFile.getPath()); api = true; } } else { api = true; } if (api) { Session mailSession = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(mailSession, fisContent); mail = MailUtils.messageToMail(msg); mail.setPath(fldPath + "/" + fileName); mm.create(token, mail); MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser()); FileLogger.info(BASE_NAME, "Created mail ''{0}''", mail.getPath()); log.info("Created mail ''{}''", mail.getPath()); } if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), null)); out.flush(); } // Stats stats.setSize(stats.getSize() + size); stats.setMails(stats.getMails() + 1); } catch (UnsupportedMimeTypeException e) { log.warn("UnsupportedMimeTypeException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "UnsupportedMimeType")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "UnsupportedMimeTypeException ''{0}''", mail.getPath()); } catch (FileSizeExceededException e) { log.warn("FileSizeExceededException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "FileSizeExceeded")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "FileSizeExceededException ''{0}''", mail.getPath()); } catch (UserQuotaExceededException e) { log.warn("UserQuotaExceededException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "UserQuotaExceeded")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "UserQuotaExceededException ''{0}''", mail.getPath()); } catch (VirusDetectedException e) { log.warn("VirusWarningException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "VirusWarningException")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "VirusWarningException ''{0}''", mail.getPath()); } catch (ItemExistsException e) { log.warn("ItemExistsException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "ItemExists")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", mail.getPath()); } catch (JsonParseException e) { log.warn("JsonParseException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", mail.getPath()); } catch (MessagingException e) { log.warn("MessagingException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "MessagingException ''{0}''", mail.getPath()); } finally { IOUtils.closeQuietly(fisContent); } return stats; }
From source file:com.piaoyou.util.FileUtil.java
public static void copyFile(String srcFilename, String destFilename, boolean overwrite) throws IOException { File srcFile = new File(srcFilename); if (!srcFile.exists()) { throw new FileNotFoundException("Cannot find the source file: " + srcFile.getAbsolutePath()); }//w w w . ja v a 2 s .c o m if (!srcFile.canRead()) { throw new IOException("Cannot read the source file: " + srcFile.getAbsolutePath()); } File destFile = new File(destFilename); if (overwrite == false) { if (destFile.exists()) { return; } } else { if (destFile.exists()) { if (!destFile.canWrite()) { throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath()); } } else { if (!destFile.createNewFile()) { throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath()); } } } BufferedInputStream inputStream = null; BufferedOutputStream outputStream = null; byte[] block = new byte[1024]; try { inputStream = new BufferedInputStream(new FileInputStream(srcFile)); outputStream = new BufferedOutputStream(new FileOutputStream(destFile)); while (true) { int readLength = inputStream.read(block); if (readLength == -1) break;// end of file outputStream.write(block, 0, readLength); } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { log.error("Cannot close stream", ex); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { log.error("Cannot close stream", ex); } } } }