Projects >> wro4j >>bb3227be1df3dec43bae2ac411f53a90de71e82f

Chunk
Conflicting content
  @Inject
  private ResourceAuthorizationManager authorizationManager;

<<<<<<< HEAD

=======
>>>>>>> d9390f978dee356e84a1e71532489c30363c0526
  public WroManager() {
    cacheSchedulerHelper = SchedulerHelper.create(new LazyInitializer() {
      @Override
Solution content
  @Inject
  private ResourceAuthorizationManager authorizationManager;


  public WroManager() {
    cacheSchedulerHelper = SchedulerHelper.create(new LazyInitializer() {
      @Override
File
WroManager.java
Developer's decision
Version 1
Kind of conflict
Blank
Chunk
Conflicting content
  };
   */
<<<<<<< HEAD
/**
 * Copyright Alex Objelean
 */
package ro.isdc.wro.model.group.processor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.Validate;

import ro.isdc.wro.cache.CacheEntry;
import ro.isdc.wro.cache.CacheStrategy;
import ro.isdc.wro.cache.ContentHashEntry;
import ro.isdc.wro.cache.DefaultSynchronizedCacheStrategyDecorator;
import ro.isdc.wro.config.Context;
import ro.isdc.wro.config.ReadOnlyContext;
import ro.isdc.wro.config.jmx.WroConfiguration;
import ro.isdc.wro.manager.WroManager;
import ro.isdc.wro.manager.callback.LifecycleCallbackRegistry;
import ro.isdc.wro.manager.factory.WroManagerFactory;
import ro.isdc.wro.model.factory.DefaultWroModelFactoryDecorator;
import ro.isdc.wro.model.factory.WroModelFactory;
import ro.isdc.wro.model.group.GroupExtractor;
import ro.isdc.wro.model.resource.locator.factory.InjectorAwareResourceLocatorFactoryDecorator;
import ro.isdc.wro.model.resource.locator.factory.ResourceLocatorFactory;
import ro.isdc.wro.model.resource.processor.factory.ProcessorsFactory;
import ro.isdc.wro.model.resource.support.ResourceAuthorizationManager;
import ro.isdc.wro.model.resource.support.hash.HashStrategy;
import ro.isdc.wro.model.resource.support.naming.NamingStrategy;
import ro.isdc.wro.util.LazyInitializer;
import ro.isdc.wro.util.ObjectFactory;


/**
 * Responsible for building the {@link Injector}. It can build an {@link Injector} without needing a {@link WroManager},
 * but just by providing required dependencies.
 * 
 * @author Alex Objelean
 * @since 1.4.3
 * @created 6 Jan 2012
 */
public class InjectorBuilder {
  private final GroupsProcessor groupsProcessor = new GroupsProcessor();
  private final PreProcessorExecutor preProcessorExecutor = new PreProcessorExecutor();
  /**
   * A list of model transformers. Allows manager to mutate the model before it is being parsed and processed.
   */
  private Injector injector;
  /**
   * Mapping of classes to be annotated and the corresponding injected object. TODO: probably replace this map with
   * something like spring ApplicationContext (lightweight IoC).
   */
  private final Map, Object> map = new HashMap, Object>();
  private WroManagerFactory managerFactory;
  private final LazyInitializer uriLocatorFactoryInitializer = new LazyInitializer() {
    @Override
    protected ResourceLocatorFactory initialize() {
      final WroManager manager = managerFactory.create();
      // update manager with new decorated factory
      manager.setResourceLocatorFactory(InjectorAwareResourceLocatorFactoryDecorator.decorate(
          manager.getResourceLocatorFactory(), injector));
      return manager.getResourceLocatorFactory();
    }
  private LazyInitializer authorizationManagerInitializer = new LazyInitializer() {
    @Override
    protected ResourceAuthorizationManager initialize() {
      final WroManager manager = managerFactory.create();
      return manager.getResourceAuthorizationManager();
    }
  };
  
  private final LazyInitializer modelFactoryInitializer = new LazyInitializer() {
    @Override
    protected WroModelFactory initialize() {
      final WroManager manager = managerFactory.create();
      // update manager with new decorated factory
      manager.setModelFactory(DefaultWroModelFactoryDecorator.decorate(manager.getModelFactory(),
          manager.getModelTransformers()));
      return manager.getModelFactory();
    }
  };
  /**
   * Ensure the strategy is decorated only once.
   */
  private final LazyInitializer> cacheStrategyInitializer = new LazyInitializer>() {
    @Override
    protected CacheStrategy initialize() {
      final WroManager manager = managerFactory.create();
      // update manager with new decorated strategy
      manager.setCacheStrategy(DefaultSynchronizedCacheStrategyDecorator.decorate(manager.getCacheStrategy()));
      return manager.getCacheStrategy();
    }
  };

  /**
   * Use factory method {@link InjectorBuilder#create(WroManagerFactory)} instead.
   * 
   * @VisibleForTesting
   */
  public InjectorBuilder() {
  }
  
  /**
   * Factory method which uses a managerFactory to initialize injected fields.
  public static InjectorBuilder create(final WroManagerFactory managerFactory) {
    Validate.notNull(managerFactory);
    return new InjectorBuilder(managerFactory);
  }
  
  public InjectorBuilder(final WroManagerFactory managerFactory) {
    Validate.notNull(managerFactory);
    this.managerFactory = managerFactory;
  }
  
  private void initMap() {
    map.put(PreProcessorExecutor.class, new InjectorObjectFactory() {
      public PreProcessorExecutor create() {
        injector.inject(preProcessorExecutor);
        return preProcessorExecutor;
      }
    });
    map.put(GroupsProcessor.class, new InjectorObjectFactory() {
      public GroupsProcessor create() {
        injector.inject(groupsProcessor);
        return groupsProcessor;
      }
    });
    map.put(LifecycleCallbackRegistry.class, new InjectorObjectFactory() {
      public LifecycleCallbackRegistry create() {
        final LifecycleCallbackRegistry callbackRegistry = managerFactory.create().getCallbackRegistry();
        injector.inject(callbackRegistry);
        return callbackRegistry;
      }
    });
    map.put(GroupExtractor.class, new InjectorObjectFactory() {
      public GroupExtractor create() {
        final GroupExtractor groupExtractor = managerFactory.create().getGroupExtractor();
        injector.inject(groupExtractor);
        return groupExtractor;
      }
    });
    map.put(Injector.class, new InjectorObjectFactory() {
      public Injector create() {
        return injector;
      }
    });
    map.put(ResourceLocatorFactory.class, new InjectorObjectFactory() {
      public ResourceLocatorFactory create() {
        return uriLocatorFactoryInitializer.get();
      }
    });
    map.put(ProcessorsFactory.class, new InjectorObjectFactory() {
      public ProcessorsFactory create() {
        return managerFactory.create().getProcessorsFactory();
      }
    });
    map.put(WroModelFactory.class, new InjectorObjectFactory() {
      public WroModelFactory create() {
        final WroModelFactory modelFactory = modelFactoryInitializer.get();
        injector.inject(modelFactory);
        return modelFactory;
      }
    });
    map.put(NamingStrategy.class, new InjectorObjectFactory() {
      public NamingStrategy create() {
        NamingStrategy namingStrategy = managerFactory.create().getNamingStrategy();
        injector.inject(namingStrategy);
        return namingStrategy;
      }
    });
    map.put(HashStrategy.class, new InjectorObjectFactory() {
      public HashStrategy create() {
        final HashStrategy hashStrategy = managerFactory.create().getHashStrategy();
        injector.inject(hashStrategy);
        return hashStrategy;
      }
    });
    map.put(ReadOnlyContext.class, createReadOnlyContextProxy());
    map.put(WroConfiguration.class, new InjectorObjectFactory() {
      public WroConfiguration create() {
        return Context.get().getConfig();
      }
    });
    map.put(CacheStrategy.class, new InjectorObjectFactory>() {
      public CacheStrategy create() {
        final CacheStrategy decorated = cacheStrategyInitializer.get();
        injector.inject(decorated);
        return decorated;
      }
    });
    map.put(ResourceAuthorizationManager.class, new InjectorObjectFactory() {
      public ResourceAuthorizationManager create() {
        return authorizationManagerInitializer.get();
      }
    });
  }
  
  /**
   * @return a proxy of {@link ReadOnlyContext} object. This solution is preferred to {@link InjectorObjectFactory}
   *         because the injected field ensure thread-safe behavior.
   */
  private ReadOnlyContext createReadOnlyContextProxy() {
    InvocationHandler handler = new InvocationHandler() {
      public Object invoke(final Object proxy, final Method method, final Object[] args)
          throws Throwable {
        return method.invoke(Context.get(), args);
      }
    };
    final ReadOnlyContext readOnlyContext = (ReadOnlyContext) Proxy.newProxyInstance(
        ReadOnlyContext.class.getClassLoader(), new Class[] {
          ReadOnlyContext.class
        }, handler);
    return readOnlyContext;
  }

  public Injector build() {
    // first initialize the map
    initMap();
    return injector = new Injector(Collections.unmodifiableMap(map));
  }
  
  /**
   * A special type used for lazy object injection only in context of this class.
   */
  static interface InjectorObjectFactory
      extends ObjectFactory {
  };
}
=======
/**
 * Copyright Alex Objelean
 */
package ro.isdc.wro.model.group.processor;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ro.isdc.wro.cache.CacheEntry;
import ro.isdc.wro.cache.CacheStrategy;
import ro.isdc.wro.cache.ContentHashEntry;
import ro.isdc.wro.cache.DefaultSynchronizedCacheStrategyDecorator;
import ro.isdc.wro.config.Context;
import ro.isdc.wro.config.ReadOnlyContext;
import ro.isdc.wro.config.jmx.WroConfiguration;
import ro.isdc.wro.manager.WroManager;
import ro.isdc.wro.manager.callback.LifecycleCallbackRegistry;
import ro.isdc.wro.manager.factory.WroManagerFactory;
import ro.isdc.wro.model.factory.DefaultWroModelFactoryDecorator;
import ro.isdc.wro.model.factory.WroModelFactory;
import ro.isdc.wro.model.group.GroupExtractor;
import ro.isdc.wro.model.resource.locator.factory.InjectorAwareUriLocatorFactoryDecorator;
import ro.isdc.wro.model.resource.locator.factory.UriLocatorFactory;
import ro.isdc.wro.model.resource.processor.factory.ProcessorsFactory;
import ro.isdc.wro.model.resource.support.ResourceAuthorizationManager;
import ro.isdc.wro.model.resource.support.hash.HashStrategy;
import ro.isdc.wro.model.resource.support.naming.NamingStrategy;
import ro.isdc.wro.util.LazyInitializer;
import ro.isdc.wro.util.ObjectFactory;
import ro.isdc.wro.util.ProxyFactory;


/**
 * Responsible for building the {@link Injector}. It can build an {@link Injector} without needing a {@link WroManager},
 * but just by providing required dependencies.
 *
 * @author Alex Objelean
 * @since 1.4.3
 * @created 6 Jan 2012
 */
public class InjectorBuilder {
  private static final Logger LOG = LoggerFactory.getLogger(InjectorBuilder.class);
  private final GroupsProcessor groupsProcessor = new GroupsProcessor();
  private final PreProcessorExecutor preProcessorExecutor = new PreProcessorExecutor();
  /**
   * A list of model transformers. Allows manager to mutate the model before it is being parsed and processed.
   */
  private Injector injector;
  /**
   * Mapping of classes to be annotated and the corresponding injected object. TODO: probably replace this map with
   * something like spring ApplicationContext (lightweight IoC).
   */
  private final Map, Object> map = new HashMap, Object>();
  private WroManagerFactory managerFactory;
  private final LazyInitializer locatorFactoryInitializer = new LazyInitializer() {
    @Override
    protected UriLocatorFactory initialize() {
      final WroManager manager = managerFactory.create();
      // update manager with new decorated factory
      manager.setUriLocatorFactory(InjectorAwareUriLocatorFactoryDecorator.decorate(manager.getUriLocatorFactory(),
          injector));
      return manager.getUriLocatorFactory();
    }
  };
  private final LazyInitializer modelFactoryInitializer = new LazyInitializer() {
    @Override
    protected WroModelFactory initialize() {
      final WroManager manager = managerFactory.create();
      // update manager with new decorated factory
      manager.setModelFactory(DefaultWroModelFactoryDecorator.decorate(manager.getModelFactory(), manager
          .getModelTransformers()));
      return manager.getModelFactory();
    }
  };
  /**
   * Ensure the strategy is decorated only once.
   */
  private final LazyInitializer> cacheStrategyInitializer = new LazyInitializer>() {
    @Override
    protected CacheStrategy initialize() {
      final WroManager manager = managerFactory.create();
      // update manager with new decorated strategy
      manager.setCacheStrategy(DefaultSynchronizedCacheStrategyDecorator.decorate(manager.getCacheStrategy()));
      return manager.getCacheStrategy();
    }
  };

  /**
   * Use factory method {@link InjectorBuilder#create(WroManagerFactory)} instead.
   *
   * @VisibleForTesting
   */
  public InjectorBuilder() {
  }

  /**
   * Factory method which uses a managerFactory to initialize injected fields.
   */
  public static InjectorBuilder create(final WroManagerFactory managerFactory) {
    Validate.notNull(managerFactory);
    return new InjectorBuilder(managerFactory);
  }

  public InjectorBuilder(final WroManagerFactory managerFactory) {
    Validate.notNull(managerFactory);
    this.managerFactory = managerFactory;
  }

  private void initMap() {
    map.put(PreProcessorExecutor.class, createPreProcessorExecutorProxy());
    map.put(GroupsProcessor.class, createGroupsProcessorProxy());
    map.put(LifecycleCallbackRegistry.class, createCallbackRegistryProxy());
    map.put(GroupExtractor.class, createGroupExtractorProxy());
    map.put(Injector.class, createInjectorProxy());
    map.put(UriLocatorFactory.class, createLocatorFactoryProxy());
    map.put(ProcessorsFactory.class, createProcessorFactoryProxy());
    map.put(WroModelFactory.class, createModelFactoryProxy());
    map.put(NamingStrategy.class, createNamingStrategyProxy());
    map.put(HashStrategy.class, createHashStrategyProxy());
    map.put(ReadOnlyContext.class, createReadOnlyContextProxy());
    map.put(WroConfiguration.class, createConfigProxy());
    map.put(CacheStrategy.class, createCacheStrategyProxy());
    map.put(ResourceAuthorizationManager.class, createResourceAuthorizationManagerProxy());
  }

  private InjectorObjectFactory createConfigProxy() {
    return new InjectorObjectFactory() {
      public WroConfiguration create() {
        LOG.warn("Do not @Inject WroConfiguration. Prefer using @Inject ReadOnlyContext context; (and context.getConfig()).");
        return Context.get().getConfig();
      }
    };
  }

  private InjectorObjectFactory createPreProcessorExecutorProxy() {
    return new InjectorObjectFactory() {
      public PreProcessorExecutor create() {
        injector.inject(preProcessorExecutor);
        return preProcessorExecutor;
      }
    };
  }

  private InjectorObjectFactory createGroupsProcessorProxy() {
    return new InjectorObjectFactory() {
      public GroupsProcessor create() {
        injector.inject(groupsProcessor);
        return groupsProcessor;
      }
    };
  }

  private InjectorObjectFactory createCallbackRegistryProxy() {
    return new InjectorObjectFactory() {
      public LifecycleCallbackRegistry create() {
        final LifecycleCallbackRegistry callbackRegistry = managerFactory.create().getCallbackRegistry();
        injector.inject(callbackRegistry);
        return callbackRegistry;
      }
    };
  }

  private InjectorObjectFactory createInjectorProxy() {
    return new InjectorObjectFactory() {
      public Injector create() {
        return injector;
      }
    };
  }

  private Object createGroupExtractorProxy() {
    return new InjectorObjectFactory() {
      public GroupExtractor create() {
        final GroupExtractor groupExtractor = managerFactory.create().getGroupExtractor();
        injector.inject(groupExtractor);
        return groupExtractor;
      }
    };
  }

  private Object createProcessorFactoryProxy() {
    return new InjectorObjectFactory() {
      public ProcessorsFactory create() {
        return managerFactory.create().getProcessorsFactory();
      }
    };
  }

  private Object createLocatorFactoryProxy() {
    return new InjectorObjectFactory() {
      public UriLocatorFactory create() {
        return locatorFactoryInitializer.get();
      }
    };
  }

  private Object createResourceAuthorizationManagerProxy() {
    return new InjectorObjectFactory() {
      public ResourceAuthorizationManager create() {
        return managerFactory.create().getResourceAuthorizationManager();
      }
    };
  }

  private Object createModelFactoryProxy() {
    return new InjectorObjectFactory() {
      public WroModelFactory create() {
        final WroModelFactory modelFactory = modelFactoryInitializer.get();
        injector.inject(modelFactory);
        //final WroModelFactory proxy = ProxyFactory.proxy(modelFactory, WroModelFactory.class).create();
        return modelFactory;
      }
    };
  }

  private Object createNamingStrategyProxy() {
    return new InjectorObjectFactory() {
      public NamingStrategy create() {
        final NamingStrategy namingStrategy = managerFactory.create().getNamingStrategy();
        injector.inject(namingStrategy);
        //final NamingStrategy proxy = new ProxyFactory(namingStrategy, NamingStrategy.class).create();
        return namingStrategy;
      }
    };
  }

  private Object createHashStrategyProxy() {
    return new InjectorObjectFactory() {
      public HashStrategy create() {
        final HashStrategy hashStrategy = managerFactory.create().getHashStrategy();
        injector.inject(hashStrategy);
        return hashStrategy;
      }
    };
  }

  @SuppressWarnings("rawtypes")
  private Object createCacheStrategyProxy() {
    return new InjectorObjectFactory() {
      public CacheStrategy create() {
        final CacheStrategy decorated = cacheStrategyInitializer.get();
        injector.inject(decorated);
        return decorated;
      }
    };
  }

  /**
   * @return a proxy of {@link ReadOnlyContext} object. This solution is preferred to {@link InjectorObjectFactory}
   *         because the injected field ensure thread-safe behavior.
   */
  private Object createReadOnlyContextProxy() {
    return ProxyFactory.proxy(new ObjectFactory() {
      public ReadOnlyContext create() {
        return Context.get();
      }
    }, ReadOnlyContext.class);
  }

  public Injector build() {
    // first initialize the map
    initMap();
    return injector = new Injector(Collections.unmodifiableMap(map));
  }

  /**
   * A special type used for lazy object injection only in context of this class.
   */
  static interface InjectorObjectFactory
      extends ObjectFactory {
  };
}
>>>>>>> d9390f978dee356e84a1e71532489c30363c0526
Solution content
/**
 * Copyright Alex Objelean
 */
package ro.isdc.wro.model.group.processor;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ro.isdc.wro.cache.CacheEntry;
import ro.isdc.wro.cache.CacheStrategy;
import ro.isdc.wro.cache.ContentHashEntry;
import ro.isdc.wro.cache.DefaultSynchronizedCacheStrategyDecorator;
import ro.isdc.wro.config.Context;
import ro.isdc.wro.config.ReadOnlyContext;
import ro.isdc.wro.config.jmx.WroConfiguration;
import ro.isdc.wro.manager.WroManager;
import ro.isdc.wro.manager.callback.LifecycleCallbackRegistry;
import ro.isdc.wro.manager.factory.WroManagerFactory;
import ro.isdc.wro.model.factory.DefaultWroModelFactoryDecorator;
import ro.isdc.wro.model.factory.WroModelFactory;
import ro.isdc.wro.model.group.GroupExtractor;
import ro.isdc.wro.model.resource.locator.factory.InjectorAwareResourceLocatorFactoryDecorator;
import ro.isdc.wro.model.resource.locator.factory.ResourceLocatorFactory;
import ro.isdc.wro.model.resource.processor.factory.ProcessorsFactory;
import ro.isdc.wro.model.resource.support.ResourceAuthorizationManager;
import ro.isdc.wro.model.resource.support.hash.HashStrategy;
import ro.isdc.wro.model.resource.support.naming.NamingStrategy;
import ro.isdc.wro.util.LazyInitializer;
import ro.isdc.wro.util.ObjectFactory;
import ro.isdc.wro.util.ProxyFactory;


/**
 * Responsible for building the {@link Injector}. It can build an {@link Injector} without needing a {@link WroManager},
 * but just by providing required dependencies.
 *
 * @author Alex Objelean
 * @since 1.4.3
 * @created 6 Jan 2012
 */
public class InjectorBuilder {
  private static final Logger LOG = LoggerFactory.getLogger(InjectorBuilder.class);

  private final GroupsProcessor groupsProcessor = new GroupsProcessor();
  private final PreProcessorExecutor preProcessorExecutor = new PreProcessorExecutor();
  /**
   * A list of model transformers. Allows manager to mutate the model before it is being parsed and processed.
   */
  private Injector injector;
  /**
   * Mapping of classes to be annotated and the corresponding injected object. TODO: probably replace this map with
   * something like spring ApplicationContext (lightweight IoC).
   */
  private final Map, Object> map = new HashMap, Object>();
  private WroManagerFactory managerFactory;
  private final LazyInitializer locatorFactoryInitializer = new LazyInitializer() {
    @Override
    protected ResourceLocatorFactory initialize() {
      final WroManager manager = managerFactory.create();
      // update manager with new decorated factory
      manager.setResourceLocatorFactory(InjectorAwareResourceLocatorFactoryDecorator.decorate(
          manager.getResourceLocatorFactory(), injector));
      return manager.getResourceLocatorFactory();
    }
  };
  private final LazyInitializer modelFactoryInitializer = new LazyInitializer() {
    @Override
    protected WroModelFactory initialize() {
      final WroManager manager = managerFactory.create();
      // update manager with new decorated factory
      manager.setModelFactory(DefaultWroModelFactoryDecorator.decorate(manager.getModelFactory(),
          manager.getModelTransformers()));
      return manager.getModelFactory();
    }
  };
  /**
   * Ensure the strategy is decorated only once.
   */
  private final LazyInitializer> cacheStrategyInitializer = new LazyInitializer>() {
    @Override
    protected CacheStrategy initialize() {
      final WroManager manager = managerFactory.create();
      // update manager with new decorated strategy
      manager.setCacheStrategy(DefaultSynchronizedCacheStrategyDecorator.decorate(manager.getCacheStrategy()));
      return manager.getCacheStrategy();
    }
  };

  /**
   * Use factory method {@link InjectorBuilder#create(WroManagerFactory)} instead.
   *
   * @VisibleForTesting
   */
  public InjectorBuilder() {
  }

  /**
   * Factory method which uses a managerFactory to initialize injected fields.
   */
  public static InjectorBuilder create(final WroManagerFactory managerFactory) {
    Validate.notNull(managerFactory);
    return new InjectorBuilder(managerFactory);
  }

  public InjectorBuilder(final WroManagerFactory managerFactory) {
    Validate.notNull(managerFactory);
    this.managerFactory = managerFactory;
  }

  private void initMap() {
    map.put(PreProcessorExecutor.class, createPreProcessorExecutorProxy());
    map.put(GroupsProcessor.class, createGroupsProcessorProxy());
    map.put(LifecycleCallbackRegistry.class, createCallbackRegistryProxy());
    map.put(GroupExtractor.class, createGroupExtractorProxy());
    map.put(Injector.class, createInjectorProxy());
    map.put(ResourceLocatorFactory.class, createLocatorFactoryProxy());
    map.put(ProcessorsFactory.class, createProcessorFactoryProxy());
    map.put(WroModelFactory.class, createModelFactoryProxy());
    map.put(NamingStrategy.class, createNamingStrategyProxy());
    map.put(HashStrategy.class, createHashStrategyProxy());
    map.put(ReadOnlyContext.class, createReadOnlyContextProxy());
    map.put(WroConfiguration.class, createConfigProxy());
    map.put(CacheStrategy.class, createCacheStrategyProxy());
    map.put(ResourceAuthorizationManager.class, createResourceAuthorizationManagerProxy());
  }

  private InjectorObjectFactory createConfigProxy() {
    return new InjectorObjectFactory() {
      public WroConfiguration create() {
        LOG.warn("Do not @Inject WroConfiguration. Prefer using @Inject ReadOnlyContext context; (and context.getConfig()).");
        return Context.get().getConfig();
      }
    };
  }

  private InjectorObjectFactory createPreProcessorExecutorProxy() {
    return new InjectorObjectFactory() {
      public PreProcessorExecutor create() {
        injector.inject(preProcessorExecutor);
        return preProcessorExecutor;
      }
    };
  }

  private InjectorObjectFactory createGroupsProcessorProxy() {
    return new InjectorObjectFactory() {
      public GroupsProcessor create() {
        injector.inject(groupsProcessor);
        return groupsProcessor;
      }
    };
  }

  private InjectorObjectFactory createCallbackRegistryProxy() {
    return new InjectorObjectFactory() {
      public LifecycleCallbackRegistry create() {
        final LifecycleCallbackRegistry callbackRegistry = managerFactory.create().getCallbackRegistry();
        injector.inject(callbackRegistry);
        return callbackRegistry;
      }
    };
  }

  private InjectorObjectFactory createInjectorProxy() {
    return new InjectorObjectFactory() {
      public Injector create() {
        return injector;
      }
    };
  }

  private Object createGroupExtractorProxy() {
    return new InjectorObjectFactory() {
      public GroupExtractor create() {
        final GroupExtractor groupExtractor = managerFactory.create().getGroupExtractor();
        injector.inject(groupExtractor);
        return groupExtractor;
      }
    };
  }

  private Object createProcessorFactoryProxy() {
    return new InjectorObjectFactory() {
      public ProcessorsFactory create() {
        return managerFactory.create().getProcessorsFactory();
      }
    };
  }

  private Object createLocatorFactoryProxy() {
    return new InjectorObjectFactory() {
      public ResourceLocatorFactory create() {
        return locatorFactoryInitializer.get();
      }
    };
  }

  private Object createResourceAuthorizationManagerProxy() {
    return new InjectorObjectFactory() {
      public ResourceAuthorizationManager create() {
        return managerFactory.create().getResourceAuthorizationManager();
      }
    };
  }

  private Object createModelFactoryProxy() {
    return new InjectorObjectFactory() {
      public WroModelFactory create() {
        final WroModelFactory modelFactory = modelFactoryInitializer.get();
        injector.inject(modelFactory);
        // final WroModelFactory proxy = ProxyFactory.proxy(modelFactory, WroModelFactory.class).create();
        return modelFactory;
      }
    };
  }

  private Object createNamingStrategyProxy() {
    return new InjectorObjectFactory() {
      public NamingStrategy create() {
        final NamingStrategy namingStrategy = managerFactory.create().getNamingStrategy();
        injector.inject(namingStrategy);
        // final NamingStrategy proxy = new ProxyFactory(namingStrategy, NamingStrategy.class).create();
        return namingStrategy;
      }
    };
  }

  private Object createHashStrategyProxy() {
    return new InjectorObjectFactory() {
      public HashStrategy create() {
        final HashStrategy hashStrategy = managerFactory.create().getHashStrategy();
        injector.inject(hashStrategy);
        return hashStrategy;
      }
    };
  }

  @SuppressWarnings("rawtypes")
  private Object createCacheStrategyProxy() {
    return new InjectorObjectFactory() {
      public CacheStrategy create() {
        final CacheStrategy decorated = cacheStrategyInitializer.get();
        injector.inject(decorated);
        return decorated;
      }
    };
  }

  /**
   * @return a proxy of {@link ReadOnlyContext} object. This solution is preferred to {@link InjectorObjectFactory}
   *         because the injected field ensure thread-safe behavior.
   */
  private Object createReadOnlyContextProxy() {
    return ProxyFactory.proxy(new ObjectFactory() {
      public ReadOnlyContext create() {
        return Context.get();
      }
    }, ReadOnlyContext.class);
  }

  public Injector build() {
    // first initialize the map
    initMap();
    return injector = new Injector(Collections.unmodifiableMap(map));
  }

  /**
   * A special type used for lazy object injection only in context of this class.
   */
  static interface InjectorObjectFactory
      extends ObjectFactory {
  };
}
File
InjectorBuilder.java
Developer's decision
Manual
Kind of conflict
Class declaration
Comment
Import
Package declaration
Chunk
Conflicting content
      try {
  public String processAndMerge(final Group group, final boolean minimize)
<<<<<<< HEAD
package ro.isdc.wro.model.group.processor;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ro.isdc.wro.WroRuntimeException;
import ro.isdc.wro.config.jmx.WroConfiguration;
import ro.isdc.wro.config.support.ContextPropagatingCallable;
import ro.isdc.wro.manager.callback.LifecycleCallbackRegistry;
import ro.isdc.wro.model.group.Group;
import ro.isdc.wro.model.group.Inject;
import ro.isdc.wro.model.resource.Resource;
import ro.isdc.wro.model.resource.locator.factory.ResourceLocatorFactory;
import ro.isdc.wro.model.resource.processor.ResourceProcessor;
import ro.isdc.wro.model.resource.processor.decorator.DefaultProcessorDecorator;
import ro.isdc.wro.model.resource.processor.factory.ProcessorsFactory;
import ro.isdc.wro.model.resource.processor.support.ProcessorsUtils;
import ro.isdc.wro.util.StopWatch;
import ro.isdc.wro.util.WroUtil;


/**
 * TODO: refactor this class. Apply all preProcessor on provided {@link Resource} and returns the result of execution as
 * String.
 * 

* This is useful when you want to preProcess a resource which is not a part of the model (css import use-case). * * @author Alex Objelean */ public class PreProcessorExecutor { private static final Logger LOG = LoggerFactory.getLogger(PreProcessorExecutor.class); @Inject private ResourceLocatorFactory resourceLocatorFactory; @Inject private ProcessorsFactory processorsFactory; @Inject private WroConfiguration config; @Inject private LifecycleCallbackRegistry callbackRegistry; @Inject private Injector injector; /** * Runs the preProcessing in parallel. */ private ExecutorService executor; /** * Apply preProcessors on resources and merge them. * * @param resources * what are the resources to merge. * @param minimize * whether minimize aware processors must be applied or not. * @return preProcessed merged content. */ throws IOException { Validate.notNull(group); callbackRegistry.onBeforeMerge(); try { final List resources = group.getResources(); final StringBuffer result = new StringBuffer(); if (shouldRunInParallel(group.getResources())) { result.append(runInParallel(resources, minimize)); } else { for (final Resource resource : resources) { LOG.debug("\tmerging resource: {}", resource); result.append(applyPreProcessors(resource, minimize)); } } return result.toString(); } finally { callbackRegistry.onAfterMerge(); } } private boolean shouldRunInParallel(final List resources) { final boolean isParallel = config.isParallelPreprocessing(); final int availableProcessors = Runtime.getRuntime().availableProcessors(); return isParallel && resources.size() > 1 && availableProcessors > 1; } /** * runs the pre processors in parallel. * * @return merged and pre processed content. */ private String runInParallel(final List resources, final boolean minimize) throws IOException { LOG.debug("Running preProcessing in Parallel"); final StringBuffer result = new StringBuffer(); final List> callables = new ArrayList>(); for (final Resource resource : resources) { // decorate with ContextPropagatingCallable in order to allow spawn threads to access the Context callables.add(new ContextPropagatingCallable(new Callable() { public String call() throws Exception { LOG.debug("Callable started for resource: {} ...", resource); return applyPreProcessors(resource, minimize); } })); } final ExecutorService exec = getExecutorService(); final List> futures = new ArrayList>(); for (final Callable callable : callables) { futures.add(exec.submit(callable)); } for (final Future future : futures) { result.append(future.get()); } catch (final Exception e) { // propagate original cause final Throwable cause = e.getCause(); if (cause instanceof WroRuntimeException) { throw (WroRuntimeException) cause; } else if (cause instanceof IOException) { throw (IOException) cause; } else { throw new WroRuntimeException("Problem during parallel pre processing", e.getCause()); } } } return result.toString(); } private ExecutorService getExecutorService() { if (executor == null) { // use at most the number of available processors (true parallelism) final int threadPoolSize = Runtime.getRuntime().availableProcessors(); LOG.debug("Parallel thread pool size: {}", threadPoolSize); executor = Executors.newFixedThreadPool(threadPoolSize, WroUtil.createDaemonThreadFactory("parallelPreprocessing")); } return executor; } /** * Apply a list of preprocessors on a resource. * * @param resource * the {@link Resource} on which processors will be applied * @param processors * the list of processor to apply on the resource. */ private String applyPreProcessors(final Resource resource, final boolean minimize) throws IOException { //TODO: apply filtering inside a specialized decorator final Collection processors = ProcessorsUtils.filterProcessorsToApply(minimize, resource.getType(), processorsFactory.getPreProcessors()); LOG.debug("applying preProcessors: {}", processors); String resourceContent = null; try { resourceContent = getResourceContent(resource); } catch (final IOException e) { LOG.debug("Invalid resource found: {}", resource); if (config.isIgnoreMissingResources()) { return StringUtils.EMPTY; } else { LOG.error("Cannot ignore missing resource: {}", resource); throw e; } } if (processors.isEmpty()) { return resourceContent; } Writer writer = null; final StopWatch stopWatch = new StopWatch(); for (final ResourceProcessor processor : processors) { stopWatch.start("Processor: " + processor.getClass().getSimpleName()); callbackRegistry.onBeforePreProcess(); writer = new StringWriter(); final Reader reader = new StringReader(resourceContent); try { //decorate and process decoratePreProcessor(processor).process(resource, reader, writer); //use the outcome for next input resourceContent = writer.toString(); } finally { stopWatch.stop(); callbackRegistry.onAfterPreProcess(); reader.close(); writer.close(); } } LOG.debug(stopWatch.prettyPrint()); return writer.toString(); } /** * Decorates preProcessor with mandatory decorators. */ private ResourceProcessor decoratePreProcessor(final ResourceProcessor processor) { final ResourceProcessor decorated = new DefaultProcessorDecorator(processor); injector.inject(decorated); return decorated; } /** * @return a Reader for the provided resource. * @param resource * {@link Resource} which content to return. * @param resources * the list of all resources processed in this context, used for duplicate resource detection. */ private String getResourceContent(final Resource resource) throws IOException { InputStream is = null; try { is = new BOMInputStream(resourceLocatorFactory.locate(resource.getUri())); final String result = IOUtils.toString(is, config.getEncoding()); if (StringUtils.isEmpty(result)) { LOG.debug("Empty resource detected: {}", resource.getUri()); } return result; } finally { IOUtils.closeQuietly(is); } } ======= package ro.isdc.wro.model.group.processor; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.BOMInputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ro.isdc.wro.WroRuntimeException; import ro.isdc.wro.config.Context; import ro.isdc.wro.config.ReadOnlyContext; import ro.isdc.wro.config.support.ContextPropagatingCallable; import ro.isdc.wro.manager.callback.LifecycleCallbackRegistry; import ro.isdc.wro.model.group.Inject; import ro.isdc.wro.model.resource.Resource; import ro.isdc.wro.model.resource.locator.factory.UriLocatorFactory; import ro.isdc.wro.model.resource.processor.ResourcePreProcessor; import ro.isdc.wro.model.resource.processor.decorator.DefaultProcessorDecorator; import ro.isdc.wro.model.resource.processor.factory.ProcessorsFactory; import ro.isdc.wro.model.resource.processor.support.ProcessorsUtils; import ro.isdc.wro.util.StopWatch; import ro.isdc.wro.util.WroUtil; /** * TODO: refactor this class. Apply all preProcessor on provided {@link Resource} and returns the result of execution as * String. *

* This is useful when you want to preProcess a resource which is not a part of the model (css import use-case). * * @author Alex Objelean */ public class PreProcessorExecutor { private static final Logger LOG = LoggerFactory.getLogger(PreProcessorExecutor.class); @Inject private UriLocatorFactory uriLocatorFactory; @Inject private ProcessorsFactory processorsFactory; @Inject private ReadOnlyContext context; @Inject private LifecycleCallbackRegistry callbackRegistry; @Inject private Injector injector; /** * Runs the preProcessing in parallel. */ private ExecutorService executor; /** * Apply preProcessors on resources and merge them. * * @param resources * what are the resources to merge. * @param minimize * whether minimize aware processors must be applied or not. * @return preProcessed merged content. */ public String processAndMerge(final List resources, final boolean minimize) throws IOException { callbackRegistry.onBeforeMerge(); try { Validate.notNull(resources); LOG.debug("process and merge resources: {}", resources); final StringBuffer result = new StringBuffer(); if (shouldRunInParallel(resources)) { result.append(runInParallel(resources, minimize)); } else { for (final Resource resource : resources) { LOG.debug("\tmerging resource: {}", resource); result.append(applyPreProcessors(resource, minimize)); } } return result.toString(); } finally { callbackRegistry.onAfterMerge(); } } private boolean shouldRunInParallel(final List resources) { final boolean isParallel = context.getConfig().isParallelPreprocessing(); final int availableProcessors = Runtime.getRuntime().availableProcessors(); return isParallel && resources.size() > 1 && availableProcessors > 1; } /** * runs the pre processors in parallel. * * @return merged and pre processed content. */ private String runInParallel(final List resources, final boolean minimize) throws IOException { LOG.debug("Running preProcessing in Parallel"); final StringBuffer result = new StringBuffer(); final List> callables = new ArrayList>(); for (final Resource resource : resources) { // decorate with ContextPropagatingCallable in order to allow spawn threads to access the Context callables.add(new ContextPropagatingCallable(new Callable() { public String call() throws Exception { LOG.debug("Callable started for resource: {} ...", resource); return applyPreProcessors(resource, minimize); } })); } final ExecutorService exec = getExecutorService(); final List> futures = new ArrayList>(); for (final Callable callable : callables) { futures.add(exec.submit(callable)); } for (final Future future : futures) { try { result.append(future.get()); } catch (final Exception e) { // propagate original cause final Throwable cause = e.getCause(); if (cause instanceof WroRuntimeException) { throw (WroRuntimeException) cause; } else if (cause instanceof IOException) { throw (IOException) cause; } else { throw new WroRuntimeException("Problem during parallel pre processing", e.getCause()); } } } return result.toString(); } private ExecutorService getExecutorService() { if (executor == null) { // use at most the number of available processors (true parallelism) final int threadPoolSize = Runtime.getRuntime().availableProcessors(); LOG.debug("Parallel thread pool size: {}", threadPoolSize); executor = Executors.newFixedThreadPool(threadPoolSize, WroUtil.createDaemonThreadFactory("parallelPreprocessing")); } return executor; } /** * Apply a list of preprocessors on a resource. * * @param resource * the {@link Resource} on which processors will be applied * @param processors * the list of processor to apply on the resource. */ private String applyPreProcessors(final Resource resource, final boolean minimize) throws IOException { //TODO: apply filtering inside a specialized decorator final Collection processors = ProcessorsUtils.filterProcessorsToApply(minimize, resource.getType(), processorsFactory.getPreProcessors()); LOG.debug("applying preProcessors: {}", processors); String resourceContent = null; try { resourceContent = getResourceContent(resource); } catch (final IOException e) { LOG.debug("Invalid resource found: {}", resource); if (Context.get().getConfig().isIgnoreMissingResources()) { return StringUtils.EMPTY; } else { LOG.error("Cannot ignore missing resource: {}", resource); throw e; } } if (processors.isEmpty()) { return resourceContent; } Writer writer = null; final StopWatch stopWatch = new StopWatch(); for (final ResourcePreProcessor processor : processors) { stopWatch.start("Processor: " + processor.getClass().getSimpleName()); callbackRegistry.onBeforePreProcess(); writer = new StringWriter(); final Reader reader = new StringReader(resourceContent); try { //decorate and process decoratePreProcessor(processor).process(resource, reader, writer); //use the outcome for next input resourceContent = writer.toString(); } finally { stopWatch.stop(); callbackRegistry.onAfterPreProcess(); reader.close(); writer.close(); } } LOG.debug(stopWatch.prettyPrint()); return writer.toString(); } /** * Decorates preProcessor with mandatory decorators. */ private ResourcePreProcessor decoratePreProcessor(final ResourcePreProcessor processor) { final ResourcePreProcessor decorated = new DefaultProcessorDecorator(processor); injector.inject(decorated); return decorated; } /** * @return a Reader for the provided resource. * @param resource * {@link Resource} which content to return. * @param resources * the list of all resources processed in this context, used for duplicate resource detection. */ private String getResourceContent(final Resource resource) throws IOException { InputStream is = null; try { is = new BOMInputStream(uriLocatorFactory.locate(resource.getUri())); final String result = IOUtils.toString(is, context.getConfig().getEncoding()); if (StringUtils.isEmpty(result)) { LOG.debug("Empty resource detected: {}", resource.getUri()); } return result; } finally { IOUtils.closeQuietly(is); } } >>>>>>> d9390f978dee356e84a1e71532489c30363c0526 }

Solution content
package ro.isdc.wro.model.group.processor;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ro.isdc.wro.WroRuntimeException;
import ro.isdc.wro.config.ReadOnlyContext;
import ro.isdc.wro.config.support.ContextPropagatingCallable;
import ro.isdc.wro.manager.callback.LifecycleCallbackRegistry;
import ro.isdc.wro.model.group.Group;
import ro.isdc.wro.model.group.Inject;
import ro.isdc.wro.model.resource.Resource;
import ro.isdc.wro.model.resource.locator.factory.ResourceLocatorFactory;
import ro.isdc.wro.model.resource.processor.ResourceProcessor;
import ro.isdc.wro.model.resource.processor.decorator.DefaultProcessorDecorator;
import ro.isdc.wro.model.resource.processor.factory.ProcessorsFactory;
import ro.isdc.wro.model.resource.processor.support.ProcessorsUtils;
import ro.isdc.wro.util.StopWatch;
import ro.isdc.wro.util.WroUtil;


/**
 * TODO: refactor this class. Apply all preProcessor on provided {@link Resource} and returns the result of execution as
 * String.
 * 

* This is useful when you want to preProcess a resource which is not a part of the model (css import use-case). * * @author Alex Objelean */ public class PreProcessorExecutor { private static final Logger LOG = LoggerFactory.getLogger(PreProcessorExecutor.class); @Inject private ResourceLocatorFactory resourceLocatorFactory; @Inject private ProcessorsFactory processorsFactory; @Inject private ReadOnlyContext context; @Inject private LifecycleCallbackRegistry callbackRegistry; @Inject private Injector injector; /** * Runs the preProcessing in parallel. */ private ExecutorService executor; /** * Apply preProcessors on resources and merge them. * * @param resources * what are the resources to merge. * @param minimize * whether minimize aware processors must be applied or not. * @return preProcessed merged content. */ public String processAndMerge(final Group group, final boolean minimize) throws IOException { Validate.notNull(group); callbackRegistry.onBeforeMerge(); try { final List resources = group.getResources(); final StringBuffer result = new StringBuffer(); if (shouldRunInParallel(group.getResources())) { result.append(runInParallel(resources, minimize)); } else { for (final Resource resource : resources) { LOG.debug("\tmerging resource: {}", resource); result.append(applyPreProcessors(resource, minimize)); } } return result.toString(); } finally { callbackRegistry.onAfterMerge(); } } private boolean shouldRunInParallel(final List resources) { final boolean isParallel = context.getConfig().isParallelPreprocessing(); final int availableProcessors = Runtime.getRuntime().availableProcessors(); return isParallel && resources.size() > 1 && availableProcessors > 1; } /** * runs the pre processors in parallel. * * @return merged and pre processed content. */ private String runInParallel(final List resources, final boolean minimize) throws IOException { LOG.debug("Running preProcessing in Parallel"); final StringBuffer result = new StringBuffer(); final List> callables = new ArrayList>(); for (final Resource resource : resources) { // decorate with ContextPropagatingCallable in order to allow spawn threads to access the Context callables.add(new ContextPropagatingCallable(new Callable() { public String call() throws Exception { LOG.debug("Callable started for resource: {} ...", resource); return applyPreProcessors(resource, minimize); } })); } final ExecutorService exec = getExecutorService(); final List> futures = new ArrayList>(); for (final Callable callable : callables) { futures.add(exec.submit(callable)); } for (final Future future : futures) { try { result.append(future.get()); } catch (final Exception e) { // propagate original cause final Throwable cause = e.getCause(); if (cause instanceof WroRuntimeException) { throw (WroRuntimeException) cause; } else if (cause instanceof IOException) { throw (IOException) cause; } else { throw new WroRuntimeException("Problem during parallel pre processing", e.getCause()); } } } return result.toString(); } private ExecutorService getExecutorService() { if (executor == null) { // use at most the number of available processors (true parallelism) final int threadPoolSize = Runtime.getRuntime().availableProcessors(); LOG.debug("Parallel thread pool size: {}", threadPoolSize); executor = Executors.newFixedThreadPool(threadPoolSize, WroUtil.createDaemonThreadFactory("parallelPreprocessing")); } return executor; } /** * Apply a list of preprocessors on a resource. * * @param resource * the {@link Resource} on which processors will be applied * @param processors * the list of processor to apply on the resource. */ private String applyPreProcessors(final Resource resource, final boolean minimize) throws IOException { //TODO: apply filtering inside a specialized decorator final Collection processors = ProcessorsUtils.filterProcessorsToApply(minimize, resource.getType(), processorsFactory.getPreProcessors()); LOG.debug("applying preProcessors: {}", processors); String resourceContent = null; try { resourceContent = getResourceContent(resource); } catch (final IOException e) { LOG.debug("Invalid resource found: {}", resource); if (context.getConfig().isIgnoreMissingResources()) { return StringUtils.EMPTY; } else { LOG.error("Cannot ignore missing resource: {}", resource); throw e; } } if (processors.isEmpty()) { return resourceContent; } Writer writer = null; final StopWatch stopWatch = new StopWatch(); for (final ResourceProcessor processor : processors) { stopWatch.start("Processor: " + processor.getClass().getSimpleName()); callbackRegistry.onBeforePreProcess(); writer = new StringWriter(); final Reader reader = new StringReader(resourceContent); try { //decorate and process decoratePreProcessor(processor).process(resource, reader, writer); //use the outcome for next input resourceContent = writer.toString(); } finally { stopWatch.stop(); callbackRegistry.onAfterPreProcess(); reader.close(); writer.close(); } } LOG.debug(stopWatch.prettyPrint()); return writer.toString(); } /** * Decorates preProcessor with mandatory decorators. */ private ResourceProcessor decoratePreProcessor(final ResourceProcessor processor) { final ResourceProcessor decorated = new DefaultProcessorDecorator(processor); injector.inject(decorated); return decorated; } /** * @return a Reader for the provided resource. * @param resource * {@link Resource} which content to return. * @param resources * the list of all resources processed in this context, used for duplicate resource detection. */ private String getResourceContent(final Resource resource) throws IOException { InputStream is = null; try { is = new BOMInputStream(resourceLocatorFactory.locate(resource.getUri())); final String result = IOUtils.toString(is, context.getConfig().getEncoding()); if (StringUtils.isEmpty(result)) { LOG.debug("Empty resource detected: {}", resource.getUri()); } return result; } finally { IOUtils.closeQuietly(is); } } }

File
PreProcessorExecutor.java
Developer's decision
Manual
Kind of conflict
Annotation
Attribute
Comment
Import
Method declaration
Method invocation
Package declaration
Chunk
Conflicting content
<<<<<<< HEAD
/*
 * Copyright (c) 2008. All rights reserved.
 */
package ro.isdc.wro.model.resource.locator.support;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ro.isdc.wro.config.Context;
import ro.isdc.wro.http.support.RedirectedStreamServletResponseWrapper;
import ro.isdc.wro.model.resource.locator.ResourceLocator;
import ro.isdc.wro.util.WroUtil;


/**
 * Responsible to locate a context relative resource. It attempts to locate the resource using {@link RequestDispatcher}
 * . If the dispatcher fails, it will fallback resource retrieval to a http call using {@link UrlUriLocator}.
 * 
 * @author Alex Objelean
 */
public class DispatcherStreamLocator {
  private static final Logger LOG = LoggerFactory.getLogger(DispatcherStreamLocator.class);
  /**
   * Attribute indicating that the request is included from within a wro request cycle. This is required to prevent
   * {@link StackOverflowError}.
   * 
   * @VisibleForTesting
   */
  public static final String ATTRIBUTE_INCLUDED_BY_DISPATCHER = DispatcherStreamLocator.class.getName()
      + ".included_with_dispatcher";

  /**
   * When using JBoss Portal and it has some funny quirks...actually a portal application have several small web
   * application behind it. So when it intercepts a requests for portal then it start bombing the the application behind
   * the portal with multiple threads (web requests) that are combined with threads for wro4j.
   * 
   * @return a valid stream for required location. This method will never return a null.
   * @throws IOException
   *           if the stream cannot be located at the specified location.
   */
  public InputStream getInputStream(final HttpServletRequest request, final HttpServletResponse response,
      final String location)
      throws IOException {
    Validate.notNull(request);
    Validate.notNull(response);
    
    // where to write the bytes of the stream
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    boolean warnOnEmptyStream = false;

    // preserve context, in case it is unset during dispatching
    final Context originalContext = Context.get();
    try {
      final RequestDispatcher dispatcher = request.getRequestDispatcher(location);
      if (dispatcher != null) {
        // Wrap request
        final ServletRequest servletRequest = getWrappedServletRequest(request, location);
        // Wrap response
        final ServletResponse servletResponse = new RedirectedStreamServletResponseWrapper(os, response);
        LOG.debug("dispatching request to location: {}", location);
        // use dispatcher
        dispatcher.include(servletRequest, servletResponse);
        warnOnEmptyStream = true;
        // force flushing - the content will be written to
        // BytArrayOutputStream. Otherwise exactly 32K of data will be
        // written.
        servletResponse.getWriter().flush();
        os.close();
      }
    } catch (final Exception e) {
      LOG.debug("[FAIL] Error while dispatching the request for location {}", location);
      // Not only servletException can be thrown, also dispatch.include can throw NPE when the scheduler runs outside
      // of the request cycle, thus connection is unavailable. This is caused mostly when invalid resources are
      // included.
      return locateExternal(request, location);
    }
    try {
      //fallback to external resource locator if the dispatcher is empty
      if (os.size() == 0) {
        return locateExternal(request, location);
      }
    } finally {
      if (warnOnEmptyStream && os.size() == 0) {
        LOG.debug("Wrong or empty resource with location: {}", location);
      }
      // Put the context back
      if (!Context.isContextSet()) {
        Context.set(originalContext);
      }
    }
    return new ByteArrayInputStream(os.toByteArray());
  }

  private InputStream locateExternal(final HttpServletRequest request, final String location)
      throws IOException {
    // happens when dynamic servlet context relative resources are included outside of the request cycle (inside
    // the thread responsible for refreshing resources)
    // Returns the part URL from the protocol name up to the query string and contextPath.
    final String servletContextPath = request.getRequestURL().toString().replace(request.getServletPath(), "");
    final String absolutePath = servletContextPath + location;
    return createExternalResourceLocator(absolutePath).getInputStream();
  }

  /**
   * Used to locate external resources. No wildcard handling is required.
   * 
   * @VisibleForTesting
   */
  ResourceLocator createExternalResourceLocator(final String location) {
    return new UrlResourceLocator(location) {
      /**
       * No wildcard handling is required.
       */
      @Override
      public boolean isEnableWildcards() {
        return false;
      };
    };
  }
  
  /**
   * Build a wrapped servlet request which will be used for dispatching.
   */
  private ServletRequest getWrappedServletRequest(final HttpServletRequest request, final String location) {
    final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(request) {
      @Override
      public String getRequestURI() {
        return getContextPath() + location;
      }

      @Override
      public String getPathInfo() {
        return WroUtil.getPathInfoFromLocation(this, location);
      }

      @Override
      public String getServletPath() {
        return WroUtil.getServletPathFromLocation(this, location);
      }
    };
    // add an attribute to mark this request as included from wro
    wrappedRequest.setAttribute(ATTRIBUTE_INCLUDED_BY_DISPATCHER, Boolean.TRUE);
    return wrappedRequest;
  }

  /**
   * @param request
   * @return true if the request is included from within wro request cycle.
   */
  public static boolean isIncludedRequest(final HttpServletRequest request) {
    Validate.notNull(request);
    return request.getAttribute(ATTRIBUTE_INCLUDED_BY_DISPATCHER) != null;
  }
=======
/*
 * Copyright (c) 2008. All rights reserved.
 */
package ro.isdc.wro.model.resource.locator.support;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ro.isdc.wro.config.Context;
import ro.isdc.wro.http.support.RedirectedStreamServletResponseWrapper;
import ro.isdc.wro.model.group.Inject;
import ro.isdc.wro.model.group.processor.Injector;
import ro.isdc.wro.model.resource.locator.UriLocator;
import ro.isdc.wro.model.resource.locator.UrlUriLocator;
import ro.isdc.wro.util.WroUtil;


/**
 * Responsible to locate a context relative resource. Attempts to locate the resource using {@link RequestDispatcher} .
 * If the dispatcher fails, it will fallback resource retrieval to a http call using {@link UrlUriLocator}.
 *
 * @author Alex Objelean
 */
public class DispatcherStreamLocator {
  private static final Logger LOG = LoggerFactory.getLogger(DispatcherStreamLocator.class);
  @Inject
  private Injector injector;
  /**
   * Attribute indicating that the request is included from within a wro request cycle. This is required to prevent
   * {@link StackOverflowError}.
   *
   * @VisibleForTesting
   */
  public static final String ATTRIBUTE_INCLUDED_BY_DISPATCHER = DispatcherStreamLocator.class.getName()
      + ".included_with_dispatcher";

  /**
   * When using JBoss Portal and it has some funny quirks...actually a portal application have several small web
   * application behind it. So when it intercepts a requests for portal then it start bombing the the application behind
   * the portal with multiple threads (web requests) that are combined with threads for wro4j.
   *
   * @return a valid stream for required location. This method will never return a null.
   * @throws IOException
   *           if the stream cannot be located at the specified location.
   */
  public InputStream getInputStream(final HttpServletRequest request, final HttpServletResponse response,
      final String location)
      throws IOException {
    Validate.notNull(request);
    Validate.notNull(response);

    // where to write the bytes of the stream
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    boolean warnOnEmptyStream = false;

    //TODO check if this is required anymore
    // preserve context, in case it is unset during dispatching
    final Context originalContext = Context.get();
    try {
      final RequestDispatcher dispatcher = request.getRequestDispatcher(location);
      if (dispatcher != null) {
        // Wrap request
        final ServletRequest servletRequest = getWrappedServletRequest(request, location);
        // Wrap response
        final ServletResponse servletResponse = new RedirectedStreamServletResponseWrapper(os, response);
        LOG.debug("dispatching request to location: {}", location);
        // use dispatcher
        dispatcher.include(servletRequest, servletResponse);
        warnOnEmptyStream = true;
        // force flushing - the content will be written to
        // BytArrayOutputStream. Otherwise exactly 32K of data will be
        // written.
        servletResponse.getWriter().flush();
        os.close();
      }
    } catch (final Exception e) {
      LOG.error("Error while dispatching to location: " + location, e);
      LOG.debug("[FAIL] Error while dispatching the request for location {}", location);
      // Not only servletException can be thrown, also dispatch.include can throw NPE when the scheduler runs outside
      // of the request cycle, thus connection is unavailable. This is caused mostly when invalid resources are
      // included.
      return locateExternal(request, location);
    }
    try {
      // fallback to external resource locator if the dispatcher is empty
      if (os.size() == 0) {
        return locateExternal(request, location);
      }
    } finally {
      if (warnOnEmptyStream && os.size() == 0) {
        LOG.debug("Wrong or empty resource with location: {}", location);
      }
      //TODO probably not required anymore
      // Put the context back
      if (!Context.isContextSet()) {
        Context.set(originalContext);
      }
    }
    return new ByteArrayInputStream(os.toByteArray());
  }

  private InputStream locateExternal(final HttpServletRequest request, final String location)
      throws IOException {
    // happens when dynamic servlet context relative resources are included outside of the request cycle (inside
    // the thread responsible for refreshing resources)
    // Returns the part URL from the protocol name up to the query string and contextPath.
    final String servletContextPath = request.getRequestURL().toString().replace(request.getServletPath(), "");
    final String absolutePath = servletContextPath + location;
    return createExternalResourceLocator().locate(absolutePath);
  }

  /**
   * @return the {@link UriLocator} responsible for locating resources when dispatcher fails. No wildcard handling is
   *         required.
   * @VisibleForTesting
   */
  UriLocator createExternalResourceLocator() {
    final UriLocator locator = new UrlUriLocator() {
      @Override
      public boolean isEnableWildcards() {
        return false;
      };
    };
    injector.inject(locator);
    return locator;
  }

  /**
   * Build a wrapped servlet request which will be used for dispatching.
   */
  private ServletRequest getWrappedServletRequest(final HttpServletRequest request, final String location) {
    final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(request) {
      @Override
      public String getRequestURI() {
        return getContextPath() + location;
      }

      @Override
      public String getPathInfo() {
        return WroUtil.getPathInfoFromLocation(this, location);
      }

      @Override
      public String getServletPath() {
        return WroUtil.getServletPathFromLocation(this, location);
      }
    };
    // add an attribute to mark this request as included from wro
    wrappedRequest.setAttribute(ATTRIBUTE_INCLUDED_BY_DISPATCHER, Boolean.TRUE);
    return wrappedRequest;
  }

  /**
   * @param request
   * @return true if the request is included from within wro request cycle.
   */
  public static boolean isIncludedRequest(final HttpServletRequest request) {
    Validate.notNull(request);
    return request.getAttribute(ATTRIBUTE_INCLUDED_BY_DISPATCHER) != null;
  }
>>>>>>> d9390f978dee356e84a1e71532489c30363c0526
}
Solution content
import ro.isdc.wro.util.WroUtil;
import ro.isdc.wro.model.resource.locator.ResourceLocator;
/*
 * Copyright (c) 2008. All rights reserved.
 */
package ro.isdc.wro.model.resource.locator.support;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ro.isdc.wro.config.Context;
import ro.isdc.wro.http.support.RedirectedStreamServletResponseWrapper;
import ro.isdc.wro.model.group.Inject;
import ro.isdc.wro.model.group.processor.Injector;


/**
 * Responsible to locate a context relative resource. It attempts to locate the resource using {@link RequestDispatcher}
 * . If the dispatcher fails, it will fallback resource retrieval to a http call using {@link UrlUriLocator}.
 *
 * @author Alex Objelean
 */
public class DispatcherStreamLocator {
  private static final Logger LOG = LoggerFactory.getLogger(DispatcherStreamLocator.class);
  @Inject
  private Injector injector;
  /**
   * Attribute indicating that the request is included from within a wro request cycle. This is required to prevent
   * {@link StackOverflowError}.
   *
   * @VisibleForTesting
   */
  public static final String ATTRIBUTE_INCLUDED_BY_DISPATCHER = DispatcherStreamLocator.class.getName()
      + ".included_with_dispatcher";

  /**
   * When using JBoss Portal and it has some funny quirks...actually a portal application have several small web
   * application behind it. So when it intercepts a requests for portal then it start bombing the the application behind
   * the portal with multiple threads (web requests) that are combined with threads for wro4j.
   *
   * @return a valid stream for required location. This method will never return a null.
   * @throws IOException
   *           if the stream cannot be located at the specified location.
   */
  public InputStream getInputStream(final HttpServletRequest request, final HttpServletResponse response,
      final String location)
      throws IOException {
    Validate.notNull(request);
    Validate.notNull(response);

    // where to write the bytes of the stream
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    boolean warnOnEmptyStream = false;

    //TODO check if this is required anymore
    // preserve context, in case it is unset during dispatching
    final Context originalContext = Context.get();
    try {
      final RequestDispatcher dispatcher = request.getRequestDispatcher(location);
      if (dispatcher != null) {
        // Wrap request
        final ServletRequest servletRequest = getWrappedServletRequest(request, location);
        // Wrap response
        final ServletResponse servletResponse = new RedirectedStreamServletResponseWrapper(os, response);
        LOG.debug("dispatching request to location: {}", location);
        // use dispatcher
        dispatcher.include(servletRequest, servletResponse);
        warnOnEmptyStream = true;
        // force flushing - the content will be written to
        // BytArrayOutputStream. Otherwise exactly 32K of data will be
        // written.
        servletResponse.getWriter().flush();
        os.close();
      }
    } catch (final Exception e) {
      LOG.error("Error while dispatching to location: " + location, e);
      LOG.debug("[FAIL] Error while dispatching the request for location {}", location);
      // Not only servletException can be thrown, also dispatch.include can throw NPE when the scheduler runs outside
      // of the request cycle, thus connection is unavailable. This is caused mostly when invalid resources are
      // included.
      return locateExternal(request, location);
    }
    try {
      //fallback to external resource locator if the dispatcher is empty
      if (os.size() == 0) {
        return locateExternal(request, location);
      }
    } finally {
      if (warnOnEmptyStream && os.size() == 0) {
        LOG.debug("Wrong or empty resource with location: {}", location);
      }
      //TODO probably not required anymore
      // Put the context back
      if (!Context.isContextSet()) {
        Context.set(originalContext);
      }
    }
    return new ByteArrayInputStream(os.toByteArray());
  }

  private InputStream locateExternal(final HttpServletRequest request, final String location)
      throws IOException {
    // happens when dynamic servlet context relative resources are included outside of the request cycle (inside
    // the thread responsible for refreshing resources)
    // Returns the part URL from the protocol name up to the query string and contextPath.
    final String servletContextPath = request.getRequestURL().toString().replace(request.getServletPath(), "");
    final String absolutePath = servletContextPath + location;
    return createExternalResourceLocator(absolutePath).getInputStream();
  }

  /**
   * Used to locate external resources. No wildcard handling is required.
   *
   * @VisibleForTesting
   */
  ResourceLocator createExternalResourceLocator(final String location) {
    final ResourceLocator locator = new UrlResourceLocator(location) {
      /**
       * No wildcard handling is required.
       */
      @Override
      public boolean isEnableWildcards() {
        return false;
      };
    };
    injector.inject(locator);
    return locator;
  }

  /**
   * Build a wrapped servlet request which will be used for dispatching.
   */
  private ServletRequest getWrappedServletRequest(final HttpServletRequest request, final String location) {
    final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(request) {
      @Override
      public String getRequestURI() {
        return getContextPath() + location;
      }

      @Override
      public String getPathInfo() {
        return WroUtil.getPathInfoFromLocation(this, location);
      }

      @Override
      public String getServletPath() {
        return WroUtil.getServletPathFromLocation(this, location);
      }
    };
    // add an attribute to mark this request as included from wro
    wrappedRequest.setAttribute(ATTRIBUTE_INCLUDED_BY_DISPATCHER, Boolean.TRUE);
    return wrappedRequest;
  }

  /**
   * @param request
   * @return true if the request is included from within wro request cycle.
   */
  public static boolean isIncludedRequest(final HttpServletRequest request) {
    Validate.notNull(request);
    return request.getAttribute(ATTRIBUTE_INCLUDED_BY_DISPATCHER) != null;
  }
}
File
DispatcherStreamLocator.java
Developer's decision
Manual
Kind of conflict
Annotation
Attribute
Comment
Import
Method declaration
Method invocation
Package declaration
Chunk
Conflicting content
   */
   */
<<<<<<< HEAD:wro4j-core/src/main/java/ro/isdc/wro/model/resource/locator/support/ServletContextResourceLocator.java
/**
 * Copyright Alex Objelean
 */
package ro.isdc.wro.model.resource.locator.support;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ro.isdc.wro.config.ReadOnlyContext;
import ro.isdc.wro.model.group.Inject;
import ro.isdc.wro.model.resource.locator.ResourceLocator;
import ro.isdc.wro.model.transformer.WildcardExpanderModelTransformer.NoMoreAttemptsIOException;
import ro.isdc.wro.util.StringUtils;


/**
 * {@link org.springframework.core.io.Resource} implementation for {@link javax.servlet.ServletContext} resources,
 * interpreting relative paths within the web application root directory.
 * 
 * @author Alex Objelean, Ivar Conradi Østhus
 * @created Created on Nov 10, 2008, Updated on March 2, 2012
 */
public class ServletContextResourceLocator
    extends AbstractResourceLocator {
  private static final Logger LOG = LoggerFactory.getLogger(ServletContextResourceLocator.class);
  /**
   * Alias used to register this locator with {@link LocatorProvider}. 
   */
  public static final String ALIAS = "servletContext";
  /**
   * Same as default Alias (exist for explicit configuration). Uses DISPATCHER_FIRST strategy. Meaning that, for
   * example, a jsp resource will be served in its final state (processed by servlet container), rather than in its raw
   * variant.
   */
  public static final String ALIAS_DISPATCHER_FIRST = "servletContext.DISPATCHER_FIRST";
  /**
   * Uses SERVLET_CONTEXT_FIRST strategy, meaning that, for example, a jsp will be served with its raw content, instead
   * of processed by container.
   */
  public static final String ALIAS_SERVLET_CONTEXT_FIRST = "servletContext.SERVLET_CONTEXT_FIRST";
  
  /**
   * Prefix for url resources.
   */
  public static final String PREFIX = "/";
  private final ServletContext servletContext;
  private final String path;
  /**
   * Locates a stream using request dispatcher.
  private final DispatcherStreamLocator dispatcherStreamLocator = new DispatcherStreamLocator();  
  /**
   * Determines the order of dispatcher resource locator and servlet context based resource locator.
   */
  private LocatorStrategy locatorStrategy = LocatorStrategy.DISPATCHER_FIRST;
  @Inject
  private ReadOnlyContext context;
  /**
   * Available LocatorStrategies. DISPATCHER_FIRST is default option. This means this UriLocator will first try to
   * locate resource via the dispatcher stream locator. This will include dynamic resources produces by servlet's or
   * JSP's. If the specified resource cannot be found with the dispatcherStreamLocator the implementation will try to
   * use the ServletContext to locate the resource. SERVLET_CONTEXT_FIRST is a alternative approach where we will first
   * try to locate the resource VIA the ServletContext first, and then use the dispatcheStreamLocator if not found. In
   * some cases, where you do not rely on dynamic resources this can be a more reliable and a more efficient approach.
   */
  public static enum LocatorStrategy {
    DISPATCHER_FIRST, SERVLET_CONTEXT_FIRST
  }
  
  /**
   * Sets the locator strategy to use.
  public ResourceLocator setLocatorStrategy(final LocatorStrategy locatorStrategy) {
    Validate.notNull(locatorStrategy);
    this.locatorStrategy = locatorStrategy;
    return this;
  }
  
  
  public ServletContextResourceLocator(final ServletContext servletContext, final String path) {
    Validate.notNull(path);
    // allow null servletContext and prefer throwing IOException if null value is set.
    this.servletContext = servletContext;
    String pathToUse = StringUtils.cleanPath(path);
    if (!pathToUse.startsWith(PREFIX)) {
      pathToUse = PREFIX + pathToUse;
    }
    this.path = pathToUse;
  }
  
  /**
   * {@inheritDoc}
   */
  public InputStream getInputStream()
      throws IOException {
    if (servletContext == null) {
      throw new IOException("Cannot get stream for the following path: " + path
          + ", because no servletContext is detected.");
    }
    LOG.debug("locating uri: " + path);
    try {
      if (getWildcardStreamLocator().hasWildcard(path)) {
        final String fullPath = FilenameUtils.getFullPath(path);
        final String realPath = servletContext.getRealPath(fullPath);
        if (realPath == null) {
          final String message = "[FAIL] Could not determine realPath for resource: " + path;
          LOG.debug(message);
          throw new IOException(message);
        }
        return getWildcardStreamLocator().locateStream(path, new File(realPath));
      }
    } catch (final IOException e) {
      /**
       * This is a special case when no more attempts are required, since the required computation was achieved
       * successfully. This solves the following issue.
       * 

* The problem was that in some situations, when the dispatcherStreamLocator was used to locate resources * containing wildcard, the following message was printed to the console: * SEVERE: Servlet.service() for servlet default threw exception * java.io.FileNotFoundException. */ if (e instanceof NoMoreAttemptsIOException) { throw e; } LOG.warn("[FAIL] localize the stream containing wildcard. Original error message: '{}'", e.getMessage() + "\".\n Trying to locate the stream without the wildcard."); } InputStream inputStream = null; try { if (locatorStrategy.equals(LocatorStrategy.DISPATCHER_FIRST)) { inputStream = dispatcherFirstStreamLocator(path); } else { inputStream = servletContextFirstStreamLocator(path); } validateInputStreamIsNotNull(inputStream, path); return inputStream; } catch (IOException e) { LOG.debug("Wrong or empty resource with location: {}", path); throw e; } } /** * {@inheritDoc} */ @Override public ResourceLocator createRelative(final String relativePath) throws IOException { final String folder = FilenameUtils.getFullPath(path); // remove '../' & normalize the path. final String pathToUse = StringUtils.cleanPath(folder + relativePath); return new ServletContextResourceLocator(servletContext, pathToUse); } private InputStream servletContextFirstStreamLocator(final String uri) throws IOException { try { return servletContextBasedStreamLocator(uri); } catch (final IOException e) { LOG.debug("retrieving servletContext stream for uri: {}", uri); return dispatcherBasedStreamLocator(uri); } } private InputStream dispatcherFirstStreamLocator(final String uri) throws IOException { try { return dispatcherBasedStreamLocator(uri); } catch (final IOException e) { LOG.debug("retrieving servletContext stream for uri: {}", uri); return servletContextBasedStreamLocator(uri); } } private InputStream dispatcherBasedStreamLocator(final String uri) throws IOException { final HttpServletRequest request = context.getRequest(); final HttpServletResponse response = context.getResponse(); // The order of stream retrieval is important. We are trying to get the dispatcherStreamLocator in order to handle // jsp resources (if such exist). Switching the order would cause jsp to not be interpreted by the container. return dispatcherStreamLocator.getInputStream(request, response, uri); } private InputStream servletContextBasedStreamLocator(final String uri) throws IOException { final ServletContext servletContext = context.getServletContext(); return servletContext.getResourceAsStream(uri); } private void validateInputStreamIsNotNull(final InputStream inputStream, final String uri) throws IOException { if (inputStream == null) { ======= /* * Copyright (c) 2008. All rights reserved. */ package ro.isdc.wro.model.resource.locator; import java.io.File; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ro.isdc.wro.config.ReadOnlyContext; import ro.isdc.wro.model.group.Inject; import ro.isdc.wro.model.group.processor.Injector; import ro.isdc.wro.model.resource.locator.support.DispatcherStreamLocator; import ro.isdc.wro.model.resource.locator.support.LocatorProvider; import ro.isdc.wro.model.resource.locator.wildcard.WildcardUriLocatorSupport; import ro.isdc.wro.model.transformer.WildcardExpanderModelTransformer.NoMoreAttemptsIOException; import ro.isdc.wro.util.WroUtil; /** * UriLocator capable to read the resources relative to servlet context. The resource reader will attempt to locate a * physic resource under the servlet context and if the resource does not exist, will try to use requestDispatcher. This * kind of resources will be accepted if their prefix is '/'. * * @author Alex Objelean, Ivar Conradi Østhus * @created Created on Nov 10, 2008, Updated on March 2, 2012 */ public class ServletContextUriLocator extends WildcardUriLocatorSupport { private static final Logger LOG = LoggerFactory.getLogger(ServletContextUriLocator.class); /** * Alias used to register this locator with {@link LocatorProvider}. */ public static final String ALIAS = "servletContext"; /** * Same as default Alias (exist for explicit configuration). Uses DISPATCHER_FIRST strategy. Meaning that, for * example, a jsp resource will be served in its final state (processed by servlet container), rather than in its raw * variant. */ public static final String ALIAS_DISPATCHER_FIRST = "servletContext.DISPATCHER_FIRST"; /** * Uses SERVLET_CONTEXT_FIRST strategy, meaning that, for example, a jsp will be served with its raw content, instead * of processed by container. */ public static final String ALIAS_SERVLET_CONTEXT_FIRST = "servletContext.SERVLET_CONTEXT_FIRST"; /** * Prefix for url resources. */ public static final String PREFIX = "/"; /** * Constant for WEB-INF folder. */ private static final String PROTECTED_PREFIX = "/WEB-INF/"; @Inject private Injector injector; /** * Locates a stream using request dispatcher. */ private DispatcherStreamLocator dispatcherStreamLocator; /** * Determines the order of dispatcher resource locator and servlet context based resource locator. */ private LocatorStrategy locatorStrategy = LocatorStrategy.DISPATCHER_FIRST; @Inject private ReadOnlyContext context; /** * Available LocatorStrategies. DISPATCHER_FIRST is default option. This means this UriLocator will first try to * locate resource via the dispatcher stream locator. This will include dynamic resources produces by servlet's or * JSP's. If the specified resource cannot be found with the dispatcherStreamLocator the implementation will try to * use the ServletContext to locate the resource. SERVLET_CONTEXT_FIRST is a alternative approach where we will first * try to locate the resource VIA the ServletContext first, and then use the dispatcheStreamLocator if not found. In * some cases, where you do not rely on dynamic resources this can be a more reliable and a more efficient approach. */ public static enum LocatorStrategy { DISPATCHER_FIRST, SERVLET_CONTEXT_FIRST } /** * Sets the locator strategy to use. */ public ServletContextUriLocator setLocatorStrategy(final LocatorStrategy locatorStrategy) { Validate.notNull(locatorStrategy); this.locatorStrategy = locatorStrategy; return this; } /** * {@inheritDoc} */ public boolean accept(final String uri) { return isValid(uri); } /** * Check if a uri is a servletContext resource. * * @param uri * to check. * @return true if the uri is a servletContext resource. */ public static boolean isValid(final String uri) { return uri.trim().startsWith(PREFIX); } /** * Check If the uri of the resource is protected: it cannot be accessed by accessing the url directly (WEB-INF * folder). * * @param uri * the uri to check. * @return true if the uri is a protected resource. */ public static boolean isProtectedResource(final String uri) { return WroUtil.startsWithIgnoreCase(uri, PROTECTED_PREFIX); } /** * {@inheritDoc} */ public InputStream locate(final String uri) throws IOException { Validate.notNull(uri, "URI cannot be NULL!"); LOG.debug("locate resource: {}", uri); try { if (getWildcardStreamLocator().hasWildcard(uri)) { final ServletContext servletContext = context.getServletContext(); final String fullPath = FilenameUtils.getFullPath(uri); final String realPath = servletContext.getRealPath(fullPath); if (realPath == null) { final String message = "[FAIL] determine realPath for resource: " + uri; LOG.debug(message); throw new IOException(message); } return getWildcardStreamLocator().locateStream(uri, new File(realPath)); } } catch (final IOException e) { /** * This is a special case when no more attempts are required, since the required computation was achieved * successfully. This solves the following issue. *

* The problem was that in some situations, when the dispatcherStreamLocator was used to locate resources * containing wildcard, the following message was printed to the console: * SEVERE: Servlet.service() for servlet default threw exception * java.io.FileNotFoundException. */ if (e instanceof NoMoreAttemptsIOException) { throw e; } LOG.warn("[FAIL] localize the stream containing wildcard. Original error message: '{}'", e.getMessage() + "\".\n Trying to locate the stream without the wildcard."); } InputStream inputStream = null; try { if (locatorStrategy.equals(LocatorStrategy.DISPATCHER_FIRST)) { inputStream = dispatcherFirstStreamLocator(uri); } else { inputStream = servletContextFirstStreamLocator(uri); } validateInputStreamIsNotNull(inputStream, uri); return inputStream; } catch (final IOException e) { LOG.debug("Wrong or empty resource with location: {}", uri); throw e; } } private InputStream servletContextFirstStreamLocator(final String uri) throws IOException { try { return servletContextBasedStreamLocator(uri); } catch (final IOException e) { LOG.debug("retrieving servletContext stream for uri: {}", uri); return dispatcherBasedStreamLocator(uri); } } private InputStream dispatcherFirstStreamLocator(final String uri) throws IOException { try { return dispatcherBasedStreamLocator(uri); } catch (final IOException e) { LOG.debug("retrieving servletContext stream for uri: {}", uri); return servletContextBasedStreamLocator(uri); } } private InputStream dispatcherBasedStreamLocator(final String uri) throws IOException { final HttpServletRequest request = context.getRequest(); final HttpServletResponse response = context.getResponse(); // The order of stream retrieval is important. We are trying to get the dispatcherStreamLocator in order to handle // jsp resources (if such exist). Switching the order would cause jsp to not be interpreted by the container. return getDispatcherStreamLocator().getInputStream(request, response, uri); } private DispatcherStreamLocator getDispatcherStreamLocator() { if (dispatcherStreamLocator == null) { dispatcherStreamLocator = new DispatcherStreamLocator(); injector.inject(dispatcherStreamLocator); } return dispatcherStreamLocator; } private InputStream servletContextBasedStreamLocator(final String uri) throws IOException { final ServletContext servletContext = context.getServletContext(); return servletContext.getResourceAsStream(uri); } private void validateInputStreamIsNotNull(final InputStream inputStream, final String uri) throws IOException { if (inputStream == null) { >>>>>>> d9390f978dee356e84a1e71532489c30363c0526:wro4j-core/src/main/java/ro/isdc/wro/model/resource/locator/ServletContextUriLocator.java LOG.debug("[FAIL] reading resource from {}", uri); throw new IOException("Exception while reading resource from " + uri); }

Solution content
  /**
/**
 * Copyright Alex Objelean
 */
package ro.isdc.wro.model.resource.locator.support;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ro.isdc.wro.config.ReadOnlyContext;
import ro.isdc.wro.model.group.Inject;
import ro.isdc.wro.model.group.processor.Injector;
import ro.isdc.wro.model.resource.locator.ResourceLocator;
import ro.isdc.wro.model.transformer.WildcardExpanderModelTransformer.NoMoreAttemptsIOException;
import ro.isdc.wro.util.StringUtils;


/**
 * {@link org.springframework.core.io.Resource} implementation for {@link javax.servlet.ServletContext} resources,
 * interpreting relative paths within the web application root directory.
 *
 * @author Alex Objelean, Ivar Conradi Østhus
 * @created Created on Nov 10, 2008, Updated on March 2, 2012
 */
public class ServletContextResourceLocator
    extends AbstractResourceLocator {
  private static final Logger LOG = LoggerFactory.getLogger(ServletContextResourceLocator.class);
  /**
   * Alias used to register this locator with {@link LocatorProvider}.
   */
  public static final String ALIAS = "servletContext";
   * Same as default Alias (exist for explicit configuration). Uses DISPATCHER_FIRST strategy. Meaning that, for
   * example, a jsp resource will be served in its final state (processed by servlet container), rather than in its raw
   * variant.
   */
  public static final String ALIAS_DISPATCHER_FIRST = "servletContext.DISPATCHER_FIRST";
  /**
   * Uses SERVLET_CONTEXT_FIRST strategy, meaning that, for example, a jsp will be served with its raw content, instead
   * of processed by container.
   */
  public static final String ALIAS_SERVLET_CONTEXT_FIRST = "servletContext.SERVLET_CONTEXT_FIRST";

  /**
   * Prefix for url resources.
   */
  public static final String PREFIX = "/";
  private final ServletContext servletContext;
  private final String path;
  /**
   * Locates a stream using request dispatcher.
   */
  private DispatcherStreamLocator dispatcherStreamLocator;
  /**
   * Determines the order of dispatcher resource locator and servlet context based resource locator.
   */
  private LocatorStrategy locatorStrategy = LocatorStrategy.DISPATCHER_FIRST;
  @Inject
  private ReadOnlyContext context;
  @Inject
  private Injector injector;
  /**
   * Available LocatorStrategies. DISPATCHER_FIRST is default option. This means this UriLocator will first try to
   * locate resource via the dispatcher stream locator. This will include dynamic resources produces by servlet's or
   * JSP's. If the specified resource cannot be found with the dispatcherStreamLocator the implementation will try to
   * use the ServletContext to locate the resource. SERVLET_CONTEXT_FIRST is a alternative approach where we will first
   * try to locate the resource VIA the ServletContext first, and then use the dispatcheStreamLocator if not found. In
   * some cases, where you do not rely on dynamic resources this can be a more reliable and a more efficient approach.
   */
  public static enum LocatorStrategy {
    DISPATCHER_FIRST, SERVLET_CONTEXT_FIRST
  }

  /**
   * Sets the locator strategy to use.
   */
  public ResourceLocator setLocatorStrategy(final LocatorStrategy locatorStrategy) {
    Validate.notNull(locatorStrategy);
    this.locatorStrategy = locatorStrategy;
    return this;
  }


  public ServletContextResourceLocator(final ServletContext servletContext, final String path) {
    Validate.notNull(path);
    // allow null servletContext and prefer throwing IOException if null value is set.
    this.servletContext = servletContext;
    String pathToUse = StringUtils.cleanPath(path);
    if (!pathToUse.startsWith(PREFIX)) {
      pathToUse = PREFIX + pathToUse;
    }
    this.path = pathToUse;
  }

  /**
   * {@inheritDoc}
   */
  public InputStream getInputStream()
      throws IOException {
    if (servletContext == null) {
      throw new IOException("Cannot get stream for the following path: " + path
          + ", because no servletContext is detected.");
    }
    LOG.debug("locating uri: " + path);
    try {
      if (getWildcardStreamLocator().hasWildcard(path)) {
        final String fullPath = FilenameUtils.getFullPath(path);
        final String realPath = servletContext.getRealPath(fullPath);
        if (realPath == null) {
          final String message = "[FAIL] Could not determine realPath for resource: " + path;
          LOG.debug(message);
          throw new IOException(message);
        }
        return getWildcardStreamLocator().locateStream(path, new File(realPath));
      }
    } catch (final IOException e) {
      /**
       * This is a special case when no more attempts are required, since the required computation was achieved
       * successfully. This solves the following issue.
       * 

* The problem was that in some situations, when the dispatcherStreamLocator was used to locate resources * containing wildcard, the following message was printed to the console: * SEVERE: Servlet.service() for servlet default threw exception * java.io.FileNotFoundException. */ if (e instanceof NoMoreAttemptsIOException) { throw e; } LOG.warn("[FAIL] localize the stream containing wildcard. Original error message: '{}'", e.getMessage() + "\".\n Trying to locate the stream without the wildcard."); } InputStream inputStream = null; try { if (locatorStrategy.equals(LocatorStrategy.DISPATCHER_FIRST)) { inputStream = dispatcherFirstStreamLocator(path); } else { inputStream = servletContextFirstStreamLocator(path); } validateInputStreamIsNotNull(inputStream, path); return inputStream; } catch (final IOException e) { LOG.debug("Wrong or empty resource with location: {}", path); throw e; } } /** * {@inheritDoc} */ @Override public ResourceLocator createRelative(final String relativePath) throws IOException { final String folder = FilenameUtils.getFullPath(path); // remove '../' & normalize the path. final String pathToUse = StringUtils.cleanPath(folder + relativePath); return new ServletContextResourceLocator(servletContext, pathToUse); } private InputStream servletContextFirstStreamLocator(final String uri) throws IOException { try { return servletContextBasedStreamLocator(uri); } catch (final IOException e) { LOG.debug("retrieving servletContext stream for uri: {}", uri); return dispatcherBasedStreamLocator(uri); } } private InputStream dispatcherFirstStreamLocator(final String uri) throws IOException { try { return dispatcherBasedStreamLocator(uri); } catch (final IOException e) { LOG.debug("retrieving servletContext stream for uri: {}", uri); return servletContextBasedStreamLocator(uri); } } private InputStream dispatcherBasedStreamLocator(final String uri) throws IOException { final HttpServletRequest request = context.getRequest(); final HttpServletResponse response = context.getResponse(); // The order of stream retrieval is important. We are trying to get the dispatcherStreamLocator in order to handle // jsp resources (if such exist). Switching the order would cause jsp to not be interpreted by the container. return getDispatcherStreamLocator().getInputStream(request, response, uri); } private DispatcherStreamLocator getDispatcherStreamLocator() { if (dispatcherStreamLocator == null) { dispatcherStreamLocator = new DispatcherStreamLocator(); injector.inject(dispatcherStreamLocator); } return dispatcherStreamLocator; } private InputStream servletContextBasedStreamLocator(final String uri) throws IOException { final ServletContext servletContext = context.getServletContext(); return servletContext.getResourceAsStream(uri); } private void validateInputStreamIsNotNull(final InputStream inputStream, final String uri) throws IOException { if (inputStream == null) { LOG.debug("[FAIL] reading resource from {}", uri); throw new IOException("Exception while reading resource from " + uri); }

File
ServletContextResourceLocator.java
Developer's decision
Combination
Kind of conflict
Annotation
Attribute
Class signature
Comment
Enum declaration
If statement
Import
Method declaration
Method invocation
Method signature
Package declaration
Chunk
Conflicting content
   * Contains a {@link UriLocatorFactory} reference injected externally.
   */
  @Inject
<<<<<<< HEAD
  private ResourceLocatorFactory locatorFactory;
  @Inject
  private WroConfiguration configuration;
=======
  private UriLocatorFactory uriLocatorFactory;

>>>>>>> d9390f978dee356e84a1e71532489c30363c0526
  /**
   * List of processed resources, useful for detecting deep recursion. A {@link ThreadLocal} is used to ensure that the
   * processor is thread-safe and doesn't erroneously detect recursion when running in concurrent environment.
Solution content
   * Contains a {@link UriLocatorFactory} reference injected externally.
   */
  @Inject
  private ResourceLocatorFactory locatorFactory;
  /**
   * List of processed resources, useful for detecting deep recursion. A {@link ThreadLocal} is used to ensure that the
   * processor is thread-safe and doesn't erroneously detect recursion when running in concurrent environment.
File
AbstractCssImportPreProcessor.java
Developer's decision
Combination
Kind of conflict
Annotation
Attribute
Chunk
Conflicting content
=======

      return false;
    }
  }
<<<<<<< HEAD:wro4j-core/src/main/java/ro/isdc/wro/model/resource/support/ResourceWatcher.java
  
  private ResourceProcessor createCssImportProcessor(final Resource resource, final AtomicBoolean changeDetected) {
    final ResourceProcessor cssImportProcessor = new AbstractCssImportPreProcessor() {
  private ResourcePreProcessor createCssImportProcessor(final Resource resource, final AtomicBoolean changeDetected,
      final String groupName) {
    final ResourcePreProcessor cssImportProcessor = new AbstractCssImportPreProcessor() {
>>>>>>> d9390f978dee356e84a1e71532489c30363c0526:wro4j-core/src/main/java/ro/isdc/wro/model/resource/support/change/ResourceWatcher.java
      @Override
      protected void onImportDetected(final String importedUri) {
        LOG.debug("Found @import {}", importedUri);
Solution content
      return false;
    }
  }

  private ResourceProcessor createCssImportProcessor(final Resource resource, final AtomicBoolean changeDetected,
      final String groupName) {
    final ResourceProcessor cssImportProcessor = new AbstractCssImportPreProcessor() {
      @Override
      protected void onImportDetected(final String importedUri) {
        LOG.debug("Found @import {}", importedUri);
File
ResourceWatcher.java
Developer's decision
Manual
Kind of conflict
Method invocation
Method signature
Variable
Chunk
Conflicting content
  @Test
  public void shouldCheckDifferentGroups() throws Exception {
<<<<<<< HEAD
    final long updatePeriod = 70;
=======
    final long updatePeriod = 30;
>>>>>>> d9390f978dee356e84a1e71532489c30363c0526
    //Using delta to avoid inconsistent test results related to test timing
    final long delta = 20;
    Context.get().getConfig().setResourceWatcherUpdatePeriod(updatePeriod);
Solution content
  @Test
  public void shouldCheckDifferentGroups() throws Exception {
    final long updatePeriod = 30;
    //Using delta to avoid inconsistent test results related to test timing
    final long delta = 10;
    Context.get().getConfig().setResourceWatcherUpdatePeriod(updatePeriod);
File
TestDefaultSynchronizedCacheStrategyDecorator.java
Developer's decision
Version 2
Kind of conflict
Variable
Chunk
Conflicting content
import ro.isdc.wro.manager.callback.LifecycleCallbackRegistry;
import ro.isdc.wro.manager.factory.BaseWroManagerFactory;
import ro.isdc.wro.model.group.Inject;
<<<<<<< HEAD
import ro.isdc.wro.model.resource.processor.ResourceProcessor;
=======
import ro.isdc.wro.model.resource.Resource;
import ro.isdc.wro.model.resource.locator.factory.UriLocatorFactory;
import ro.isdc.wro.model.resource.processor.ResourcePreProcessor;
>>>>>>> d9390f978dee356e84a1e71532489c30363c0526
import ro.isdc.wro.model.resource.processor.decorator.CopyrightKeeperProcessorDecorator;
import ro.isdc.wro.model.resource.processor.impl.js.JSMinProcessor;
Solution content
import ro.isdc.wro.manager.callback.LifecycleCallbackRegistry;
import ro.isdc.wro.manager.factory.BaseWroManagerFactory;
import ro.isdc.wro.model.group.Inject;
import ro.isdc.wro.model.resource.Resource;
import ro.isdc.wro.model.resource.locator.factory.ResourceLocatorFactory;
import ro.isdc.wro.model.resource.processor.ResourceProcessor;
import ro.isdc.wro.model.resource.processor.decorator.CopyrightKeeperProcessorDecorator;
import ro.isdc.wro.model.resource.processor.impl.js.JSMinProcessor;
File
TestInjector.java
Developer's decision
Manual
Kind of conflict
Import
Chunk
Conflicting content
  }

  @Test
<<<<<<< HEAD
  public void shouldBuildValidInjectorWithSomeFieldsSet() {
    final NamingStrategy namingStrategy = Mockito.mock(NamingStrategy.class);
    final ProcessorsFactory processorsFactory = Mockito.mock(ProcessorsFactory.class);
    final ResourceLocatorFactory resourceLocatorFactory = Mockito.mock(ResourceLocatorFactory.class);

    final BaseWroManagerFactory managerFactroy = new BaseWroManagerFactory();
    managerFactroy.setNamingStrategy(namingStrategy);
    managerFactroy.setProcessorsFactory(processorsFactory);
    managerFactroy.setLocatorFactory(resourceLocatorFactory);
    
=======
  public void shouldBuildValidInjectorWithSomeFieldsSet() throws Exception {
    final NamingStrategy mockNamingStrategy = Mockito.mock(NamingStrategy.class);
    final ProcessorsFactory mockProcessorsFactory = Mockito.mock(ProcessorsFactory.class);
    final UriLocatorFactory mockLocatorFactory = Mockito.mock(UriLocatorFactory.class);

    final BaseWroManagerFactory managerFactroy = new BaseWroManagerFactory();
    managerFactroy.setNamingStrategy(mockNamingStrategy);
    managerFactroy.setProcessorsFactory(mockProcessorsFactory);
    managerFactroy.setUriLocatorFactory(mockLocatorFactory);

>>>>>>> d9390f978dee356e84a1e71532489c30363c0526
    final Injector injector = InjectorBuilder.create(managerFactroy).build();
    Assert.assertNotNull(injector);
Solution content
  }

  @Test
  public void shouldBuildValidInjectorWithSomeFieldsSet() {
    final NamingStrategy namingStrategy = Mockito.mock(NamingStrategy.class);
    final ProcessorsFactory processorsFactory = Mockito.mock(ProcessorsFactory.class);
    final ResourceLocatorFactory resourceLocatorFactory = Mockito.mock(ResourceLocatorFactory.class);

    final BaseWroManagerFactory managerFactroy = new BaseWroManagerFactory();
    managerFactroy.setNamingStrategy(namingStrategy);
    managerFactroy.setProcessorsFactory(processorsFactory);
    managerFactroy.setLocatorFactory(resourceLocatorFactory);

    final Injector injector = InjectorBuilder.create(managerFactroy).build();
    Assert.assertNotNull(injector);
File
TestInjectorBuilder.java
Developer's decision
Version 1
Kind of conflict
Method invocation
Method signature
Variable
Chunk
Conflicting content
    final Sample sample = new Sample();
    injector.inject(sample);
<<<<<<< HEAD
    Assert.assertSame(namingStrategy, sample.namingStrategy);
    Assert.assertNotNull(sample.preProcessorExecutor);

    Assert.assertSame(processorsFactory, AbstractDecorator.getOriginalDecoratedObject(sample.processorsFactory));
    Assert.assertSame(resourceLocatorFactory, AbstractDecorator.getOriginalDecoratedObject(sample.resourceLocatorFactory));
    Assert.assertNotNull(sample.callbackRegistry);
    Assert.assertSame(injector, sample.injector);
    Assert.assertNotNull(sample.groupsProcessor);
    Assert.assertNotNull(sample.modelFactory);
    Assert.assertNotNull(sample.groupExtractor);
    Assert.assertNotNull(sample.cacheStrategy);
    Assert.assertNotNull(sample.hashBuilder);
    Assert.assertNotNull(sample.readOnlyContext);
=======
//    assertTrue(Proxy.isProxyClass(sample.namingStrategy.getClass()));
    assertNotNull(sample.preProcessorExecutor);

    sample.namingStrategy.rename("", WroUtil.EMPTY_STREAM);
    verify(mockNamingStrategy).rename("", WroUtil.EMPTY_STREAM);

    sample.processorsFactory.getPostProcessors();
    verify(mockProcessorsFactory).getPostProcessors();

    sample.uriLocatorFactory.getInstance("");
    verify(mockLocatorFactory).getInstance("");

    assertNotNull(sample.callbackRegistry);
    assertSame(injector, sample.injector);
    assertNotNull(sample.groupsProcessor);
    assertNotNull(sample.modelFactory);
    assertNotNull(sample.groupExtractor);
    assertNotNull(sample.cacheStrategy);
    assertNotNull(sample.hashBuilder);
    assertNotNull(sample.readOnlyContext);
>>>>>>> d9390f978dee356e84a1e71532489c30363c0526
  }

  @Test(expected = IOException.class)
Solution content
    final Sample sample = new Sample();
    injector.inject(sample);
    Assert.assertSame(namingStrategy, sample.namingStrategy);
    Assert.assertNotNull(sample.preProcessorExecutor);

    Assert.assertSame(processorsFactory, AbstractDecorator.getOriginalDecoratedObject(sample.processorsFactory));
    Assert.assertSame(resourceLocatorFactory, AbstractDecorator.getOriginalDecoratedObject(sample.resourceLocatorFactory));
    Assert.assertNotNull(sample.callbackRegistry);
    Assert.assertSame(injector, sample.injector);
    Assert.assertNotNull(sample.groupsProcessor);
    Assert.assertNotNull(sample.modelFactory);
    Assert.assertNotNull(sample.groupExtractor);
    Assert.assertNotNull(sample.cacheStrategy);
    Assert.assertNotNull(sample.hashBuilder);
    Assert.assertNotNull(sample.readOnlyContext);
  }

  @Test(expected = IOException.class)
File
TestInjectorBuilder.java
Developer's decision
Version 1
Kind of conflict
Comment
Method invocation
Chunk
Conflicting content
import org.mockito.stubbing.Answer;

import ro.isdc.wro.config.Context;
<<<<<<< HEAD
import ro.isdc.wro.model.resource.locator.ResourceLocator;
=======
import ro.isdc.wro.model.resource.locator.UriLocator;
import ro.isdc.wro.util.WroTestUtils;
>>>>>>> d9390f978dee356e84a1e71532489c30363c0526


/**
Solution content
import org.mockito.stubbing.Answer;

import ro.isdc.wro.config.Context;
import ro.isdc.wro.model.resource.locator.ResourceLocator;
import ro.isdc.wro.util.WroTestUtils;


/**
File
TestDispatcherStreamLocator.java
Developer's decision
Combination
Kind of conflict
Import
Chunk
Conflicting content
    }).when(mockDispatcher).include(Mockito.any(HttpServletRequest.class),
        Mockito.any(HttpServletResponse.class));
    victim.getInputStream(mockRequest, mockResponse, location);
<<<<<<< HEAD
    
    verify(mockUriLocator).getInputStream();
=======

    verify(mockUriLocator).locate(Mockito.anyString());
>>>>>>> d9390f978dee356e84a1e71532489c30363c0526
  }

  @Test(expected = NullPointerException.class)
Solution content
    }).when(mockDispatcher).include(Mockito.any(HttpServletRequest.class),
        Mockito.any(HttpServletResponse.class));
    victim.getInputStream(mockRequest, mockResponse, location);

    verify(mockUriLocator).getInputStream();
  }

  @Test(expected = NullPointerException.class)
File
TestDispatcherStreamLocator.java
Developer's decision
Version 1
Kind of conflict
Method invocation
Chunk
Conflicting content
 * @author Alex Objelean
 */
public class TestExceptionHandlingProcessorDecorator {
<<<<<<< HEAD
  @Mock 
  private ResourceProcessor mockProcessor;
  @Mock 
=======
  @Mock
  private ResourcePreProcessor mockProcessor;
  @Mock
>>>>>>> d9390f978dee356e84a1e71532489c30363c0526
  private Resource mockResource;
  private ExceptionHandlingProcessorDecorator victim;
Solution content
 * @author Alex Objelean
 */
public class TestExceptionHandlingProcessorDecorator {
  @Mock 
  private ResourceProcessor mockProcessor;
  @Mock 
  private Resource mockResource;
  private ExceptionHandlingProcessorDecorator victim;
File
TestExceptionHandlingProcessorDecorator.java
Developer's decision
Version 1
Kind of conflict
Annotation
Attribute
Chunk
Conflicting content
      }
    };
    createInjector().inject(victim);
<<<<<<< HEAD:wro4j-core/src/test/java/ro/isdc/wro/model/resource/support/TestResourceWatcher.java
    when(mockLocator.getInputStream()).then(answerWithContent(String.format("@import url(%s)", importResourceUri)));
    
    final ResourceLocator mockImportedResourceLocator = mock(ResourceLocator.class);
    when(mockImportedResourceLocator.getInputStream()).then(answerWithContent("initial"));
    
    when(mockLocatorFactory.getLocator(Mockito.eq("/" + RESOURCE_URI))).thenReturn(mockLocator);
    when(mockLocatorFactory.getLocator(Mockito.eq("/" + importResourceUri))).thenReturn(mockImportedResourceLocator);
    
    victim.check(cacheEntry);
    
    when(mockImportedResourceLocator.getInputStream()).then(answerWithContent("changed"));
    
=======
    when(mockLocator.locate(Mockito.anyString())).thenAnswer(answerWithContent("initial"));
    when(mockLocator.locate("/" + Mockito.eq(RESOURCE_URI))).thenAnswer(answerWithContent(String.format("@import url(%s)", importResourceUri)));

    victim.check(cacheEntry);

    when(mockLocator.locate(Mockito.anyString())).thenAnswer(answerWithContent("changed"));
    when(mockLocator.locate("/" + Mockito.eq(RESOURCE_URI))).thenAnswer(answerWithContent(String.format("@import url(%s)", importResourceUri)));

>>>>>>> d9390f978dee356e84a1e71532489c30363c0526:wro4j-core/src/test/java/ro/isdc/wro/model/resource/support/change/TestResourceWatcher.java
    victim.check(cacheEntry);
    assertTrue(groupChanged.get());
    assertTrue(importResourceChanged.get());
Solution content
      }
    };
    createInjector().inject(victim);
    when(mockLocator.getInputStream()).then(answerWithContent(String.format("@import url(%s)", importResourceUri)));

    final ResourceLocator mockImportedResourceLocator = mock(ResourceLocator.class);
    when(mockImportedResourceLocator.getInputStream()).then(answerWithContent("initial"));

    when(mockLocatorFactory.getLocator(Mockito.eq("/" + RESOURCE_URI))).thenReturn(mockLocator);
    when(mockLocatorFactory.getLocator(Mockito.eq("/" + importResourceUri))).thenReturn(mockImportedResourceLocator);

    victim.check(cacheEntry);

    when(mockImportedResourceLocator.getInputStream()).then(answerWithContent("changed"));

    victim.check(cacheEntry);
    assertTrue(groupChanged.get());
    assertTrue(importResourceChanged.get());
File
TestResourceWatcher.java
Developer's decision
Version 1
Kind of conflict
Method invocation
Variable
Chunk
Conflicting content
package ro.isdc.wro.model.resource.support.change;

import static junit.framework.Assert.assertTrue;
<<<<<<< HEAD:wro4j-core/src/test/java/ro/isdc/wro/model/resource/support/TestResourceWatcher.java
import static org.mockito.Mockito.mock;
=======
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
>>>>>>> d9390f978dee356e84a1e71532489c30363c0526:wro4j-core/src/test/java/ro/isdc/wro/model/resource/support/change/TestResourceWatcher.java
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
Solution content
package ro.isdc.wro.model.resource.support.change;

import static junit.framework.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
File
TestResourceWatcher.java
Developer's decision
Concatenation
Kind of conflict
Import
Chunk
Conflicting content
  private final CacheEntry cacheEntry = new CacheEntry(GROUP_NAME, ResourceType.CSS, true);
  private ResourceWatcher victim;
  @Mock
<<<<<<< HEAD:wro4j-core/src/test/java/ro/isdc/wro/model/resource/support/TestResourceWatcher.java
  private ResourceLocator mockLocator;
  @Mock
  private ResourceLocatorFactory mockLocatorFactory;
  
=======
  private UriLocator mockLocator;

>>>>>>> d9390f978dee356e84a1e71532489c30363c0526:wro4j-core/src/test/java/ro/isdc/wro/model/resource/support/change/TestResourceWatcher.java
  @Before
  public void setUp() throws Exception {
    initMocks(this);
Solution content
  private final CacheEntry cacheEntry = new CacheEntry(GROUP_NAME, ResourceType.CSS, true);
  private ResourceWatcher victim;
  @Mock
  private ResourceLocator mockLocator;
  @Mock
  private ResourceLocatorFactory mockLocatorFactory;

  @Before
  public void setUp()
      throws Exception {
    initMocks(this);
File
TestResourceWatcher.java
Developer's decision
Manual
Kind of conflict
Annotation
Attribute
Chunk
Conflicting content
  public void setUp() throws Exception {
    initMocks(this);
    Context.set(Context.standaloneContext());
<<<<<<< HEAD:wro4j-core/src/test/java/ro/isdc/wro/model/resource/support/TestResourceWatcher.java
=======
    // spy the interface instead of WroTestUtils.createResourceMockingLocator() because of mockito bug which was
    // reported on their mailing list.
    mockLocator = Mockito.spy(new UriLocator() {
      public InputStream locate(final String uri)
          throws IOException {
        return new ByteArrayInputStream(uri.getBytes());
      }
      public boolean accept(final String uri) {
        return true;
      }
    });
>>>>>>> d9390f978dee356e84a1e71532489c30363c0526:wro4j-core/src/test/java/ro/isdc/wro/model/resource/support/change/TestResourceWatcher.java
    victim = new ResourceWatcher();
    createInjector().inject(victim);
  }
Solution content
    initMocks(this);
    Context.set(Context.standaloneContext());
    victim = new ResourceWatcher();
    createInjector().inject(victim);
  }
File
TestResourceWatcher.java
Developer's decision
Version 1
Kind of conflict
Attribute
Comment
Method invocation
Chunk
Conflicting content
    createInjector().inject(victim);
  }

<<<<<<< HEAD:wro4j-core/src/test/java/ro/isdc/wro/model/resource/support/TestResourceWatcher.java
  public Injector createInjector() throws Exception {
    when(mockLocatorFactory.getLocator(Mockito.anyString())).thenReturn(mockLocator);
    when(mockLocator.getInputStream()).thenReturn(WroUtil.EMPTY_STREAM);
    
=======
  public Injector createInjector() {
    final UriLocatorFactory locatorFactory = new AbstractUriLocatorFactory() {
      public UriLocator getInstance(final String uri) {
        return mockLocator;
      }
    };

>>>>>>> d9390f978dee356e84a1e71532489c30363c0526:wro4j-core/src/test/java/ro/isdc/wro/model/resource/support/change/TestResourceWatcher.java
    final WroModel model = new WroModel().addGroup(new Group(GROUP_NAME).addResource(Resource.create(RESOURCE_URI)));
    final WroModelFactory modelFactory = WroTestUtils.simpleModelFactory(model);
    final WroManagerFactory factory = new BaseWroManagerFactory().setModelFactory(modelFactory).setLocatorFactory(
Solution content
    createInjector().inject(victim);
  }

  public Injector createInjector()
      throws Exception {
    when(mockLocatorFactory.getLocator(Mockito.anyString())).thenReturn(mockLocator);
    when(mockLocator.getInputStream()).thenReturn(WroUtil.EMPTY_STREAM);

    final WroModel model = new WroModel().addGroup(new Group(GROUP_NAME).addResource(Resource.create(RESOURCE_URI)));
    final WroModelFactory modelFactory = WroTestUtils.simpleModelFactory(model);
    final WroManagerFactory factory = new BaseWroManagerFactory().setModelFactory(modelFactory).setLocatorFactory(
File
TestResourceWatcher.java
Developer's decision
Version 1
Kind of conflict
Method invocation
Method signature
Variable
Chunk
Conflicting content
    };
    createInjector().inject(victim);
    victim.check(cacheEntry);
<<<<<<< HEAD:wro4j-core/src/test/java/ro/isdc/wro/model/resource/support/TestResourceWatcher.java
    assertEquals(1, victim.getPreviousHashes().keySet().size());
    
    Mockito.when(mockLocator.getInputStream()).thenReturn(
=======
    assertTrue(victim.getResourceChangeDetector().checkChangeForGroup(RESOURCE_URI, GROUP_NAME));

    Mockito.when(mockLocator.locate(Mockito.anyString())).thenReturn(
>>>>>>> d9390f978dee356e84a1e71532489c30363c0526:wro4j-core/src/test/java/ro/isdc/wro/model/resource/support/change/TestResourceWatcher.java
        new ByteArrayInputStream("different".getBytes()));

    victim.check(cacheEntry);
Solution content
    };
    createInjector().inject(victim);
    victim.check(cacheEntry);
    assertTrue(victim.getResourceChangeDetector().checkChangeForGroup(RESOURCE_URI, GROUP_NAME));

    Mockito.when(mockLocator.getInputStream()).thenReturn(new ByteArrayInputStream("different".getBytes()));

    victim.check(cacheEntry);
File
TestResourceWatcher.java
Developer's decision
Manual
Kind of conflict
Method invocation
Chunk
Conflicting content
    createInjector().inject(victim);
    final ResourceChangeDetector mockChangeDetector = Mockito.spy(victim.getResourceChangeDetector());
    victim.check(cacheEntry);
<<<<<<< HEAD:wro4j-core/src/test/java/ro/isdc/wro/model/resource/support/TestResourceWatcher.java
    assertEquals(1, victim.getPreviousHashes().keySet().size());
    
    Mockito.when(mockLocator.getInputStream()).thenThrow(new IOException("Resource is unavailable"));
    
=======
    verify(mockChangeDetector, never()).checkChangeForGroup(Mockito.anyString(), Mockito.anyString());

    Mockito.when(mockLocator.locate(Mockito.anyString())).thenThrow(new IOException("Resource is unavailable"));

>>>>>>> d9390f978dee356e84a1e71532489c30363c0526:wro4j-core/src/test/java/ro/isdc/wro/model/resource/support/change/TestResourceWatcher.java
    victim.check(cacheEntry);
    verify(mockChangeDetector, never()).checkChangeForGroup(Mockito.anyString(), Mockito.anyString());
  }
Solution content
    createInjector().inject(victim);
    final ResourceChangeDetector mockChangeDetector = Mockito.spy(victim.getResourceChangeDetector());
    victim.check(cacheEntry);
    verify(mockChangeDetector, never()).checkChangeForGroup(Mockito.anyString(), Mockito.anyString());

    Mockito.when(mockLocator.getInputStream()).thenThrow(new IOException("Resource is unavailable"));

    victim.check(cacheEntry);
    verify(mockChangeDetector, never()).checkChangeForGroup(Mockito.anyString(), Mockito.anyString());
  }
File
TestResourceWatcher.java
Developer's decision
Combination
Kind of conflict
Method invocation