Performs the replacement in content.<p>

@param file the file object
@param contents the byte content

@return the new content if a replacement has been performed

@throws Exception if something goes wrong
325137
private byte[] replaceInContent(CmsFile file, byte[] contents) throws Exception {

        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_settings.getLocale())) {
            Locale contentLocale = CmsLocaleManager.getMainLocale(getCms(), file);
            if (!contentLocale.toString().equalsIgnoreCase(m_settings.getLocale())) {
                // content does not match the requested locale, skip it
                getReport().println(
                    Messages.get().container(Messages.RPT_SOURCESEARCH_NOT_MATCHED_0),
                    I_CmsReport.FORMAT_NOTE);
                return null;
            }
        }

        String encoding = CmsLocaleManager.getResourceEncoding(getCms(), file);
        String content = new String(contents, encoding);

        if (CmsSourceSearchForm.REGEX_ALL.equals(m_settings.getSearchpattern()) & !m_replace) {
            m_matchedResources.add(file);
            getReport().print(Messages.get().container(Messages.RPT_SOURCESEARCH_MATCHED_0), I_CmsReport.FORMAT_OK);
            return null;
        }

        Matcher matcher = Pattern.compile(m_settings.getSearchpattern()).matcher(content);

        if (matcher.find()) {
            // search pattern did match here, so take this file in the list with matches resources
            m_matchedResources.add(file);
            getReport().print(Messages.get().container(Messages.RPT_SOURCESEARCH_MATCHED_0), I_CmsReport.FORMAT_OK);
            if (m_replace) {
                if (m_settings.getType().equals(SearchType.renameContainer)) {

                    return renameNestedContainers(
                        file,
                        m_settings.getElementResource(),
                        m_settings.getReplacepattern().split(";")[0],
                        m_settings.getReplacepattern().split(";")[1]);
                }
                return matcher.replaceAll(m_settings.getReplacepattern()).getBytes(encoding);
            }
        } else {
            // search pattern did not match
            getReport().print(
                Messages.get().container(Messages.RPT_SOURCESEARCH_NOT_MATCHED_0),
                I_CmsReport.FORMAT_NOTE);
        }
        return null;
    }
288696
public void setContent(final WComponent content) {
		WComponent oldContent = getContent();

		if (oldContent != null) {
			remove(oldContent);
		}

		if (content != null) {
			add(content);
		}
	}
849637
public static void replaceFile(File src, File target) throws IOException {
    /* renameTo() has two limitations on Windows platform.
     * src.renameTo(target) fails if
     * 1) If target already exists OR
     * 2) If target is already open for reading/writing.
     */
    if (!src.renameTo(target)) {
      int retries = 5;
      while (target.exists() && !target.delete() && retries-- >= 0) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          throw new IOException("replaceFile interrupted.");
        }
      }
      if (!src.renameTo(target)) {
        throw new IOException("Unable to rename " + src +
                              " to " + target);
      }
    }
  }
440640
public static void setFileContents(File file, ByteBuffer contents) throws IOException {
    setFileContents(file, contents, false);
  }
1112198
private File processFile(File file) throws Exception {
        List<String> original = readFile(file);
        List<String> content = new ArrayList<>(original);
        BeanGen gen;
        try {
            BeanParser parser = new BeanParser(file, content, config);
            gen = parser.parse();
        } catch (BeanCodeGenException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new BeanCodeGenException(ex.getMessage(), ex, file);
        }
        if (gen.isBean()) {
            if (verbosity >= 2) {
                System.out.print(file + "  [processing]");
            }
            gen.process();
            if (content.equals(original) == false) {
                if (write) {
                    if (verbosity >= 2) {
                        System.out.println(" [writing]");
                    } else if (verbosity == 1) {
                        System.out.println(file + "  [writing]");
                    }
                    writeFile(file, content);
                } else {
                    if (verbosity >= 2) {
                        System.out.println(" [changed not written]");
                    } else if (verbosity == 1) {
                        System.out.println(file + "  [changed not written]");
                    }
                }
                return file;
            } else {
                if (verbosity >= 2) {
                    System.out.println(" [no change]");
                }
            }
        } else {
            gen.processNonBean();
            if (!content.equals(original)) {
                if (write) {
                    if (verbosity >= 2) {
                        System.out.println(" [writing]");
                    } else if (verbosity == 1) {
                        System.out.println(file + "  [writing]");
                    }
                    writeFile(file, content);
                } else {
                    if (verbosity >= 2) {
                        System.out.println(" [changed not written]");
                    } else if (verbosity == 1) {
                        System.out.println(file + "  [changed not written]");
                    }
                }
                return file;
            } else {
                if (verbosity == 3) {
                    System.out.println(file + "  [ignored]");
                }
            }
        }
        return null;
    }
915042
private void replaceInFile(String oldText, String newText) {
        StringBuilder oldContent = new StringBuilder();

        try (FileReader fr = new FileReader(file); BufferedReader reader = new BufferedReader(fr)) {
            String line;
            while ((line = reader.readLine()) != null) {
                oldContent.append(line);
                oldContent.append("\r\n");
            }
        } catch (IOException e) {
            log.error(e);
        }

        // replace a word in a file
        String newContent = oldContent.toString().replaceAll(oldText, newText);

        try (FileWriter writer = new FileWriter(file)) {
            writer.write(newContent);
        } catch (IOException ioe) {
            log.error(ioe);
        }
    }
460882
public void actionNew() throws JspException {

        String newFileName = "";
        try {
            newFileName = A_CmsResourceCollector.createResourceForCollector(
                getCms(),
                m_paramNewLink,
                getElementLocale(),
                getParamResource(),
                getParamModelFile(),
                getParamMode(),
                getParamPostCreateHandler());
            // wipe out parameters for the editor to ensure proper operation
            setParamNewLink(null);
            setParamAction(null);
            setParamResource(newFileName);
            setAction(ACTION_DEFAULT);

            // create the temporary file to work with
            setParamTempfile(createTempFile());

            // set the member variables for the content
            m_file = getCms().readFile(getParamTempfile(), CmsResourceFilter.ALL);
            if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getParamModelFile())) {
                m_content = CmsXmlContentFactory.unmarshal(
                    getCms(),
                    getCms().readFile(newFileName, CmsResourceFilter.ALL));
            } else {
                m_content = CmsXmlContentFactory.unmarshal(getCms(), m_file);
            }

        } catch (CmsException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_CREATE_XML_CONTENT_ITEM_1, m_paramNewLink), e);
            }
            throw new JspException(e);
        } finally {
            try {
                // delete the new file
                getCms().deleteResource(newFileName, CmsResource.DELETE_REMOVE_SIBLINGS);
            } catch (CmsException e) {
                // ignore
            }
        }
    }
1339249
private List<String> readFile(File file) throws Exception {
        List<String> content = new ArrayList<>(100);
        try (BufferedReader is = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
            String line;
            while ((line = is.readLine()) != null) {
                content.add(line);
            }
            return content;
        }
    }
602736
public static void doFile(File f)
                              throws Exception {
        // If this is a directory, walk each file/dir in that directory
        if (f.isDirectory()) {
            String files[] = f.list();
            for(int i=0; i < files.length; i++)
                doFile(new File(f, files[i]));
        }

        // otherwise, if this is a groovy file, parse it!
        else if (f.getName().endsWith(".groovy")) {
            System.err.println(" --- "+f.getAbsolutePath());
            // parseFile(f.getName(), new FileInputStream(f));
            SourceBuffer sourceBuffer = new SourceBuffer();
            UnicodeEscapingReader unicodeReader = new UnicodeEscapingReader(new FileReader(f),sourceBuffer);
            GroovyLexer lexer = new GroovyLexer(unicodeReader);
            unicodeReader.setLexer(lexer);
            parseFile(f.getName(),lexer,sourceBuffer);
        }
    }

    // Here's where we do the real work...
    public static void parseFile(String f, GroovyLexer l, SourceBuffer sourceBuffer)
                                 throws Exception {
        try {
            // Create a parser that reads from the scanner
            GroovyRecognizer parser = GroovyRecognizer.make(l);
            parser.setSourceBuffer(sourceBuffer);
            parser.setFilename(f);
                        
                        if (whitespaceIncluded) {
                            GroovyLexer lexer = parser.getLexer();
                            lexer.setWhitespaceIncluded(true);
                            while (true) {
                                Token t = lexer.nextToken();
                                System.out.println(t);
                                if (t == null || t.getType() == Token.EOF_TYPE)  break;
                            }
                            return;
                        }

            // start parsing at the compilationUnit rule
            parser.compilationUnit();
            
            System.out.println("parseFile "+f+" => "+parser.getAST());

            // do something with the tree
            doTreeAction(f, parser.getAST(), parser.getTokenNames());
        }
327339
public function overwrite($file, $content)
    {
        $written = file_put_contents($file, $content);

        // If $content is not empty
        // but nothing was written to $file
        // throw an exception.
        if ($content and ! $written)
        {
            throw new RuntimeException(
                "Unable to write to {$file}."
            );
        }
    }
1296652
public static void saveFile(final File file, byte[] fileContents) throws IOException {
        if (file.isDirectory()) {
            throw new IOException("Unable to save file contents as a directory.");
        }

        final FileOutputStream fos = new FileOutputStream(file);
        fos.write(fileContents);
        fos.flush();
        fos.close();
    }
961633
public void stringToFile(String content, File file) throws IOException {
        stringToOutputStream(content, new FileOutputStream(file));
    }
520402
private void spoolContent(InputStream is) throws IOException, FileNotFoundException
   {
      SwapFile swapFile =
         SwapFile.get(spoolConfig.tempDirectory, System.currentTimeMillis() + "_" + SEQUENCE.incrementAndGet(),
            spoolConfig.fileCleaner);
      try
      {
         OutputStream os = PrivilegedFileHelper.fileOutputStream(swapFile); 
         try
         {
            byte[] bytes = new byte[1024];
            int length;
            while ((length = is.read(bytes)) != -1)
            {
               os.write(bytes, 0, length);
            }
         }
         finally
         {
            os.close();
         }
      }
      finally
      {
         swapFile.spoolDone();
         is.close();
      }
      tempFile = swapFile;
   }
802952
private void replaceModuleName() throws CmsException, UnsupportedEncodingException {

        CmsResourceFilter filter = CmsResourceFilter.ALL.addRequireFile().addExcludeState(
            CmsResource.STATE_DELETED).addRequireTimerange().addRequireVisible();
        List<CmsResource> resources = getCms().readResources(
            CmsWorkplace.VFS_PATH_MODULES + m_cloneInfo.getName() + "/",
            filter);
        for (CmsResource resource : resources) {
            CmsFile file = getCms().readFile(resource);
            if (CmsResourceTypeXmlContent.isXmlContent(file)) {
                CmsXmlContent xmlContent = CmsXmlContentFactory.unmarshal(getCms(), file);
                xmlContent.setAutoCorrectionEnabled(true);
                file = xmlContent.correctXmlStructure(getCms());
            }
            byte[] contents = file.getContents();
            String encoding = CmsLocaleManager.getResourceEncoding(getCms(), file);
            String content = new String(contents, encoding);
            Matcher matcher = Pattern.compile(m_cloneInfo.getSourceModuleName()).matcher(content);
            if (matcher.find()) {
                contents = matcher.replaceAll(m_cloneInfo.getName()).getBytes(encoding);
                if (lockResource(getCms(), file)) {
                    file.setContents(contents);
                    getCms().writeFile(file);
                }
            }
        }
    }
745694
InputStream openContentStream(final ContentItem item) throws IOException {
        final File file = getFile(item);
        if (file == null) {
            throw new IllegalStateException();
        }
        return new FileInputStream(file);
    }
1237457
public static boolean replaceEntry(final File zip, final String path, final File file) {
    return operateInPlace(zip, new InPlaceAction() {
      public boolean act(File tmpFile) {
        return replaceEntry(zip, new FileSource(path, file), tmpFile);
      }
    });
  }
98772
public void add(String file, String contents) throws IOException {
		FileUtils.writeStringToFile(tempDir.resolve(file).toFile(), contents);
	}