/** @throws java.lang.Exception */
 @Before
 public void setUp() throws Exception {
   processor = new UglifyPostProcessor();
   when(config.getContext()).thenReturn(context);
   when(config.getConfigProperties()).thenReturn(new Properties());
   when(bundle.getId()).thenReturn("/myJsBundle.js");
 }
  @Test
  public void testBasicURLWithNonExistingImageRewriting() {

    // Set the properties
    Properties props = new Properties();
    config = new JawrConfig("css", props);
    ServletContext servletContext = new MockServletContext();
    config.setContext(servletContext);
    config.setServletMapping("/css");
    config.setCharsetName("UTF-8");
    addGeneratorRegistryToConfig(config, "css");
    status =
        new BundleProcessingStatus(
            BundleProcessingStatus.BUNDLE_PROCESSING_TYPE, bundle, rsHandler, config);

    // Set up the Image servlet Jawr config
    props = new Properties();
    JawrConfig imgServletJawrConfig = new JawrConfig(JawrConstant.BINARY_TYPE, props);
    addGeneratorRegistryToConfig(imgServletJawrConfig, JawrConstant.BINARY_TYPE);

    BinaryResourcesHandler imgRsHandler =
        new BinaryResourcesHandler(imgServletJawrConfig, rsHandler, null);
    servletContext.setAttribute(JawrConstant.BINARY_CONTEXT_ATTRIBUTE, imgRsHandler);
    // basic test
    StringBuffer data = new StringBuffer("background-image:url(../../../../images/someImage.gif);");
    // the image is at /images
    String filePath = "/css/folder/subfolder/subfolder/someCSS.css";
    // Expected: goes 1 back for servlet mapping, 1 back for prefix, 1 back for the id having a
    // subdir path.
    String expectedURL = "background-image:url(../../../images/someImage.gif);";
    status.setLastPathAdded(filePath);

    String result = processor.postProcessBundle(status, data).toString();
    assertEquals("URL was not rewritten properly", expectedURL, result);
  }
示例#3
0
  /**
   * The constructor
   *
   * @param config the jawr config
   */
  public EhCacheManager(JawrConfig config) {

    super(config);
    String configPath = config.getProperty(JAWR_EHCACHE_CONFIG_PATH, DEFAULT_EHCACHE_CONFIG_PATH);
    String cacheName = config.getProperty(JAWR_EHCACHE_CACHE_NAME);
    try {
      CacheManager cacheMgr =
          CacheManager.create(ClassLoaderResourceUtils.getResourceAsStream(configPath, this));
      cache = cacheMgr.getCache(cacheName);

    } catch (Exception e) {
      LOGGER.error("Unable to load EHCACHE configuration file", e);
    }
  }
 @Test
 public void testSameUrlWithQuotes() {
   StringBuffer data = new StringBuffer("background-image:url(  'images/some\\'Image\\\".gif' );");
   // Remove the url mapping from config, one back reference less expected
   config.setServletMapping("");
   String expectedURL = "background-image:url('../../css/images/some\\'Image\\\".gif');";
   String result = processor.postProcessBundle(status, data).toString();
   assertEquals("URL was not rewritten properly:" + result, expectedURL, result);
 }
  @Test
  public void testURLImgClasspathCssRewriting() {

    // Set the properties
    Properties props = new Properties();
    props.setProperty(JawrConfig.JAWR_CSS_CLASSPATH_HANDLE_IMAGE, "true");
    config = new JawrConfig("css", props);
    ServletContext servletContext = new MockServletContext();
    config.setContext(servletContext);
    config.setServletMapping("/css");
    config.setCharsetName("UTF-8");
    addGeneratorRegistryToConfig(config, "css");

    // Set up the Image servlet Jawr config
    props = new Properties();
    JawrConfig imgServletJawrConfig = new JawrConfig(JawrConstant.BINARY_TYPE, props);
    GeneratorRegistry generatorRegistry =
        addGeneratorRegistryToConfig(imgServletJawrConfig, JawrConstant.BINARY_TYPE);
    generatorRegistry.setResourceReaderHandler(rsHandler);
    imgServletJawrConfig.setServletMapping("/cssImg/");
    BinaryResourcesHandler imgRsHandler =
        new BinaryResourcesHandler(imgServletJawrConfig, rsHandler, null);
    servletContext.setAttribute(JawrConstant.BINARY_CONTEXT_ATTRIBUTE, imgRsHandler);

    status =
        new BundleProcessingStatus(
            BundleProcessingStatus.BUNDLE_PROCESSING_TYPE, bundle, null, config);

    // Css data
    StringBuffer data = new StringBuffer("background-image:url(jar:style/images/logo.png);");

    // Css path
    String filePath = "style/default/assets/someCSS.css";

    // Expected: goes 3 back to the context path, then add the CSS image servlet mapping,
    // then go to the image path
    // the image is at classPath:/style/images/someImage.gif
    String expectedURL =
        "background-image:url(../../../cssImg/jar_cb3015770054/style/images/logo.png);";
    status.setLastPathAdded(filePath);

    String result = processor.postProcessBundle(status, data).toString();
    assertEquals("URL was not rewritten properly", expectedURL, result);
  }
  /**
   * Returns the resource input stream
   *
   * @param config the Jawr config
   * @param path the resource path
   * @return the resource input stream
   */
  private InputStream getResourceInputStream(JawrConfig config, String path) {
    InputStream is = config.getContext().getResourceAsStream(path);
    if (is == null) {
      try {
        is = ClassLoaderResourceUtils.getResourceAsStream(path, this);
      } catch (FileNotFoundException e) {
        throw new BundlingProcessException(e);
      }
    }

    return is;
  }
  /** Initialize the postprocessor */
  private void initialize(JawrConfig config) {

    StopWatch stopWatch = new StopWatch("Initializing JS engine for Autoprefixer");
    stopWatch.start();

    // Load JavaScript Script Engine
    String script =
        config.getProperty(AUTOPREFIXER_SCRIPT_LOCATION, AUTOPREFIXER_SCRIPT_DEFAULT_LOCATION);
    String jsEngineName = config.getJavascriptEngineName(AUTOPREFIXER_JS_ENGINE);
    jsEngine = new JavascriptEngine(jsEngineName, true);
    jsEngine.getBindings().put("logger", PERF_LOGGER);
    InputStream inputStream = getResourceInputStream(config, script);
    jsEngine.evaluate("autoprefixer.js", inputStream);
    String strOptions =
        config.getProperty(AUTOPREFIXER_SCRIPT_OPTIONS, AUTOPREFIXER_DEFAULT_OPTIONS);
    this.options = jsEngine.execEval(strOptions);

    jsEngine.evaluate(
        "initAutoPrefixer.js", String.format("processor = autoprefixer(%s);", strOptions));
    jsEngine.evaluate(
        "jawrAutoPrefixerProcess.js",
        String.format(
            "function process(cssSource, opts){"
                + "var result = processor.process(cssSource, opts);"
                + "if(result.warnings){"
                + "result.warnings().forEach(function(message){"
                + "if(logger.isWarnEnabled()){"
                + "logger.warn(message.toString());"
                + "}"
                + "});}"
                + "return result.css;"
                + "}"));

    stopWatch.stop();
    if (PERF_LOGGER.isDebugEnabled()) {
      PERF_LOGGER.debug(stopWatch.shortSummary());
    }
  }
  @SuppressWarnings("unchecked")
  @Before
  public void setUp() throws Exception {
    // Bundle path (full url would be: /servletMapping/prefix/css/bundle.css
    final String bundlePath = "/css/bundle.css";
    // Bundle url prefix
    final String urlPrefix = "/v00";

    when(rsHandler.getResourceAsStream(Matchers.anyString()))
        .thenAnswer(
            new Answer<InputStream>() {

              @Override
              public InputStream answer(InvocationOnMock invocation) throws Throwable {
                String resourceName = (String) invocation.getArguments()[0];
                if (resourceName.equals("jar:style/images/logo.png")) {
                  return new ByteArrayInputStream("Fake value".getBytes());
                }

                throw new ResourceNotFoundException(resourceName);
              }
            });

    when(bundle.getId()).thenReturn(bundlePath);
    when(bundle.getURLPrefix(Matchers.anyMap())).thenReturn(urlPrefix);

    config = new JawrConfig("css", new Properties());
    ServletContext servletContext = new MockServletContext();
    config.setContext(servletContext);
    config.setServletMapping("/js");
    config.setCharsetName("UTF-8");
    status =
        new BundleProcessingStatus(
            BundleProcessingStatus.BUNDLE_PROCESSING_TYPE, bundle, null, config);
    addGeneratorRegistryToConfig(config, "js");
    status.setLastPathAdded("/css/someCSS.css");
    processor = new CSSURLPathRewriterPostProcessor();
  }
 @Test
 public void testBasicURLWithAbsolutePathInContextPathRewriting() {
   // basic test
   StringBuffer data = new StringBuffer("background-image:url(/myApp/images/someImage.gif);");
   config.getConfigProperties().put("jawr.css.url.rewriter.context.path", "/myApp/");
   // StringBuffer data = new
   // StringBuffer("background-image:url(../../../../images/someImage.gif);");
   // the image is at /images
   String filePath = "/css/folder/subfolder/subfolder/someCSS.css";
   // Expected: goes 1 back for servlet mapping, 1 back for prefix, 1 back for the id having a
   // subdir path.
   String expectedURL = "background-image:url(../../../images/someImage.gif);";
   status.setLastPathAdded(filePath);
   String result = processor.postProcessBundle(status, data).toString();
   assertEquals("URL was not rewritten properly", expectedURL, result);
 }
  @Test
  public void testPostProcessWithOutputOptions() throws Exception {

    String src = FileUtils.readClassPathFile("postprocessor/js/uglify/simpleJS.js");
    StringBuffer sb = new StringBuffer(src);
    when(config.getProperty(JawrConstant.UGLIFY_POSTPROCESSOR_OPTIONS, "{}"))
        .thenReturn("{output : {comments : /@preserve/ }}");
    BundleProcessingStatus status =
        new BundleProcessingStatus(
            BundleProcessingStatus.BUNDLE_PROCESSING_TYPE, bundle, null, config);
    StringBuffer ret = processor.postProcessBundle(status, sb);

    String expected =
        FileUtils.readClassPathFile(
            "postprocessor/js/uglify/simpleJS_WithOutputOptions_expected.js");
    assertEquals(expected, ret.toString());
  }
  private GeneratorRegistry addGeneratorRegistryToConfig(JawrConfig config, String type) {
    GeneratorRegistry generatorRegistry =
        new GeneratorRegistry(type) {
          private static final long serialVersionUID = 1L;

          public boolean isHandlingCssImage(String cssResourcePath) {

            boolean result = false;
            if (cssResourcePath.startsWith("jar:")) {
              result = true;
            }
            return result;
          }
        };
    generatorRegistry.setConfig(config);
    config.setGeneratorRegistry(generatorRegistry);
    return generatorRegistry;
  }
 /* (non-Javadoc)
  * @see net.jawr.web.resource.handler.reader.ServletContextResourceReader#init(javax.servlet.ServletContext, net.jawr.web.config.JawrConfig)
  */
 public void init(ServletContext context, JawrConfig config) {
   this.context = context;
   this.charset = config.getResourceCharset();
 }