Rewrites the image URL

@param originalCssPath
the original CSS path
@param newCssPath
the new CSS path
@param originalCssContent
the original CSS content
@return the new CSS content with image path rewritten
@throws IOException
if an IO exception occurs
519216
public StringBuffer rewriteUrl(String originalCssPath, String newCssPath, String originalCssContent)
			throws IOException {

		// Rewrite each css image url path
		Matcher matcher = URL_PATTERN.matcher(originalCssContent);
		StringBuffer sb = new StringBuffer();
		while (matcher.find()) {

			String url = getUrlPath(matcher.group(), originalCssPath, newCssPath);
			matcher.appendReplacement(sb, RegexUtil.adaptReplacementToMatcher(url));
		}
		matcher.appendTail(sb);
		return sb;
	}
653891
public static BufferedWriter newBufferedWriter(Path path) throws IOException {
        FileUtils.checkDirectory(path.getParent());
        BufferedWriter bufferedWriter;
        if (path.toFile().getName().endsWith(".gz")) {
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(path.toFile()))));
        } else {
            bufferedWriter = Files.newBufferedWriter(path, Charset.defaultCharset());
        }
        return bufferedWriter;
    }
457558
private URL buildUrl(final String styleSheetPath, final boolean skipStylesFolder) {

        URL cssResource = null;

        final List<String> stylePaths = skipStylesFolder ? Collections.singletonList("") : ResourceParameters.STYLE_FOLDER.get();

        for (int i = 0; i < stylePaths.size() && cssResource == null; i++) {

            String stylePath = stylePaths.get(i);
            if (!stylePath.isEmpty()) {
                stylePath += Resources.PATH_SEP;
            }
            cssResource = Thread.currentThread().getContextClassLoader().getResource(stylePath + styleSheetPath);
        }

        if (cssResource == null) {
            LOGGER.error("Style Sheet : {} not found into base folder: {}", styleSheetPath, ResourceParameters.STYLE_FOLDER.get());
        }
        return cssResource;
    }
196778
protected String rewriteContentString(String originalContent) {

        Pattern uuidPattern = Pattern.compile(CmsUUID.UUID_REGEX);
        I_CmsRegexSubstitution substitution = new I_CmsRegexSubstitution() {

            public String substituteMatch(String text, Matcher matcher) {

                String uuidString = text.substring(matcher.start(), matcher.end());
                CmsUUID uuid = new CmsUUID(uuidString);
                String result = uuidString;
                if (m_translationsById.containsKey(uuid)) {
                    result = m_translationsById.get(uuid).getStructureId().toString();
                }
                return result;
            }
        };
        return CmsStringUtil.substitute(uuidPattern, originalContent, substitution);
    }
12008
@Nonnull
  public static HCLink createCSSLink (@Nonnull final ISimpleURL aCSSURL)
  {
    return new HCLink ().setRel (EHCLinkType.STYLESHEET).setType (CMimeType.TEXT_CSS).setHref (aCSSURL);
  }
1034519
private static CEMI create(int msgCode, IndividualAddress src, KNXAddress dst,
		byte[] data, CEMILData original, boolean ext)
	{
		final int mc = msgCode != 0 ? msgCode : original.getMessageCode();
		final IndividualAddress s = src != null ? src : original.getSource();
		final KNXAddress d = dst != null ? dst : original.getDestination();
		final byte[] content = data != null ? data : original.getPayload();
		if (original instanceof CEMILDataEx) {
			final CEMILDataEx f = (CEMILDataEx) original;
			final CEMILDataEx copy =
				new CEMILDataEx(mc, s, d, content, f.getPriority(), f.isRepetition(), f
					.isDomainBroadcast(), f.isAckRequested(), f.getHopCount());
			// copy additional info
			final List l = f.getAdditionalInfo();
			for (final Iterator i = l.iterator(); i.hasNext();) {
				final CEMILDataEx.AddInfo info = (CEMILDataEx.AddInfo) i.next();
				copy.addAdditionalInfo(info.getType(), info.getInfo());
			}
			return copy;
		}
		if (ext)
			return new CEMILDataEx(mc, s, d, content, original.getPriority(), original
				.isRepetition(), original.getHopCount());
		return new CEMILData(mc, s, d, content, original.getPriority(), original
			.isRepetition(), original.getHopCount());
	}
260623
public void generateDataUriCss(String dir) throws IOException {
		final String path = (dir == null) ? "" : dir + "/";
		final PrintWriter out = new PrintWriter(path + "DataUriCss.html");

		try {
			out.append("<html>\n<head>\n\t<style>");

			for (OptimizerResult result : results) {
				final String name = result.fileName.replaceAll("[^A-Za-z0-9]", "_");
				out.append('#').append(name).append(" {\n")
						.append("\tbackground: url(\"data:image/png;base64,")
						.append(result.dataUri).append("\") no-repeat left top;\n")
						.append("\twidth: ").append(String.valueOf(result.width)).append("px;\n")
						.append("\theight: ").append(String.valueOf(result.height)).append("px;\n")
						.append("}\n");
			}
			out.append("\t</style>\n</head>\n<body>\n");

			for (OptimizerResult result : results) {
				final String name = result.fileName.replaceAll("[^A-Za-z0-9]", "_");
				out.append("\t<div id=\"").append(name).append("\"></div>\n");
			}

			out.append("</body>\n</html>");
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
1117471
public static final StyleSheet parse(URL url, String encoding)
			throws CSSException, IOException {
		return getCSSParserFactory().parse(url, getNetworkProcessor(), encoding, SourceType.URL, url);
	}
468388
private void renderRecipe() throws IOException {
		StringBuilder sb = new StringBuilder();

		// First pages
		if( ! Constants.GENERATED.equalsIgnoreCase( this.applicationTemplate.getName())) {
			sb.append( renderDocumentTitle());
			sb.append( renderPageBreak());

			sb.append( renderParagraph( this.messages.get( "intro" ))); //$NON-NLS-1$
			sb.append( renderPageBreak());

			sb.append( renderDocumentIndex());
			sb.append( renderPageBreak());

			sb.append( startTable());
			sb.append( addTableLine( this.messages.get( "app.name" ), this.applicationTemplate.getName())); //$NON-NLS-1$
			sb.append( addTableLine( this.messages.get( "app.qualifier" ), this.applicationTemplate.getVersion())); //$NON-NLS-1$
			sb.append( endTable());

			sb.append( renderApplicationDescription());
			sb.append( renderPageBreak());
			sb.append( renderSections( new ArrayList<String>( 0 )));

		} else {
			sb.append( renderDocumentIndex());
			sb.append( renderPageBreak());
		}

		// Render information about components
		sb.append( renderComponents());

		// Render information about facets
		sb.append( renderFacets());

		writeFileContent( sb.toString());
	}
146639
protected function fixRelativePaths($content, $originalFile)
    {
        $cssParserSettings = CssSettings::create()->withMultibyteSupport(false);
        $cssParser = new CssParser($content, $cssParserSettings);
        $cssDocument = $cssParser->parse();

        $cssBlocks = $cssDocument->getAllValues();

        $this->fixUrls($cssBlocks, $originalFile);

        return $cssDocument->render();
    }
156438
private String getCssPathContent(String cssPathToImport, String media, BundleProcessingStatus status)
			throws IOException {

		String currentCssPath = status.getLastPathAdded();

		String path = cssPathToImport;

		JawrConfig jawrConfig = status.getJawrConfig();

		if (jawrConfig.getGeneratorRegistry().isPathGenerated(path)) {

			ResourceGenerator generator = jawrConfig.getGeneratorRegistry().getResourceGenerator(path);
			if (generator != null && generator.getResolver() instanceof SuffixedPathResolver) {
				path = PathNormalizer.concatWebPath(currentCssPath, cssPathToImport);
			}
		} else if (!cssPathToImport.startsWith("/")) { // relative URL
			path = PathNormalizer.concatWebPath(currentCssPath, cssPathToImport);
		}

		FilePathMappingUtils.buildFilePathMapping(status.getCurrentBundle(), path, status.getRsReader());
		Reader reader = null;

		try {
			reader = status.getRsReader().getResource(status.getCurrentBundle(), path, true);
		} catch (ResourceNotFoundException e) {
			throw new IOException("Css to import '" + path + "' was not found", e);
		}

		StringWriter content = new StringWriter();
		IOUtils.copy(reader, content, true);

		BinaryResourcesHandler binaryRsHandler = (BinaryResourcesHandler) jawrConfig.getContext()
				.getAttribute(JawrConstant.BINARY_CONTEXT_ATTRIBUTE);
		if (binaryRsHandler != null) {
			jawrConfig = binaryRsHandler.getConfig();
		}
		// Rewrite image URL
		CssImportedUrlRewriter urlRewriter = new CssImportedUrlRewriter(jawrConfig);
		StringBuilder result = new StringBuilder();
		boolean isMediaAttributeSet = StringUtils.isNotEmpty(media);
		if (isMediaAttributeSet) {
			result.append("@media ").append(media).append(" {\n");
		}
		result.append(urlRewriter.rewriteUrl(path, currentCssPath, content.getBuffer().toString()));
		if (isMediaAttributeSet) {
			result.append("\n}\n");
		}
		return result.toString();
	}
692650
private URL buildStyleSheetUrl(final StyleSheet ss) {

        final StringBuilder sb = new StringBuilder();

        if (!ss.path().isEmpty()) {
            sb.append(ss.path()).append(Resources.PATH_SEP);
        }

        sb.append(ss.name());

        if (!ss.name().endsWith(CSS_EXT)) {
            sb.append(CSS_EXT);
        }

        return buildUrl(sb.toString(), ss.skipStylesFolder());
    }
363844
protected void writeLink(Header header) throws IOException {
        addTabs(2);
        writeStart(HtmlTags.LINK);
        write(HtmlTags.REL, header.getName());
        write(HtmlTags.TYPE, HtmlTags.TEXT_CSS);
        write(HtmlTags.REFERENCE, header.getContent());
        writeEnd();
    }
991366
private void renderIeCssBundleLink(BundleRendererContext ctx, Writer out, BundlePath bundlePath)
			throws IOException {
		Random randomSeed = new Random();
		int random = randomSeed.nextInt();
		if (random < 0)
			random *= -1;
		String path = GeneratorRegistry.IE_CSS_GENERATOR_PREFIX + GeneratorRegistry.PREFIX_SEPARATOR
				+ bundlePath.getPath();
		path = PathNormalizer.createGenerationPath(path, bundler.getConfig().getGeneratorRegistry(), "d=" + random);
		out.write(createBundleLink(path, null, null, ctx.getContextPath(), ctx.isSslRequest()));
	}
1332414
public function write(string $originalFileName, int $lifetime, string $originalContent)
    {
        $configuration = GeneralUtility::makeInstance(ConfigurationService::class);
        $tagService = GeneralUtility::makeInstance(TagService::class);

        $fileName = PathUtility::pathinfo($originalFileName, PATHINFO_DIRNAME) . '/.htaccess';
        $accessTimeout = (int)$configuration->get('htaccessTimeout');
        $lifetime = $accessTimeout ? $accessTimeout : $lifetime;

        $tags = $tagService->isEnable() ? $tagService->getTags() : [];

        $variables = [
            'mode' => $accessTimeout ? 'A' : 'M',
            'lifetime' => $lifetime,
            'expires' => (new DateTimeService())->getCurrentTime() + $lifetime,
            'typo3headers' => GeneralUtility::makeInstance(TypoScriptFrontendService::class)->getAdditionalHeaders(),
            'sendCacheControlHeader' => $configuration->isBool('sendCacheControlHeader'),
            'sendCacheControlHeaderRedirectAfterCacheTimeout' => $configuration->isBool('sendCacheControlHeaderRedirectAfterCacheTimeout'),
            'sendTypo3Headers' => $configuration->isBool('sendTypo3Headers'),
            'tags' => \implode(',', $tags),
            'tagHeaderName' => $tagService->getHeaderName(),
            'sendStaticFileCacheHeader' => $configuration->isBool('sendStaticFileCacheHeader'),
            'httpPushHeaders' => GeneralUtility::makeInstance(HttpPushService::class)->getHttpPushHeaders($originalContent),
        ];

        $this->renderTemplateToFile($this->getTemplateName(), $variables, $fileName);
    }
1230121
def install_custom_css( destdir, cssfile, resource=PKGNAME ):
    
    ensure_dir_exists( destdir )
    custom = os.path.join( destdir, 'custom.css' )
    prefix = css_frame_prefix(resource)

    # Check if custom.css already includes it. If so, let's remove it first
    exists = False
    if os.path.exists( custom ):
        with io.open(custom) as f:
            for line in f:
                if line.find( prefix ) >= 0:
                    exists = True
                    break
    if exists:
        remove_custom_css( destdir, resource )

    # Fetch the CSS file
    cssfile += '.css'
    data = pkgutil.get_data( resource, os.path.join('resources',cssfile) )
    # get_data() delivers encoded data, str (Python2) or bytes (Python3)

    # Add the CSS at the beginning of custom.css
    # io.open uses unicode strings (unicode in Python2, str in Python3)
    with io.open(custom + '-new', 'wt', encoding='utf-8') as fout:
        fout.write( u'{}START ======================== */\n'.format(prefix))
        fout.write( data.decode('utf-8') )
        fout.write( u'{}END ======================== */\n'.format(prefix))
        if os.path.exists( custom ):
            with io.open( custom, 'rt', encoding='utf-8' ) as fin:
                for line in fin:
                    fout.write( unicode(line) )
    os.rename( custom+'-new',custom)
1019482
function cssToJsFn(filePath, file) {
    var STYLE_HEADER = 'css = \'',
        STYLE_FOOTER = '\';';

    var css = new CleanCss({})
        .minify(file.contents.toString())
        .styles;

    file.contents = new Buffer(STYLE_HEADER + escapeStr(css) + STYLE_FOOTER);

    return file.contents.toString('utf8');
}