List of usage examples for org.apache.commons.io FileUtils writeLines
public static void writeLines(File file, Collection lines, String lineEnding) throws IOException
toString()
value of each item in a collection to the specified File
line by line. From source file:org.jahia.services.templates.SourceControlFactory.java
private void addIgnore(File path) throws IOException { File ignore = new File(path, ".gitignore"); List<String> lines; if (ignore.exists()) { lines = FileUtils.readLines(ignore, "UTF-8"); } else {//www . ja v a 2 s.co m lines = new ArrayList<>(); } for (String ignoredFile : ignoredFiles) { if (!lines.contains(ignoredFile)) { lines.add(ignoredFile); } } FileUtils.writeLines(ignore, "UTF-8", lines); }
From source file:org.jahia.utils.maven.plugin.jarscan.JarsToSkipListMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { if (src == null || !src.exists()) { getLog().info("Folder " + src + " does not exist. Skipping task."); return;//w w w.j av a2 s . c om } long start = System.currentTimeMillis(); Set<String> toSkip = new TreeSet<String>(); if (StringUtils.isNotEmpty(defaultJarsToSkip)) { @SuppressWarnings("unchecked") List<String> skipByDefault = Arrays.asList(StringUtils.split(defaultJarsToSkip, ", ")); toSkip.addAll(skipByDefault); } try { if (append && dest.isFile()) { toSkip.addAll(FileUtils.readLines(dest)); } } catch (IOException e) { getLog().error("Unable to read entries from existing file " + dest, e); } for (Artifact artifact : project.getArtifacts()) { if (artifact.getType().equals("jar") && (Artifact.SCOPE_COMPILE.equals(artifact.getScope()) || Artifact.SCOPE_RUNTIME.equals(artifact.getScope()))) { File file = artifact.getFile(); try { boolean hasTLDFiles = hasTLDFiles(file); if (getLog().isDebugEnabled()) { if (hasTLDFiles) { getLog().debug("Scanned dependency " + file + ". TLD files found."); } else { getLog().debug("Scanned dependency " + file + ". No TLD files found. Will be added to the skip list."); } } if (!hasTLDFiles) { toSkip.add(file.getName()); } } catch (IOException e) { getLog().error(e); } } } try { FileUtils.writeLines(dest, toSkip, "\n"); } catch (IOException e) { throw new MojoExecutionException("Unable to write results to the destination file " + dest, e); } getLog().info("Took " + (System.currentTimeMillis() - start) + " ms for scanning TLDs in JARs. Found " + toSkip.size() + " JARs without TLDs. The list is written into " + dest); }
From source file:org.jasig.maven.notice.CheckNoticeMojoTest.java
public void copyFileWithOppositeLineEnding(File src, File dst) throws IOException { final List<String> lines = FileUtils.readLines(src); if (IOUtils.LINE_SEPARATOR_UNIX.equals(IOUtils.LINE_SEPARATOR)) { FileUtils.writeLines(dst, lines, IOUtils.LINE_SEPARATOR_WINDOWS); } else {/*from w ww. j a v a 2 s . c o m*/ FileUtils.writeLines(dst, lines, IOUtils.LINE_SEPARATOR_UNIX); } }
From source file:org.openehr.am.template.PathMap.java
/** * Writes this path map to file/*from w ww . jav a 2 s . c om*/ * * @param filename * @throws IOException */ public void writeToFile(String filename) throws IOException { List<String> paths = new ArrayList<String>(); DateFormat df = DateFormat.getDateTimeInstance(); paths.add("# Generated path map on " + df.format(new Date())); int maxLen = 0; String maxLenKey = null; for (String key : keyPathMap.keySet()) { String path = keyPathMap.get(key); if (key.length() > maxLen) { maxLen = key.length(); maxLenKey = key; } paths.add(key + DELIMITER + path); } log.debug("max length of key: " + maxLen + ", key: " + maxLenKey); File pathMapFile = new File(filename); FileUtils.writeLines(pathMapFile, UTF8, paths); log.info("total " + (paths.size() - 1) + " line(s) of path written to file"); }
From source file:org.opoo.press.source.SourceManagerImpl.java
@Override public void saveSourceToFile(Source source) { File file = source.getSourceEntry().getFile(); File dir = file.getParentFile(); if (!dir.exists()) { dir.mkdirs();/*w w w . j av a 2 s .co m*/ } else { if (!dir.isDirectory()) { throw new RuntimeException("Can not save file, '" + dir + "' is not a valid directory."); } } List<String> lines = new ArrayList<String>(); lines.add(Source.TRIPLE_DASHED_LINE); //for(Map.Entry<String, Object> en: source.getMeta().entrySet()){ // //} String line = yaml.dumpAsMap(source.getMeta()); lines.add(line); lines.add(Source.TRIPLE_DASHED_LINE); lines.add(source.getContent()); try { FileUtils.writeLines(file, "UTF-8", lines); } catch (IOException e) { throw new RuntimeException("Write file exception", e); } }
From source file:org.patientview.radar.service.impl.UtilityManagerImpl.java
private void writeConsultantToFile(List<Consultant> consultants) { File file = new File(getFilePathAndName()); List<String> list = new ArrayList<String>(); for (Consultant consultant : consultants) { list.add(consultant.getId() + "," + consultant.getFullName() + "," + consultant.getCentre().getId() + " : " + consultant.getCentre().getUnitCode()); }/*from w ww . ja v a 2 s. c om*/ if (!list.isEmpty()) { try { FileUtils.writeLines(file, "UTF-8", list); } catch (IOException e) { LOGGER.error(e.getMessage()); LOGGER.debug(e.getMessage(), e); } } }
From source file:org.ramidore.logic.system.GuildBattleLogLogic.java
/** * ???.// ww w. j a v a2 s .c o m * * @param items */ public static void saveStatData(ObservableList<GvStatTable> items, File f) { List<String> lines = new ArrayList<>(); lines.add("name\tkill\tdeath\tpoint\tnote"); for (GvStatTable item : items) { List<String> itemList = new ArrayList<>(); itemList.add(item.getCharaName()); itemList.add(String.valueOf(item.getKillCount())); itemList.add(String.valueOf(item.getDeathCount())); itemList.add(String.valueOf(item.getPoint())); itemList.add(item.getNote()); String line = StringUtils.join(itemList, '\t'); lines.add(line); } try { FileUtils.writeLines(f, Const.ENCODING, lines); } catch (IOException e) { LOG.error("I/O error " + f.getAbsolutePath()); } }
From source file:org.silverpeas.core.io.file.ImageCache.java
/** * Puts an entry into the cache for the specified resized image of the specified original image. * @param originalImagePath the absolute path of the original image from which the resized image * was made./*from w ww . j a v a2 s . c o m*/ * @param resizedImagePath the absolute path of the resized image for which an entry will be * created into the cache. */ protected static void putImage(final String originalImagePath, final String resizedImagePath) { String entryName = hash(originalImagePath); File entry = new File(IMAGE_CACHE_TABLE, entryName); try { List<String> lines = new ArrayList<String>(); if (!entry.exists()) { lines.add(originalImagePath); } lines.add(resizedImagePath); FileUtils.writeLines(entry, lines, true); } catch (IOException ex) { SilverLogger.getLogger(ImageCache.class).error( "Cannot write the cache entry {0} with value {1}. Cause: {2}", new String[] { entry.getAbsolutePath(), resizedImagePath, ex.getMessage() }); } }
From source file:org.simplericity.jettyconsole.creator.DefaultCreator.java
private void writeOptions(List<String> options) { File optionsFile = new File(new File(workingDirectory, consoleDirectory), "options.txt"); try {//from w w w . ja v a 2 s . c o m FileUtils.writeLines(optionsFile, "utf-8", options); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.structr.rest.service.HttpService.java
@Override public void initialize(final Services services, final StructrConf additionalConfig) throws ClassNotFoundException, IllegalAccessException, InstantiationException { final StructrConf finalConfig = new StructrConf(); // Default configuration finalConfig.setProperty(APPLICATION_TITLE, "structr server"); finalConfig.setProperty(APPLICATION_HOST, "0.0.0.0"); finalConfig.setProperty(APPLICATION_HTTP_PORT, "8082"); finalConfig.setProperty(APPLICATION_HTTPS_ENABLED, "false"); finalConfig.setProperty(APPLICATION_HTTPS_PORT, "8083"); finalConfig.setProperty(ASYNC, "true"); finalConfig.setProperty(SERVLETS, "JsonRestServlet"); finalConfig.setProperty("JsonRestServlet.class", JsonRestServlet.class.getName()); finalConfig.setProperty("JsonRestServlet.path", "/structr/rest/*"); finalConfig.setProperty("JsonRestServlet.resourceprovider", DefaultResourceProvider.class.getName()); finalConfig.setProperty("JsonRestServlet.authenticator", SuperUserAuthenticator.class.getName()); finalConfig.setProperty("JsonRestServlet.user.class", "org.structr.dynamic.User"); finalConfig.setProperty("JsonRestServlet.user.autocreate", "false"); finalConfig.setProperty("JsonRestServlet.defaultview", PropertyView.Public); finalConfig.setProperty("JsonRestServlet.outputdepth", "3"); Services.mergeConfiguration(finalConfig, additionalConfig); final String mainClassName = (String) finalConfig.get(MAIN_CLASS); Class mainClass = null;/* w ww . j a va2 s . c o m*/ if (mainClassName != null) { logger.log(Level.INFO, "Running main class {0}", new Object[] { mainClassName }); try { mainClass = Class.forName(mainClassName); } catch (ClassNotFoundException ex) { logger.log(Level.WARNING, "Did not find class for main class from config " + mainClassName, ex); } } String sourceJarName = (mainClass != null ? mainClass : getClass()).getProtectionDomain().getCodeSource() .getLocation().toString(); final boolean isTest = Boolean.parseBoolean(finalConfig.getProperty(Services.TESTING, "false")); if (!isTest && StringUtils.stripEnd(sourceJarName, System.getProperty("file.separator")).endsWith("classes")) { String jarFile = System.getProperty("jarFile"); if (StringUtils.isEmpty(jarFile)) { throw new IllegalArgumentException(getClass().getName() + " was started in an environment where the classloader cannot determine the JAR file containing the main class.\n" + "Please specify the path to the JAR file in the parameter -DjarFile.\n" + "Example: -DjarFile=${project.build.directory}/${project.artifactId}-${project.version}.jar"); } sourceJarName = jarFile; } // load configuration from properties file applicationName = finalConfig.getProperty(APPLICATION_TITLE); host = finalConfig.getProperty(APPLICATION_HOST); basePath = finalConfig.getProperty(Services.BASE_PATH); httpPort = Services.parseInt(finalConfig.getProperty(APPLICATION_HTTP_PORT), 8082); maxIdleTime = Services.parseInt(System.getProperty("maxIdleTime"), 30000); requestHeaderSize = Services.parseInt(System.getProperty("requestHeaderSize"), 8192); async = Services.parseBoolean(finalConfig.getProperty(ASYNC), true); if (async) { logger.log(Level.INFO, "Running in asynchronous mode"); } // other properties final String keyStorePath = finalConfig.getProperty(APPLICATION_KEYSTORE_PATH); final String keyStorePassword = finalConfig.getProperty(APPLICATION_KEYSTORE_PASSWORD); final String contextPath = System.getProperty("contextPath", "/"); final String logPrefix = "structr"; final boolean enableRewriteFilter = true; // configurationFile.getProperty(Services. final boolean enableHttps = Services.parseBoolean(finalConfig.getProperty(APPLICATION_HTTPS_ENABLED), false); final boolean enableGzipCompression = true; // final boolean logRequests = false; // final int httpsPort = Services.parseInt(finalConfig.getProperty(APPLICATION_HTTPS_PORT), 8083); // get current base path basePath = System.getProperty("home", basePath); if (basePath.isEmpty()) { // use cwd and, if that fails, /tmp as a fallback basePath = System.getProperty("user.dir", "/tmp"); } // create base directory if it does not exist final File baseDir = new File(basePath); if (!baseDir.exists()) { baseDir.mkdirs(); } server = new Server(httpPort); final ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.addHandler(new DefaultHandler()); final ServletContextHandler servletContext = new ServletContextHandler(server, contextPath, true, true); final List<Connector> connectors = new LinkedList<>(); // create resource collection from base path & source JAR try { servletContext.setBaseResource(new ResourceCollection(Resource.newResource(basePath), JarResource.newJarResource(Resource.newResource(sourceJarName)))); } catch (Throwable t) { logger.log(Level.WARNING, "Base resource {0} not usable: {1}", new Object[] { basePath, t.getMessage() }); } // this is needed for the filters to work on the root context "/" servletContext.addServlet("org.eclipse.jetty.servlet.DefaultServlet", "/"); servletContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false"); try { // CMIS setup servletContext.addEventListener(new CmisRepositoryContextListener()); final ServletHolder cmisAtomHolder = servletContext.addServlet(CmisAtomPubServlet.class.getName(), "/structr/cmis/atom/*"); cmisAtomHolder.setInitParameter("callContextHandler", BasicAuthCallContextHandler.class.getName()); cmisAtomHolder.setInitParameter("cmisVersion", "1.1"); final ServletHolder cmisBrowserHolder = servletContext .addServlet(CmisBrowserBindingServlet.class.getName(), "/structr/cmis/browser/*"); cmisBrowserHolder.setInitParameter("callContextHandler", BasicAuthCallContextHandler.class.getName()); cmisBrowserHolder.setInitParameter("cmisVersion", "1.1"); } catch (Throwable t) { t.printStackTrace(); } hashSessionManager = new HashSessionManager(); try { hashSessionManager.setStoreDirectory(new File(baseDir + "/sessions")); } catch (IOException ex) { logger.log(Level.WARNING, "Could not set custom session manager with session store directory {0}/sessions", baseDir); } servletContext.getSessionHandler().setSessionManager(hashSessionManager); if (enableRewriteFilter) { final FilterHolder rewriteFilter = new FilterHolder(UrlRewriteFilter.class); rewriteFilter.setInitParameter("confPath", "urlrewrite.xml"); servletContext.addFilter(rewriteFilter, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC)); } if (enableGzipCompression) { final FilterHolder gzipFilter = async ? new FilterHolder(AsyncGzipFilter.class) : new FilterHolder(GzipFilter.class); gzipFilter.setInitParameter("mimeTypes", "text/html,text/plain,text/css,text/javascript,application/json"); gzipFilter.setInitParameter("bufferSize", "32768"); gzipFilter.setInitParameter("minGzipSize", "256"); gzipFilter.setInitParameter("deflateCompressionLevel", "9"); gzipFilter.setInitParameter("methods", "GET,POST,PUT,HEAD,DELETE"); servletContext.addFilter(gzipFilter, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC)); } contexts.addHandler(servletContext); // enable request logging if (logRequests || "true".equals(finalConfig.getProperty("log.requests", "false"))) { final String etcPath = basePath + "/etc"; final File etcDir = new File(etcPath); if (!etcDir.exists()) { etcDir.mkdir(); } final String logbackConfFilePath = basePath + "/etc/logback-access.xml"; final File logbackConfFile = new File(logbackConfFilePath); if (!logbackConfFile.exists()) { // synthesize a logback accees log config file List<String> config = new LinkedList<>(); config.add("<configuration>"); config.add(" <appender name=\"FILE\" class=\"ch.qos.logback.core.rolling.RollingFileAppender\">"); config.add(" <rollingPolicy class=\"ch.qos.logback.core.rolling.TimeBasedRollingPolicy\">"); config.add(" <fileNamePattern>logs/" + logPrefix + "-%d{yyyy_MM_dd}.request.log.zip</fileNamePattern>"); config.add(" </rollingPolicy>"); config.add(" <encoder>"); config.add(" <charset>UTF-8</charset>"); config.add(" <pattern>%h %l %u %t \"%r\" %s %b %n%fullRequest%n%n%fullResponse</pattern>"); config.add(" </encoder>"); config.add(" </appender>"); config.add(" <appender-ref ref=\"FILE\" />"); config.add("</configuration>"); try { logbackConfFile.createNewFile(); FileUtils.writeLines(logbackConfFile, "UTF-8", config); } catch (IOException ioex) { logger.log(Level.WARNING, "Unable to write logback configuration.", ioex); } } final FilterHolder loggingFilter = new FilterHolder(TeeFilter.class); servletContext.addFilter(loggingFilter, "/*", EnumSet.of(DispatcherType.REQUEST, async ? DispatcherType.ASYNC : DispatcherType.FORWARD)); loggingFilter.setInitParameter("includes", ""); final RequestLogHandler requestLogHandler = new RequestLogHandler(); final String logPath = basePath + "/logs"; final File logDir = new File(logPath); // Create logs directory if not existing if (!logDir.exists()) { logDir.mkdir(); } final RequestLogImpl requestLog = new RequestLogImpl(); requestLog.setName("REQUESTLOG"); requestLogHandler.setRequestLog(requestLog); final HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[] { contexts, requestLogHandler }); server.setHandler(handlers); } else { server.setHandler(contexts); } final List<ContextHandler> resourceHandler = collectResourceHandlers(finalConfig); for (ContextHandler contextHandler : resourceHandler) { contexts.addHandler(contextHandler); } final Map<String, ServletHolder> servlets = collectServlets(finalConfig); // add servlet elements int position = 1; for (Map.Entry<String, ServletHolder> servlet : servlets.entrySet()) { final ServletHolder servletHolder = servlet.getValue(); final String path = servlet.getKey(); servletHolder.setInitOrder(position++); logger.log(Level.INFO, "Adding servlet {0} for {1}", new Object[] { servletHolder, path }); servletContext.addServlet(servletHolder, path); } contexts.addHandler(servletContext); if (host != null && !host.isEmpty() && httpPort > -1) { httpConfig = new HttpConfiguration(); httpConfig.setSecureScheme("https"); httpConfig.setSecurePort(httpsPort); //httpConfig.setOutputBufferSize(8192); httpConfig.setRequestHeaderSize(requestHeaderSize); final ServerConnector httpConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); httpConnector.setHost(host); httpConnector.setPort(httpPort); connectors.add(httpConnector); } else { logger.log(Level.WARNING, "Unable to configure HTTP server port, please make sure that {0} and {1} are set correctly in structr.conf.", new Object[] { APPLICATION_HOST, APPLICATION_HTTP_PORT }); } if (enableHttps) { if (httpsPort > -1 && keyStorePath != null && !keyStorePath.isEmpty() && keyStorePassword != null) { httpsConfig = new HttpConfiguration(httpConfig); httpsConfig.addCustomizer(new SecureRequestCustomizer()); final SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath(keyStorePath); sslContextFactory.setKeyStorePassword(keyStorePassword); final ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(httpsConfig)); https.setPort(httpsPort); https.setIdleTimeout(500000); https.setHost(host); https.setPort(httpsPort); connectors.add(https); } else { logger.log(Level.WARNING, "Unable to configure SSL, please make sure that {0}, {1} and {2} are set correctly in structr.conf.", new Object[] { APPLICATION_HTTPS_PORT, APPLICATION_KEYSTORE_PATH, APPLICATION_KEYSTORE_PASSWORD }); } } if (!connectors.isEmpty()) { server.setConnectors(connectors.toArray(new Connector[0])); } else { logger.log(Level.SEVERE, "No connectors configured, aborting."); System.exit(0); } server.setStopTimeout(1000); server.setStopAtShutdown(true); }