_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q176800 | AwsUtils.performAmazonActionWithRetry | test | public static <T> T performAmazonActionWithRetry(String actionLabel, Supplier<T> action, int retryLimit, int durationInMillis) {
int retryCount = 0;
do {
try {
return action.get();
} catch (LimitExceededException | ProvisionedThroughputExceededException | KMSThrottlingException e) {
// We should just wait a little time before trying again
int remainingRetries = retryLimit - retryCount;
LOG.debug("Amazon exception caught",
args -> args.add("exception", e.getClass().getName()).add("action", actionLabel).add("remainingRetryCount", remainingRetries));
}
sleepUntilInterrupted(actionLabel, durationInMillis);
} while (retryCount++ < retryLimit);
throw new AwsException("Limit exceeded, all retries failed", args -> args.add("action", actionLabel).add("retryLimit", retryLimit));
} | java | {
"resource": ""
} |
q176801 | AwsUtils.tryAmazonAction | test | public static <T> Optional<T> tryAmazonAction(String actionLabel, Supplier<T> action, AtomicLong durationBetweenRequests) {
try {
return of(action.get());
} catch (LimitExceededException | ProvisionedThroughputExceededException | KMSThrottlingException e) {
int durationRandomModifier = 1 + RANDOM.nextInt(64);// random duration to make readers out of sync, avoiding simultaneous readings
long updatedDuration = durationBetweenRequests.updateAndGet(duration -> duration * 2 // twice the duration
+ duration * 2 / durationRandomModifier);// add random duration to avoid simultaneous reads
LOG.debug("Update of minimal duration between two get shard iterator requests",
args -> args.add("actionLabel", actionLabel).add("new minimalDurationBetweenTwoGetShardIteratorRequests", updatedDuration));
}
return empty();
} | java | {
"resource": ""
} |
q176802 | AwsS3Utils.checkBucketIsAccessible | test | static String checkBucketIsAccessible(AmazonS3 amazonS3, String bucketName) {
HeadBucketRequest headBucketRequest = new HeadBucketRequest(bucketName);
try {
amazonS3.headBucket(headBucketRequest);
} catch (AmazonServiceException e) {
throw new AwsS3Exception("Bucket is not accessible", args -> args.add("bucketName", bucketName), e);
}
return bucketName;
} | java | {
"resource": ""
} |
q176803 | StorePersistence.loadStores | test | Optional<BigInteger> loadStores(Function<String, EntityStores> entityStoresByStoreName,
BiFunction<SerializableSnapshot, String, SerializableSnapshot> snapshotPostProcessor) {
Optional<BigInteger> latestSnapshotTxId;
try {
latestSnapshotTxId = m_snapshotStore.listSnapshots().stream().max(BigInteger::compareTo);
} catch (IOException e) {
throw new UnrecoverableStoreException("Error occurred when recovering from latest snapshot", e);
}
latestSnapshotTxId.ifPresent(lastTx -> {
LOG.info("Recovering store from snapshot", args -> args.add("transactionId", lastTx));
var postProcess = new SnapshotPostProcessor(snapshotPostProcessor);
try {
Flowable.fromPublisher(m_snapshotStore.createSnapshotReader(lastTx)) //
.blockingForEach(reader -> {
String storeName = reader.storeName();
EntityStores entityStores = entityStoresByStoreName.apply(storeName);
SerializableSnapshot serializableSnapshot;
try (InputStream is = reader.inputStream()) {
serializableSnapshot = m_snapshotSerializer.deserializeSnapshot(storeName, is);
}
if (serializableSnapshot.getSnapshotModelVersion() != SNAPSHOT_MODEL_VERSION) {
throw new UnrecoverableStoreException("Snapshot serializable model version is not supported",
args -> args.add("version", serializableSnapshot.getSnapshotModelVersion())
.add("expectedVersion", SNAPSHOT_MODEL_VERSION));
}
if (!lastTx.equals(serializableSnapshot.getTransactionId())) {
throw new UnrecoverableStoreException("Snapshot transaction id mismatch with request transaction id",
args -> args.add("snapshotTransactionId", serializableSnapshot.getTransactionId())
.add("requestTransactionId", lastTx));
}
SerializableSnapshot finalSnapshot = postProcess.apply(storeName, serializableSnapshot);
finalSnapshot.getEntities().forEach(serializableEntityInstances -> {
String entityName = serializableEntityInstances.getEntityName();
EntityStore<?> entityStore = entityStores.getEntityStore(entityName);
checkArgument(entityStore != null, "Entity has not be registered in the store", args -> args.add("entityName", entityName));
entityStore.recover(serializableEntityInstances);
});
});
} catch (Exception e) {
throw new UnrecoverableStoreException("Error occurred when recovering from latest snapshot", e);
}
// update the applicationModelVersion if any consistent load/update
m_applicationModelVersion = postProcess.getConsistentApplicationModelVersion();
});
if (!latestSnapshotTxId.isPresent()) {
LOG.info("Store has no snapshot, store is empty, creating it's first snapshot");
}
return latestSnapshotTxId;
} | java | {
"resource": ""
} |
q176804 | DefaultWildcardStreamLocator.triggerWildcardExpander | test | void triggerWildcardExpander(final Collection<File> allFiles, final WildcardContext wildcardContext)
throws IOException {
LOG.debug("wildcard resources: {}", allFiles);
if (allFiles.isEmpty()) {
final String message = String.format("No resource found for wildcard: %s", wildcardContext.getWildcard());
LOG.warn(message);
throw new IOException(message);
}
if (wildcardExpanderHandler != null) {
try {
wildcardExpanderHandler.apply(allFiles);
} catch(final IOException e) {
// preserve exception type if the exception is already an IOException
throw e;
} catch (final Exception e) {
LOG.debug("wildcard expanding error. Reporting original exception", e);
throw new IOException("Exception during expanding wildcard: " + e.getMessage());
}
}
} | java | {
"resource": ""
} |
q176805 | StringUtils.replace | test | private static String replace(final String inString, final String oldPattern,
final String newPattern) {
if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {
return inString;
}
final StringBuffer sbuf = new StringBuffer();
// output StringBuffer we'll build up
int pos = 0; // our position in the old string
int index = inString.indexOf(oldPattern);
// the index of an occurrence we've found, or -1
final int patLen = oldPattern.length();
while (index >= 0) {
sbuf.append(inString.substring(pos, index));
sbuf.append(newPattern);
pos = index + patLen;
index = inString.indexOf(oldPattern, pos);
}
sbuf.append(inString.substring(pos));
// remember to append any characters to the right of a match
return sbuf.toString();
} | java | {
"resource": ""
} |
q176806 | StringUtils.deleteAny | test | private static String deleteAny(final String inString,
final String charsToDelete) {
if (!hasLength(inString) || !hasLength(charsToDelete)) {
return inString;
}
final StringBuffer out = new StringBuffer();
for (int i = 0; i < inString.length(); i++) {
final char c = inString.charAt(i);
if (charsToDelete.indexOf(c) == -1) {
out.append(c);
}
}
return out.toString();
} | java | {
"resource": ""
} |
q176807 | LintReport.addReport | test | public LintReport<T> addReport(final ResourceLintReport<T> resourceLintReport) {
Validate.notNull(resourceLintReport);
reports.add(resourceLintReport);
return this;
} | java | {
"resource": ""
} |
q176808 | ConfigurableWroManagerFactory.updatePropertiesWithConfiguration | test | private void updatePropertiesWithConfiguration(final Properties props, final String key) {
final FilterConfig filterConfig = Context.get().getFilterConfig();
// first, retrieve value from init-param for backward compatibility
final String valuesAsString = filterConfig.getInitParameter(key);
if (valuesAsString != null) {
props.setProperty(key, valuesAsString);
} else {
// retrieve value from configProperties file
final String value = getConfigProperties().getProperty(key);
if (value != null) {
props.setProperty(key, value);
}
}
} | java | {
"resource": ""
} |
q176809 | ConfigurableWroManagerFactory.getConfigProperties | test | private Properties getConfigProperties() {
if (configProperties == null) {
configProperties = newConfigProperties();
if (additionalConfigProperties != null) {
configProperties.putAll(additionalConfigProperties);
}
}
return configProperties;
} | java | {
"resource": ""
} |
q176810 | SmartWroModelFactory.createAutoDetectedStream | test | private InputStream createAutoDetectedStream(final String defaultFileName)
throws IOException {
try {
Validate.notNull(wroFile, "Cannot call this method if wroFile is null!");
if (autoDetectWroFile) {
final File file = new File(wroFile.getParentFile(), defaultFileName);
LOG.debug("\tloading autodetected wro file: " + file);
return new FileInputStream(file);
}
LOG.debug("loading wroFile: " + wroFile);
return new FileInputStream(wroFile);
} catch (final FileNotFoundException e) {
// When auto detect is turned on, do not skip trying.. because the auto detection assume that the wro file name
// can be wrong.
if (autoDetectWroFile) {
throw e;
}
throw new WroRuntimeException("The wroFile doesn't exist. Skip trying with other wro model factories", e);
}
} | java | {
"resource": ""
} |
q176811 | DefaultProcessorProvider.toPostProcessors | test | private Map<String, ResourcePostProcessor> toPostProcessors(
final Map<String, ResourcePreProcessor> preProcessorsMap) {
final Map<String, ResourcePostProcessor> map = new HashMap<String, ResourcePostProcessor>();
for (final Entry<String, ResourcePreProcessor> entry : preProcessorsMap.entrySet()) {
map.put(entry.getKey(), new ProcessorDecorator(entry.getValue()));
}
return map;
} | java | {
"resource": ""
} |
q176812 | AbstractJsTemplateCompiler.compile | test | public String compile(final String content, final String optionalArgument) {
final RhinoScriptBuilder builder = initScriptBuilder();
final String argStr = createArgStr(optionalArgument) + createArgStr(getArguments());
final String compileScript =
String.format("%s(%s%s);", getCompileCommand(), WroUtil.toJSMultiLineString(content), argStr);
return (String) builder.evaluate(compileScript, getCompileCommand());
} | java | {
"resource": ""
} |
q176813 | WroConfiguration.reloadCacheWithNewValue | test | private void reloadCacheWithNewValue(final Long newValue) {
final long newValueAsPrimitive = newValue == null ? getCacheUpdatePeriod() : newValue;
LOG.debug("invoking {} listeners", cacheUpdatePeriodListeners.size());
for (final PropertyChangeListener listener : cacheUpdatePeriodListeners) {
final PropertyChangeEvent event = new PropertyChangeEvent(this, "cache", getCacheUpdatePeriod(),
newValueAsPrimitive);
listener.propertyChange(event);
}
} | java | {
"resource": ""
} |
q176814 | WroConfiguration.reloadModelWithNewValue | test | private void reloadModelWithNewValue(final Long newValue) {
final long newValueAsPrimitive = newValue == null ? getModelUpdatePeriod() : newValue;
for (final PropertyChangeListener listener : modelUpdatePeriodListeners) {
final PropertyChangeEvent event = new PropertyChangeEvent(this, "model", getModelUpdatePeriod(),
newValueAsPrimitive);
listener.propertyChange(event);
}
} | java | {
"resource": ""
} |
q176815 | DispatcherStreamLocator.getWrappedServletRequest | test | 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;
} | java | {
"resource": ""
} |
q176816 | Transformers.baseNameSuffixTransformer | test | public static Transformer<String> baseNameSuffixTransformer(final String suffix) {
return new Transformer<String>() {
public String transform(final String input) {
final String baseName = FilenameUtils.getBaseName(input);
final String extension = FilenameUtils.getExtension(input);
return baseName + suffix + "." + extension;
}
};
} | java | {
"resource": ""
} |
q176817 | RedirectedStreamServletResponseWrapper.onError | test | private void onError(final int sc, final String msg) {
LOG.debug("Error detected with code: {} and message: {}", sc, msg);
final OutputStream emptyStream = new ByteArrayOutputStream();
printWriter = new PrintWriter(emptyStream);
servletOutputStream = new DelegatingServletOutputStream(emptyStream);
} | java | {
"resource": ""
} |
q176818 | RedirectedStreamServletResponseWrapper.sendRedirect | test | @Override
public void sendRedirect(final String location)
throws IOException {
try {
LOG.debug("redirecting to: {}", location);
final InputStream is = externalResourceLocator.locate(location);
IOUtils.copy(is, servletOutputStream);
is.close();
servletOutputStream.close();
} catch (final IOException e) {
LOG.warn("{}: Invalid response for location: {}", e.getClass().getName(), location);
throw e;
}
} | java | {
"resource": ""
} |
q176819 | WildcardExpanderModelTransformer.processResource | test | private void processResource(final Group group, final Resource resource) {
final UriLocator uriLocator = locatorFactory.getInstance(resource.getUri());
if (uriLocator instanceof WildcardUriLocatorSupport) {
final WildcardStreamLocator wildcardStreamLocator = ((WildcardUriLocatorSupport) uriLocator).getWildcardStreamLocator();
// TODO should we probably handle the situation when wildcard is present, but the implementation is not
// expandedHandledAware?
if (wildcardStreamLocator.hasWildcard(resource.getUri())
&& wildcardStreamLocator instanceof WildcardExpanderHandlerAware) {
final WildcardExpanderHandlerAware expandedHandler = (WildcardExpanderHandlerAware) wildcardStreamLocator;
LOG.debug("Expanding resource: {}", resource.getUri());
final String baseNameFolder = computeBaseNameFolder(resource, uriLocator, expandedHandler);
LOG.debug("baseNameFolder: {}", baseNameFolder);
expandedHandler.setWildcardExpanderHandler(createExpanderHandler(group, resource, baseNameFolder));
try {
// trigger the wildcard replacement
uriLocator.locate(resource.getUri());
} catch (final IOException e) {
// log only
LOG.debug("[FAIL] problem while trying to expand wildcard for the following resource uri: {}",
resource.getUri());
} finally {
// remove the handler, it is not needed anymore
expandedHandler.setWildcardExpanderHandler(null);
}
}
}
} | java | {
"resource": ""
} |
q176820 | WildcardExpanderModelTransformer.createExpanderHandler | test | public Function<Collection<File>, Void> createExpanderHandler(final Group group, final Resource resource,
final String baseNameFolder) {
LOG.debug("createExpanderHandler using baseNameFolder: {}\n for resource {}", baseNameFolder, resource);
return new Function<Collection<File>, Void>() {
public Void apply(final Collection<File> files) {
if (baseNameFolder == null) {
// replacing group with empty list since the original uri has no associated resources.
// No BaseNameFolder found
LOG.warn("The resource {} is probably invalid, removing it from the group.", resource);
group.replace(resource, new ArrayList<Resource>());
} else {
final List<Resource> expandedResources = new ArrayList<Resource>();
LOG.debug("baseNameFolder: {}", baseNameFolder);
for (final File file : files) {
final String resourcePath = getFullPathNoEndSeparator(resource);
LOG.debug("\tresourcePath: {}", resourcePath);
LOG.debug("\tfile path: {}", file.getPath());
final String computedResourceUri = resourcePath
+ StringUtils.removeStart(file.getPath(), baseNameFolder).replace('\\', '/');
final Resource expandedResource = Resource.create(computedResourceUri, resource.getType());
LOG.debug("\texpanded resource: {}", expandedResource);
expandedResources.add(expandedResource);
}
LOG.debug("\treplace resource {}", resource);
group.replace(resource, expandedResources);
}
return null;
}
/**
* This method fixes the problem when a resource in a group uses deep wildcard and starts at the root.
* <p/>
* Find more details <a href="https://github.com/alexo/wro4j/pull/44">here</a>.
*/
private String getFullPathNoEndSeparator(final Resource resource1) {
final String result = FilenameUtils.getFullPathNoEndSeparator(resource1.getUri());
if (result != null && 1 == result.length() && 0 == FilenameUtils.indexOfLastSeparator(result)) {
return "";
}
return result;
}
};
} | java | {
"resource": ""
} |
q176821 | AbstractUriLocatorFactory.locate | test | public final InputStream locate(final String uri)
throws IOException {
final UriLocator uriLocator = getInstance(uri);
if (uriLocator == null) {
throw new WroRuntimeException("No locator is capable of handling uri: " + uri);
}
LOG.debug("[OK] locating {} using locator: {}", uri, uriLocator.getClass().getSimpleName());
return new AutoCloseInputStream(uriLocator.locate(uri));
} | java | {
"resource": ""
} |
q176822 | WroFilter.createConfiguration | test | private WroConfiguration createConfiguration() {
// Extract config from servletContext (if already configured)
// TODO use a named helper
final WroConfiguration configAttribute = ServletContextAttributeHelper.create(filterConfig).getWroConfiguration();
if (configAttribute != null) {
setConfiguration(configAttribute);
}
return getWroConfigurationFactory().create();
} | java | {
"resource": ""
} |
q176823 | WroFilter.registerChangeListeners | test | private void registerChangeListeners() {
wroConfiguration.registerCacheUpdatePeriodChangeListener(new PropertyChangeListener() {
public void propertyChange(final PropertyChangeEvent event) {
// reset cache headers when any property is changed in order to avoid browser caching
headersConfigurer = newResponseHeadersConfigurer();
wroManagerFactory.onCachePeriodChanged(valueAsLong(event.getNewValue()));
}
});
wroConfiguration.registerModelUpdatePeriodChangeListener(new PropertyChangeListener() {
public void propertyChange(final PropertyChangeEvent event) {
headersConfigurer = newResponseHeadersConfigurer();
wroManagerFactory.onModelPeriodChanged(valueAsLong(event.getNewValue()));
}
});
LOG.debug("Cache & Model change listeners were registered");
} | java | {
"resource": ""
} |
q176824 | WroFilter.processRequest | test | private void processRequest(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
setResponseHeaders(response);
// process the uri using manager
wroManagerFactory.create().process();
} | java | {
"resource": ""
} |
q176825 | WroFilter.setConfiguration | test | public final void setConfiguration(final WroConfiguration config) {
notNull(config);
wroConfigurationFactory = new ObjectFactory<WroConfiguration>() {
public WroConfiguration create() {
return config;
}
};
} | java | {
"resource": ""
} |
q176826 | WroModel.identifyDuplicateGroupNames | test | private void identifyDuplicateGroupNames(final Collection<Group> groups) {
LOG.debug("identifyDuplicateGroupNames");
final List<String> groupNames = new ArrayList<String>();
for (final Group group : groups) {
if (groupNames.contains(group.getName())) {
throw new WroRuntimeException("Duplicate group name detected: " + group.getName());
}
groupNames.add(group.getName());
}
} | java | {
"resource": ""
} |
q176827 | WroModel.merge | test | public void merge(final WroModel importedModel) {
Validate.notNull(importedModel, "imported model cannot be null!");
LOG.debug("merging importedModel: {}", importedModel);
for (final String groupName : new WroModelInspector(importedModel).getGroupNames()) {
if (new WroModelInspector(this).getGroupNames().contains(groupName)) {
throw new WroRuntimeException("Duplicate group name detected: " + groupName);
}
final Group importedGroup = new WroModelInspector(importedModel).getGroupByName(groupName);
addGroup(importedGroup);
}
} | java | {
"resource": ""
} |
q176828 | InjectableUriLocatorFactoryDecorator.locate | test | public InputStream locate(final String uri)
throws IOException {
final UriLocator locator = getInstance(uri);
if (locator == null) {
return getDecoratedObject().locate(uri);
}
return locator.locate(uri);
} | java | {
"resource": ""
} |
q176829 | GroupsProcessor.applyPostProcessors | test | private String applyPostProcessors(final CacheKey cacheKey, final String content)
throws IOException {
final Collection<ResourcePostProcessor> processors = processorsFactory.getPostProcessors();
LOG.debug("appying post processors: {}", processors);
if (processors.isEmpty()) {
return content;
}
final Resource resource = Resource.create(cacheKey.getGroupName(), cacheKey.getType());
Reader reader = new StringReader(content.toString());
Writer writer = null;
for (final ResourcePostProcessor processor : processors) {
final ResourcePreProcessor decoratedProcessor = decorateProcessor(processor, cacheKey.isMinimize());
writer = new StringWriter();
decoratedProcessor.process(resource, reader, writer);
reader = new StringReader(writer.toString());
}
return writer.toString();
} | java | {
"resource": ""
} |
q176830 | GroupsProcessor.decorateProcessor | test | private synchronized ProcessorDecorator decorateProcessor(final ResourcePostProcessor processor,
final boolean minimize) {
final ProcessorDecorator decorated = new DefaultProcessorDecorator(processor, minimize) {
@Override
public void process(final Resource resource, final Reader reader, final Writer writer)
throws IOException {
try {
callbackRegistry.onBeforePostProcess();
super.process(resource, reader, writer);
} finally {
callbackRegistry.onAfterPostProcess();
}
}
};
injector.inject(decorated);
return decorated;
} | java | {
"resource": ""
} |
q176831 | AbstractProcessorsFilter.doProcess | test | private void doProcess(final String requestUri, final Reader reader, final Writer writer)
throws IOException {
Reader input = reader;
Writer output = null;
LOG.debug("processing resource: {}", requestUri);
try {
final StopWatch stopWatch = new StopWatch();
final Injector injector = InjectorBuilder.create(new BaseWroManagerFactory()).build();
final List<ResourcePreProcessor> processors = getProcessorsList();
if (processors == null || processors.isEmpty()) {
IOUtils.copy(reader, writer);
} else {
for (final ResourcePreProcessor processor : processors) {
stopWatch.start("Using " + processor.getClass().getSimpleName());
// inject all required properties
injector.inject(processor);
output = new StringWriter();
LOG.debug("Using {} processor", processor);
processor.process(createResource(requestUri), input, output);
input = new StringReader(output.toString());
stopWatch.stop();
}
LOG.debug(stopWatch.prettyPrint());
if (output != null) {
writer.write(output.toString());
}
}
} finally {
reader.close();
writer.close();
}
} | java | {
"resource": ""
} |
q176832 | OptionsBuilder.splitOptions | test | public String[] splitOptions(final String optionAsString) {
return optionAsString == null ? ArrayUtils.EMPTY_STRING_ARRAY : optionAsString.split("(?ims),(?![^\\[\\]]*\\])");
} | java | {
"resource": ""
} |
q176833 | RegexpProperties.load | test | public Properties load(final InputStream inputStream) throws IOException {
Validate.notNull(inputStream);
final String rawContent = IOUtils.toString(inputStream, CharEncoding.UTF_8);
parseProperties(rawContent.replaceAll(REGEX_COMMENTS, ""));
return this.properties;
} | java | {
"resource": ""
} |
q176834 | RegexpProperties.parseProperties | test | private void parseProperties(final String propertiesAsString) {
//should work also \r?\n
final String[] propertyEntries = propertiesAsString.split("\\r?\\n");
for (final String entry : propertyEntries) {
readPropertyEntry(entry);
}
} | java | {
"resource": ""
} |
q176835 | AbstractWro4jMojo.createCustomManagerFactory | test | private WroManagerFactory createCustomManagerFactory()
throws MojoExecutionException {
WroManagerFactory factory = null;
try {
final Class<?> wroManagerFactoryClass = Thread.currentThread().getContextClassLoader().loadClass(
wroManagerFactory.trim());
factory = (WroManagerFactory) wroManagerFactoryClass.newInstance();
} catch (final Exception e) {
throw new MojoExecutionException("Invalid wroManagerFactoryClass, called: " + wroManagerFactory, e);
}
return factory;
} | java | {
"resource": ""
} |
q176836 | AbstractWro4jMojo.persistResourceFingerprints | test | private void persistResourceFingerprints(final List<String> groupNames) {
final WroModelInspector modelInspector = new WroModelInspector(getModel());
for (final String groupName : groupNames) {
final Group group = modelInspector.getGroupByName(groupName);
if (group != null) {
for (final Resource resource : group.getResources()) {
getResourceChangeHandler().remember(resource);
}
}
}
} | java | {
"resource": ""
} |
q176837 | AbstractWro4jMojo.isTargetGroup | test | private boolean isTargetGroup(final Group group) {
notNull(group);
final String targetGroups = getTargetGroups();
// null, means all groups are target groups
return targetGroups == null || targetGroups.contains(group.getName());
} | java | {
"resource": ""
} |
q176838 | AbstractWro4jMojo.extendPluginClasspath | test | protected final void extendPluginClasspath()
throws MojoExecutionException {
// this code is inspired from http://teleal.org/weblog/Extending%20the%20Maven%20plugin%20classpath.html
final List<String> classpathElements = new ArrayList<String>();
try {
classpathElements.addAll(mavenProject.getRuntimeClasspathElements());
} catch (final DependencyResolutionRequiredException e) {
throw new MojoExecutionException("Could not get compile classpath elements", e);
}
final ClassLoader classLoader = createClassLoader(classpathElements);
Thread.currentThread().setContextClassLoader(classLoader);
} | java | {
"resource": ""
} |
q176839 | AbstractWroModelFactory.getModelResourceAsStream | test | protected InputStream getModelResourceAsStream()
throws IOException {
final ServletContext servletContext = context.getServletContext();
// Don't allow NPE, throw a more detailed exception
if (servletContext == null) {
throw new WroRuntimeException(
"No servletContext is available. Probably you are running this code outside of the request cycle!");
}
final String resourceLocation = "/WEB-INF/" + getDefaultModelFilename();
final InputStream stream = servletContext.getResourceAsStream(resourceLocation);
if (stream == null) {
throw new IOException("Invalid resource requested: " + resourceLocation);
}
return stream;
} | java | {
"resource": ""
} |
q176840 | DefaultWroManagerFactory.initFactory | test | private WroManagerFactory initFactory(final Properties properties) {
WroManagerFactory factory = null;
final String wroManagerClassName = properties.getProperty(ConfigConstants.managerFactoryClassName.name());
if (StringUtils.isEmpty(wroManagerClassName)) {
// If no context param was specified we return the default factory
factory = newManagerFactory();
} else {
// Try to find the specified factory class
Class<?> factoryClass = null;
try {
factoryClass = Thread.currentThread().getContextClassLoader().loadClass(wroManagerClassName);
factory = (WroManagerFactory) factoryClass.newInstance();
} catch (final Exception e) {
throw new WroRuntimeException("Exception while loading WroManagerFactory class:" + wroManagerClassName, e);
}
}
// add properties if required
if (factory instanceof ConfigurableWroManagerFactory) {
((ConfigurableWroManagerFactory) factory).addConfigProperties(properties);
}
return factory;
} | java | {
"resource": ""
} |
q176841 | ModelTransformerFactory.setTransformers | test | public ModelTransformerFactory setTransformers(final List<Transformer<WroModel>> modelTransformers) {
Validate.notNull(modelTransformers);
this.modelTransformers = modelTransformers;
return this;
} | java | {
"resource": ""
} |
q176842 | EmberJs.compile | test | @Override
public String compile(final String content, final String name) {
final String precompiledFunction = super.compile(content, "");
return String.format("(function() {Ember.TEMPLATES[%s] = Ember.Handlebars.template(%s)})();", name, precompiledFunction);
} | java | {
"resource": ""
} |
q176843 | PreProcessorExecutor.processAndMerge | test | public String processAndMerge(final List<Resource> resources, final boolean minimize)
throws IOException {
return processAndMerge(resources, ProcessingCriteria.create(ProcessingType.ALL, minimize));
} | java | {
"resource": ""
} |
q176844 | PreProcessorExecutor.processAndMerge | test | public String processAndMerge(final List<Resource> resources, final ProcessingCriteria criteria)
throws IOException {
notNull(criteria);
LOG.debug("criteria: {}", criteria);
callbackRegistry.onBeforeMerge();
try {
notNull(resources);
LOG.debug("process and merge resources: {}", resources);
final StringBuffer result = new StringBuffer();
if (shouldRunInParallel(resources)) {
result.append(runInParallel(resources, criteria));
} else {
for (final Resource resource : resources) {
LOG.debug("\tmerging resource: {}", resource);
result.append(applyPreProcessors(resource, criteria));
}
}
return result.toString();
} finally {
callbackRegistry.onAfterMerge();
}
} | java | {
"resource": ""
} |
q176845 | PreProcessorExecutor.runInParallel | test | private String runInParallel(final List<Resource> resources, final ProcessingCriteria criteria)
throws IOException {
LOG.debug("Running preProcessing in Parallel");
final StringBuffer result = new StringBuffer();
final List<Callable<String>> callables = new ArrayList<Callable<String>>();
for (final Resource resource : resources) {
callables.add(new Callable<String>() {
public String call()
throws Exception {
LOG.debug("Callable started for resource: {} ...", resource);
return applyPreProcessors(resource, criteria);
}
});
}
final ExecutorService exec = getExecutorService();
final List<Future<String>> futures = new ArrayList<Future<String>>();
for (final Callable<String> callable : callables) {
// decorate with ContextPropagatingCallable in order to allow spawn threads to access the Context
final Callable<String> decoratedCallable = new ContextPropagatingCallable<String>(callable);
futures.add(exec.submit(decoratedCallable));
}
for (final Future<String> 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);
}
}
}
return result.toString();
} | java | {
"resource": ""
} |
q176846 | PreProcessorExecutor.applyPreProcessors | test | private String applyPreProcessors(final Resource resource, final ProcessingCriteria criteria)
throws IOException {
final Collection<ResourcePreProcessor> processors = 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()) {
Writer writer = null;
for (final ResourcePreProcessor processor : processors) {
final ResourcePreProcessor decoratedProcessor = decoratePreProcessor(processor, criteria);
writer = new StringWriter();
final Reader reader = new StringReader(resourceContent);
// decorate and process
decoratedProcessor.process(resource, reader, writer);
// use the outcome for next input
resourceContent = writer.toString();
}
}
// add explicitly new line at the end to avoid unexpected comment issue
return String.format("%s%n", resourceContent);
} | java | {
"resource": ""
} |
q176847 | PreProcessorExecutor.decoratePreProcessor | test | private synchronized ResourcePreProcessor decoratePreProcessor(final ResourcePreProcessor processor,
final ProcessingCriteria criteria) {
final ResourcePreProcessor decorated = new DefaultProcessorDecorator(processor, criteria) {
@Override
public void process(final Resource resource, final Reader reader, final Writer writer)
throws IOException {
try {
callbackRegistry.onBeforePreProcess();
super.process(resource, reader, writer);
} finally {
callbackRegistry.onAfterPreProcess();
}
}
};
injector.inject(decorated);
return decorated;
} | java | {
"resource": ""
} |
q176848 | BuildContextHolder.persist | test | public void persist() {
OutputStream os = null;
try {
os = new FileOutputStream(fallbackStorageFile);
fallbackStorage.store(os, "Generated");
LOG.debug("fallback storage written to {}", fallbackStorageFile);
} catch (final IOException e) {
LOG.warn("Cannot persist fallback storage: {}.", fallbackStorageFile, e);
} finally {
IOUtils.closeQuietly(os);
}
} | java | {
"resource": ""
} |
q176849 | Injector.getAllFields | test | private Collection<Field> getAllFields(final Object object) {
final Collection<Field> fields = new ArrayList<Field>();
fields.addAll(Arrays.asList(object.getClass().getDeclaredFields()));
// inspect super classes
Class<?> superClass = object.getClass().getSuperclass();
while (superClass != null) {
fields.addAll(Arrays.asList(superClass.getDeclaredFields()));
superClass = superClass.getSuperclass();
}
return fields;
} | java | {
"resource": ""
} |
q176850 | ImageUrlRewriter.rewrite | test | public String rewrite(final String cssUri, final String imageUrl) {
notNull(cssUri);
notNull(imageUrl);
if (StringUtils.isEmpty(imageUrl)) {
return imageUrl;
}
if (ServletContextUriLocator.isValid(cssUri)) {
if (ServletContextUriLocator.isValid(imageUrl)) {
return prependContextPath(imageUrl);
}
// Treat WEB-INF special case
if (ServletContextUriLocator.isProtectedResource(cssUri)) {
return context.proxyPrefix + computeNewImageLocation(cssUri, imageUrl);
}
// Compute the folder where the final css is located. This is important for computing image location after url
// rewriting.
// Prefix of the path to the overwritten image url. This will be of the following type: "../" or "../.." depending
// on the depth of the aggregatedFolderPath.
final String aggregatedPathPrefix = computeAggregationPathPrefix(context.aggregatedFolderPath);
LOG.debug("computed aggregatedPathPrefix {}", aggregatedPathPrefix);
String newImageLocation = computeNewImageLocation(aggregatedPathPrefix + cssUri, imageUrl);
if (newImageLocation.startsWith(ServletContextUriLocator.PREFIX)) {
newImageLocation = prependContextPath(newImageLocation);
}
LOG.debug("newImageLocation: {}", newImageLocation);
return newImageLocation;
}
if (ClasspathUriLocator.isValid(cssUri)) {
final String proxyUrl = context.proxyPrefix + computeNewImageLocation(cssUri, imageUrl);
final String contextRelativeUrl = prependContextPath(imageUrl);
//final String contextRelativeUrl = context.contextPath + imageUrl;
// leave imageUrl unchanged if it is a servlet context relative resource
return (ServletContextUriLocator.isValid(imageUrl) ? contextRelativeUrl : proxyUrl);
}
if (UrlUriLocator.isValid(cssUri)) {
final String computedCssUri = ServletContextUriLocator.isValid(imageUrl) ? computeCssUriForExternalServer(cssUri)
: cssUri;
return computeNewImageLocation(computedCssUri, imageUrl);
}
throw new WroRuntimeException("Could not replace imageUrl: " + imageUrl + ", contained at location: " + cssUri);
} | java | {
"resource": ""
} |
q176851 | ImageUrlRewriter.computeNewImageLocation | test | private String computeNewImageLocation(final String cssUri, final String imageUrl) {
LOG.debug("cssUri: {}, imageUrl {}", cssUri, imageUrl);
final String cleanImageUrl = cleanImageUrl(imageUrl);
// TODO move to ServletContextUriLocator as a helper method?
// for the following input: /a/b/c/1.css => /a/b/c/
int idxLastSeparator = cssUri.lastIndexOf(ServletContextUriLocator.PREFIX);
if (idxLastSeparator == -1) {
if (ClasspathUriLocator.isValid(cssUri)) {
idxLastSeparator = cssUri.lastIndexOf(ClasspathUriLocator.PREFIX);
// find the index of ':' character used by classpath prefix
if (idxLastSeparator >= 0) {
idxLastSeparator += ClasspathUriLocator.PREFIX.length() - 1;
}
}
if (idxLastSeparator < 0) {
throw new IllegalStateException("Invalid cssUri: " + cssUri + ". Should contain at least one '/' character!");
}
}
final String cssUriFolder = cssUri.substring(0, idxLastSeparator + 1);
// remove '/' from imageUrl if it starts with one.
final String processedImageUrl = cleanImageUrl.startsWith(ServletContextUriLocator.PREFIX) ? cleanImageUrl.substring(1)
: cleanImageUrl;
final String computedImageLocation = cleanPath(cssUriFolder + processedImageUrl);
LOG.debug("computedImageLocation: {}", computedImageLocation);
return computedImageLocation;
} | java | {
"resource": ""
} |
q176852 | BaseWroManagerFactory.addModelTransformer | test | public BaseWroManagerFactory addModelTransformer(final Transformer<WroModel> modelTransformer) {
if (modelTransformers == null) {
modelTransformers = new ArrayList<Transformer<WroModel>>();
}
this.modelTransformers.add(modelTransformer);
return this;
} | java | {
"resource": ""
} |
q176853 | ResourceBundleProcessor.serveProcessedBundle | test | public void serveProcessedBundle()
throws IOException {
final WroConfiguration configuration = context.getConfig();
final HttpServletRequest request = context.getRequest();
final HttpServletResponse response = context.getResponse();
OutputStream os = null;
try {
final CacheKey cacheKey = getSafeCacheKey(request);
initAggregatedFolderPath(request, cacheKey.getType());
final CacheValue cacheValue = cacheStrategy.get(cacheKey);
// TODO move ETag check in wroManagerFactory
final String ifNoneMatch = request.getHeader(HttpHeader.IF_NONE_MATCH.toString());
// enclose etag value in quotes to be compliant with the RFC
final String etagValue = String.format("\"%s\"", cacheValue.getHash());
if (etagValue != null && etagValue.equals(ifNoneMatch)) {
LOG.debug("ETag hash detected: {}. Sending {} status code", etagValue, HttpServletResponse.SC_NOT_MODIFIED);
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
// because we cannot return null, return a stream containing nothing.
// TODO close output stream?
return;
}
/**
* Set contentType before actual content is written, solves <br/>
* <a href="http://code.google.com/p/wro4j/issues/detail?id=341">issue341</a>
*/
response.setContentType(cacheKey.getType().getContentType() + "; charset=" + configuration.getEncoding());
// set ETag header
response.setHeader(HttpHeader.ETAG.toString(), etagValue);
os = response.getOutputStream();
if (cacheValue.getRawContent() != null) {
// use gziped response if supported & Set content length based on gzip flag
if (isGzipAllowed()) {
response.setContentLength(cacheValue.getGzippedContent().length);
// add gzip header and gzip response
response.setHeader(HttpHeader.CONTENT_ENCODING.toString(), "gzip");
response.setHeader("Vary", "Accept-Encoding");
IOUtils.write(cacheValue.getGzippedContent(), os);
} else {
//using getRawContent().length() is not the same and can return 2Bytes smaller size.
response.setContentLength(cacheValue.getRawContent().getBytes(configuration.getEncoding()).length);
IOUtils.write(cacheValue.getRawContent(), os, configuration.getEncoding());
}
}
} finally {
if (os != null) {
IOUtils.closeQuietly(os);
}
}
} | java | {
"resource": ""
} |
q176854 | ResourceBundleProcessor.initAggregatedFolderPath | test | private void initAggregatedFolderPath(final HttpServletRequest request, final ResourceType type) {
if (ResourceType.CSS == type && context.getAggregatedFolderPath() == null) {
final String requestUri = request.getRequestURI();
final String cssFolder = StringUtils.removeEnd(requestUri, FilenameUtils.getName(requestUri));
final String aggregatedFolder = StringUtils.removeStart(cssFolder, request.getContextPath());
LOG.debug("set aggregatedFolderPath: {}", aggregatedFolder);
Context.get().setAggregatedFolderPath(aggregatedFolder);
}
} | java | {
"resource": ""
} |
q176855 | CssVariablesProcessor.extractVariables | test | private Map<String, String> extractVariables(final String variablesBody) {
final Map<String, String> map = new HashMap<String, String>();
final Matcher m = PATTERN_VARIABLES_BODY.matcher(variablesBody);
LOG.debug("parsing variables body");
while (m.find()) {
final String key = m.group(1);
final String value = m.group(2);
if (map.containsKey(key)) {
LOG.warn("A duplicate variable name found with name: {} and value: {}.", key, value);
}
map.put(key, value);
}
return map;
} | java | {
"resource": ""
} |
q176856 | CssVariablesProcessor.parseCss | test | private String parseCss(final String css) {
// map containing variables & their values
final Map<String, String> map = new HashMap<String, String>();
final StringBuffer sb = new StringBuffer();
final Matcher m = PATTERN_VARIABLES_DEFINITION.matcher(css);
while (m.find()) {
final String variablesBody = m.group(1);
// LOG.debug("variables body: " + variablesBody);
// extract variables
map.putAll(extractVariables(variablesBody));
// remove variables definition
m.appendReplacement(sb, "");
}
m.appendTail(sb);
// LOG.debug("replaced variables: " + result);
return replaceVariables(sb.toString(), map);
} | java | {
"resource": ""
} |
q176857 | CssVariablesProcessor.replaceVariables | test | private String replaceVariables(final String css, final Map<String, String> variables) {
final StringBuffer sb = new StringBuffer();
final Matcher m = PATTERN_VARIABLE_HOLDER.matcher(css);
while (m.find()) {
final String oldMatch = m.group();
final String variableName = m.group(1);
final String variableValue = variables.get(variableName);
if (variableValue != null) {
final String newReplacement = oldMatch.replace(oldMatch, variableValue);
m.appendReplacement(sb, newReplacement.trim());
} else {
LOG.warn("No variable with name " + variableName + " was found!");
}
}
m.appendTail(sb);
return sb.toString();
} | java | {
"resource": ""
} |
q176858 | ProcessorDecorator.toPreProcessor | test | private static ResourcePreProcessor toPreProcessor(final ResourcePostProcessor postProcessor) {
return new AbstractProcessorDecoratorSupport<ResourcePostProcessor>(postProcessor) {
public void process(final Resource resource, final Reader reader, final Writer writer)
throws IOException {
postProcessor.process(reader, writer);
}
@Override
protected boolean isMinimizeInternal() {
return isMinimizeForProcessor(postProcessor);
}
@Override
protected SupportedResourceType getSupportedResourceTypeInternal() {
return getSupportedResourceTypeForProcessor(postProcessor);
}
@Override
public String toString() {
return postProcessor.toString();
}
};
} | java | {
"resource": ""
} |
q176859 | ProcessorDecorator.isEligible | test | public final boolean isEligible(final boolean minimize, final ResourceType searchedType) {
Validate.notNull(searchedType);
final SupportedResourceType supportedType = getSupportedResourceType();
final boolean isTypeSatisfied = supportedType == null
|| (supportedType != null && searchedType == supportedType.value());
final boolean isMinimizedSatisfied = minimize == true || !isMinimize();
return isTypeSatisfied && isMinimizedSatisfied;
} | java | {
"resource": ""
} |
q176860 | GzipFilter.doGzipResponse | test | private void doGzipResponse(final HttpServletRequest req, final HttpServletResponse response, final FilterChain chain)
throws IOException, ServletException {
LOG.debug("Applying gzip on resource: " + req.getRequestURI());
response.setHeader(HttpHeader.CONTENT_ENCODING.toString(), "gzip");
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final CountingOutputStream countingStream = new CountingOutputStream(new GZIPOutputStream(new BufferedOutputStream(
baos)));
// final GZIPOutputStream gzout = new GZIPOutputStream(new BufferedOutputStream(baos));
// Perform gzip operation in-memory before sending response
final HttpServletResponseWrapper wrappedResponse = new RedirectedStreamServletResponseWrapper(countingStream,
response);
chain.doFilter(req, wrappedResponse);
// close underlying stream
countingStream.close();
response.setContentLength(countingStream.getCount());
// avoid NO CONTENT error thrown by jetty when gzipping empty response
if (countingStream.getCount() > 0) {
IOUtils.write(baos.toByteArray(), response.getOutputStream());
}
} | java | {
"resource": ""
} |
q176861 | PathPatternProcessorDecorator.include | test | public static PathPatternProcessorDecorator include(final Object processor, final String... patterns) {
return new PathPatternProcessorDecorator(processor, true, patterns);
} | java | {
"resource": ""
} |
q176862 | PathPatternProcessorDecorator.exclude | test | public static PathPatternProcessorDecorator exclude(final Object processor, final String... patterns) {
return new PathPatternProcessorDecorator(processor, false, patterns);
} | java | {
"resource": ""
} |
q176863 | ResourceChangeHandler.create | test | public static ResourceChangeHandler create(final WroManagerFactory managerFactory, final Log log) {
notNull(managerFactory, "WroManagerFactory was not set");
notNull(log, "Log was not set");
return new ResourceChangeHandler().setManagerFactory(managerFactory).setLog(log);
} | java | {
"resource": ""
} |
q176864 | ResourceChangeHandler.remember | test | public void remember(final Resource resource) {
final WroManager manager = getManagerFactory().create();
final HashStrategy hashStrategy = manager.getHashStrategy();
final UriLocatorFactory locatorFactory = manager.getUriLocatorFactory();
if (rememberedSet.contains(resource.getUri())) {
// only calculate fingerprints and check imports if not already done
getLog().debug("Resource with uri '" + resource.getUri() + "' has already been updated in this run.");
} else {
try {
final String fingerprint = hashStrategy.getHash(locatorFactory.locate(resource.getUri()));
getBuildContextHolder().setValue(resource.getUri(), fingerprint);
rememberedSet.add(resource.getUri());
getLog().debug("Persist fingerprint for resource '" + resource.getUri() + "' : " + fingerprint);
if (resource.getType() == ResourceType.CSS) {
final Reader reader = new InputStreamReader(locatorFactory.locate(resource.getUri()));
getLog().debug("Check @import directive from " + resource);
// persist fingerprints in imported resources.
persistFingerprintsForCssImports(resource, reader);
}
} catch (final IOException e) {
getLog().debug("could not check fingerprint of resource: " + resource);
}
}
} | java | {
"resource": ""
} |
q176865 | ResourceChangeHandler.forEachCssImportApply | test | private void forEachCssImportApply(final Function<String, ChangeStatus> func, final Resource resource, final Reader reader)
throws IOException {
final ResourcePreProcessor processor = createCssImportProcessor(func);
InjectorBuilder.create(getManagerFactory()).build().inject(processor);
processor.process(resource, reader, new StringWriter());
} | java | {
"resource": ""
} |
q176866 | ResourceLintReport.filter | test | private List<T> filter(final Collection<T> collection) {
final List<T> nullFreeList = new ArrayList<T>();
if (collection != null) {
for (final T item : collection) {
if (item != null) {
nullFreeList.add(item);
}
}
}
return nullFreeList;
} | java | {
"resource": ""
} |
q176867 | DefaultGroupExtractor.isMinimized | test | public boolean isMinimized(final HttpServletRequest request) {
Validate.notNull(request);
final String minimizeAsString = request.getParameter(PARAM_MINIMIZE);
return !(Context.get().getConfig().isDebug() && "false".equalsIgnoreCase(minimizeAsString));
} | java | {
"resource": ""
} |
q176868 | AbstractCssImportPreProcessor.findImportedResources | test | private List<Resource> findImportedResources(final String resourceUri, final String cssContent)
throws IOException {
// it should be sorted
final List<Resource> imports = new ArrayList<Resource>();
final String css = cssContent;
final List<String> foundImports = findImports(css);
for (final String importUrl : foundImports) {
final Resource importedResource = createImportedResource(resourceUri, importUrl);
// check if already exist
if (imports.contains(importedResource)) {
LOG.debug("[WARN] Duplicate imported resource: {}", importedResource);
} else {
imports.add(importedResource);
onImportDetected(importedResource.getUri());
}
}
return imports;
} | java | {
"resource": ""
} |
q176869 | AbstractCssImportPreProcessor.computeAbsoluteUrl | test | private String computeAbsoluteUrl(final String relativeResourceUri, final String importUrl) {
final String folder = WroUtil.getFullPath(relativeResourceUri);
// remove '../' & normalize the path.
return StringUtils.cleanPath(folder + importUrl);
} | java | {
"resource": ""
} |
q176870 | AbstractConfigurableMultipleStrategy.createItemsAsString | test | public static String createItemsAsString(final String... items) {
final StringBuffer sb = new StringBuffer();
for (int i = 0; i < items.length; i++) {
sb.append(items[i]);
if (i < items.length - 1) {
sb.append(TOKEN_DELIMITER);
}
}
return sb.toString();
} | java | {
"resource": ""
} |
q176871 | AbstractConfigurableMultipleStrategy.getAliasList | test | private List<String> getAliasList(final String aliasCsv) {
LOG.debug("configured aliases: {}", aliasCsv);
final List<String> list = new ArrayList<String>();
if (!StringUtils.isEmpty(aliasCsv)) {
final String[] tokens = aliasCsv.split(TOKEN_DELIMITER);
for (final String token : tokens) {
list.add(token.trim());
}
}
return list;
} | java | {
"resource": ""
} |
q176872 | RhinoScriptBuilder.createContext | test | private ScriptableObject createContext(final ScriptableObject initialScope) {
final Context context = getContext();
context.setOptimizationLevel(-1);
// TODO redirect errors from System.err to LOG.error()
context.setErrorReporter(new ToolErrorReporter(false));
context.setLanguageVersion(Context.VERSION_1_8);
InputStream script = null;
final ScriptableObject scriptCommon = (ScriptableObject) context.initStandardObjects(initialScope);
try {
script = new AutoCloseInputStream(getClass().getResourceAsStream("commons.js"));
context.evaluateReader(scriptCommon, new InputStreamReader(script), "commons.js", 1, null);
} catch (final IOException e) {
throw new RuntimeException("Problem while evaluationg commons script.", e);
} finally {
IOUtils.closeQuietly(script);
}
return scriptCommon;
} | java | {
"resource": ""
} |
q176873 | RhinoScriptBuilder.evaluate | test | public Object evaluate(final Reader reader, final String sourceName)
throws IOException {
notNull(reader);
try {
return evaluate(IOUtils.toString(reader), sourceName);
} finally {
reader.close();
}
} | java | {
"resource": ""
} |
q176874 | RhinoScriptBuilder.evaluate | test | public Object evaluate(final String script, final String sourceName) {
notNull(script);
// make sure we have a context associated with current thread
try {
return getContext().evaluateString(scope, script, sourceName, 1, null);
} catch (final RhinoException e) {
final String message = RhinoUtils.createExceptionMessage(e);
LOG.error("JavaScriptException occured: {}", message);
throw new WroRuntimeException(message);
} finally {
// Rhino throws an exception when trying to exit twice. Make sure we don't get any exception
if (Context.getCurrentContext() != null) {
Context.exit();
}
}
} | java | {
"resource": ""
} |
q176875 | WroManager.process | test | public final void process()
throws IOException {
// reschedule cache & model updates
final WroConfiguration config = Context.get().getConfig();
cacheSchedulerHelper.scheduleWithPeriod(config.getCacheUpdatePeriod());
modelSchedulerHelper.scheduleWithPeriod(config.getModelUpdatePeriod());
resourceBundleProcessor.serveProcessedBundle();
} | java | {
"resource": ""
} |
q176876 | ResourceWatcherRequestHandler.isHandlerRequest | test | private boolean isHandlerRequest(final HttpServletRequest request) {
String apiHandlerValue = request.getParameter(PATH_API);
return PATH_HANDLER.equals(apiHandlerValue) && retrieveCacheKey(request) != null;
} | java | {
"resource": ""
} |
q176877 | ResourceWatcherRequestHandler.createHandlerRequestPath | test | public static String createHandlerRequestPath(final CacheKey cacheKey, final HttpServletRequest request) {
final String handlerQueryPath = getRequestHandlerPath(cacheKey.getGroupName(), cacheKey.getType());
return request.getServletPath() + handlerQueryPath;
} | java | {
"resource": ""
} |
q176878 | Wro4jMojo.rename | test | private String rename(final String group, final InputStream input)
throws Exception {
try {
final String newName = getManagerFactory().create().getNamingStrategy().rename(group, input);
groupNames.setProperty(group, newName);
return newName;
} catch (final IOException e) {
throw new MojoExecutionException("Error occured during renaming", e);
}
} | java | {
"resource": ""
} |
q176879 | Wro4jMojo.computeDestinationFolder | test | private File computeDestinationFolder(final ResourceType resourceType)
throws MojoExecutionException {
File folder = destinationFolder;
if (resourceType == ResourceType.JS) {
if (jsDestinationFolder != null) {
folder = jsDestinationFolder;
}
}
if (resourceType == ResourceType.CSS) {
if (cssDestinationFolder != null) {
folder = cssDestinationFolder;
}
}
getLog().info("folder: " + folder);
if (folder == null) {
throw new MojoExecutionException("Couldn't compute destination folder for resourceType: " + resourceType
+ ". That means that you didn't define one of the following parameters: "
+ "destinationFolder, cssDestinationFolder, jsDestinationFolder");
}
if (!folder.exists()) {
folder.mkdirs();
}
return folder;
} | java | {
"resource": ""
} |
q176880 | Wro4jMojo.processGroup | test | private void processGroup(final String group, final File parentFoder)
throws Exception {
ByteArrayOutputStream resultOutputStream = null;
InputStream resultInputStream = null;
try {
getLog().info("processing group: " + group);
// mock request
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getContextPath()).thenReturn(normalizeContextPath(contextPath));
Mockito.when(request.getRequestURI()).thenReturn(group);
// mock response
final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
resultOutputStream = new ByteArrayOutputStream();
Mockito.when(response.getOutputStream()).thenReturn(new DelegatingServletOutputStream(resultOutputStream));
// init context
final WroConfiguration config = Context.get().getConfig();
// the maven plugin should ignore empty groups, since it will try to process all types of resources.
config.setIgnoreEmptyGroup(true);
Context.set(Context.webContext(request, response, Mockito.mock(FilterConfig.class)), config);
Context.get().setAggregatedFolderPath(getAggregatedPathResolver().resolve());
// perform processing
getManagerFactory().create().process();
// encode version & write result to file
resultInputStream = new UnclosableBufferedInputStream(resultOutputStream.toByteArray());
final File destinationFile = new File(parentFoder, rename(group, resultInputStream));
final File parentFolder = destinationFile.getParentFile();
if (!parentFolder.exists()) {
// make directories if required
parentFolder.mkdirs();
}
destinationFile.createNewFile();
// allow the same stream to be read again
resultInputStream.reset();
getLog().debug("Created file: " + destinationFile.getName());
final OutputStream fos = new FileOutputStream(destinationFile);
// use reader to detect encoding
IOUtils.copy(resultInputStream, fos);
fos.close();
// delete empty files
if (destinationFile.length() == 0) {
getLog().debug("No content found for group: " + group);
destinationFile.delete();
} else {
getLog().info("file size: " + destinationFile.getName() + " -> " + destinationFile.length() + " bytes");
getLog().info(destinationFile.getAbsolutePath() + " (" + destinationFile.length() + " bytes" + ")");
}
} finally {
// instruct the build about the change in context of incremental build
if (getBuildContext() != null) {
getBuildContext().refresh(parentFoder);
}
if (resultOutputStream != null) {
resultOutputStream.close();
}
if (resultInputStream != null) {
resultInputStream.close();
}
}
} | java | {
"resource": ""
} |
q176881 | ResourceChangeDetector.checkChangeForGroup | test | public boolean checkChangeForGroup(final String uri, final String groupName) throws IOException {
notNull(uri);
notNull(groupName);
LOG.debug("group={}, uri={}", groupName, uri);
final ResourceChangeInfo resourceInfo = changeInfoMap.get(uri);
if (resourceInfo.isCheckRequiredForGroup(groupName)) {
final InputStream inputStream = locatorFactory.locate(uri);
try{
final String currentHash = hashStrategy.getHash(inputStream);
resourceInfo.updateHashForGroup(currentHash, groupName);
}finally{
IOUtils.closeQuietly(inputStream);
}
}
return resourceInfo.isChanged(groupName);
} | java | {
"resource": ""
} |
q176882 | StandaloneServletContextUriLocator.locate | test | @Override
public InputStream locate(final String uri)
throws IOException {
validState(standaloneContext != null, "Locator was not initialized properly. StandaloneContext missing.");
Exception lastException = null;
final String[] contextFolders = standaloneContext.getContextFolders();
for(final String contextFolder : contextFolders) {
try {
return locateStreamWithContextFolder(uri, contextFolder);
} catch(final IOException e) {
lastException = e;
LOG.debug("Could not locate: {} using contextFolder: {}", uri, contextFolder);
}
}
final String exceptionMessage = String.format("No valid resource '%s' found inside any of contextFolders: %s", uri,
Arrays.toString(standaloneContext.getContextFolders()));
throw new IOException(exceptionMessage, lastException);
} | java | {
"resource": ""
} |
q176883 | ObjectPoolHelper.createObjectPool | test | private GenericObjectPool<T> createObjectPool(final ObjectFactory<T> objectFactory) {
final GenericObjectPool<T> pool = newObjectPool(objectFactory);
notNull(pool);
return pool;
} | java | {
"resource": ""
} |
q176884 | JarWildcardStreamLocator.locateStream | test | @Override
public InputStream locateStream(final String uri, final File folder)
throws IOException {
notNull(folder);
final File jarPath = getJarFile(folder);
if (isSupported(jarPath)) {
return locateStreamFromJar(uri, jarPath);
}
return super.locateStream(uri, folder);
} | java | {
"resource": ""
} |
q176885 | JarWildcardStreamLocator.open | test | JarFile open(final File jarFile) throws IOException {
isTrue(jarFile.exists(), "The JAR file must exists.");
return new JarFile(jarFile);
} | java | {
"resource": ""
} |
q176886 | WebjarsUriLocator.extractPath | test | private String extractPath(final String uri) {
return DefaultWildcardStreamLocator.stripQueryPath(uri.replace(PREFIX, StringUtils.EMPTY));
} | java | {
"resource": ""
} |
q176887 | DefaultCacheKeyFactory.isMinimized | test | private boolean isMinimized(final HttpServletRequest request) {
return context.getConfig().isMinimizeEnabled() ? groupExtractor.isMinimized(request) : false;
} | java | {
"resource": ""
} |
q176888 | SimpleUriLocatorFactory.addLocator | test | public final SimpleUriLocatorFactory addLocator(final UriLocator... locators) {
for (final UriLocator locator : locators) {
uriLocators.add(locator);
}
return this;
} | java | {
"resource": ""
} |
q176889 | DefaultWroModelFactoryDecorator.decorate | test | public static WroModelFactory decorate(final WroModelFactory decorated,
final List<Transformer<WroModel>> modelTransformers) {
return decorated instanceof DefaultWroModelFactoryDecorator ? decorated : new DefaultWroModelFactoryDecorator(
decorated, modelTransformers);
} | java | {
"resource": ""
} |
q176890 | RubySassEngine.addRequire | test | public void addRequire(final String require) {
if (require != null && require.trim().length() > 0) {
requires.add(require.trim());
}
} | java | {
"resource": ""
} |
q176891 | RubySassEngine.process | test | public String process(final String content) {
if (isEmpty(content)) {
return StringUtils.EMPTY;
}
try {
synchronized(this) {
return engineInitializer.get().eval(buildUpdateScript(content)).toString();
}
} catch (final ScriptException e) {
throw new WroRuntimeException(e.getMessage(), e);
}
} | java | {
"resource": ""
} |
q176892 | ProgressIndicator.logSummary | test | public void logSummary() {
final String message = totalFoundErrors == 0 ? "No lint errors found." : String.format(
"Found %s errors in %s files.", totalFoundErrors, totalResourcesWithErrors);
log.info("----------------------------------------");
log.info(String.format("Total resources: %s", totalResources));
log.info(message);
log.info("----------------------------------------\n");
} | java | {
"resource": ""
} |
q176893 | ProgressIndicator.onProcessingResource | test | public synchronized void onProcessingResource(final Resource resource) {
totalResources++;
log.debug("processing resource: " + resource.getUri());
if (isLogRequired()) {
log.info("Processed until now: " + getTotalResources() + ". Last processed: " + resource.getUri());
updateLastInvocation();
}
} | java | {
"resource": ""
} |
q176894 | AbstractSynchronizedCacheStrategyDecorator.getLockForKey | test | private ReadWriteLock getLockForKey(final K key) {
final ReadWriteLock lock = locks.putIfAbsent(key, new ReentrantReadWriteLock());
return lock == null ? locks.get(key) : lock;
} | java | {
"resource": ""
} |
q176895 | NodeLessCssProcessor.createProcess | test | private Process createProcess(final File sourceFile)
throws IOException {
notNull(sourceFile);
final String[] commandLine = getCommandLine(sourceFile.getPath());
LOG.debug("CommandLine arguments: {}", Arrays.asList(commandLine));
return new ProcessBuilder(commandLine).redirectErrorStream(true).start();
} | java | {
"resource": ""
} |
q176896 | Selector.parseProperties | test | private Property[] parseProperties(final String contents) {
final String[] parts = contents.split(";");
final List<Property> resultsAsList = new ArrayList<Property>();
for (String part : parts) {
try {
// ignore empty parts
if (!StringUtils.isEmpty(part.trim())) {
resultsAsList.add(new Property(part));
}
} catch (final Exception e) {
LOG.warn(e.getMessage(), e);
}
}
return resultsAsList.toArray(new Property[resultsAsList.size()]);
} | java | {
"resource": ""
} |
q176897 | StopWatch.getTaskInfo | test | public TaskInfo[] getTaskInfo() {
if (!this.keepTaskList) {
throw new UnsupportedOperationException("Task info is not being kept!");
}
return (TaskInfo[])this.taskList.toArray(new TaskInfo[this.taskList.size()]);
} | java | {
"resource": ""
} |
q176898 | TypeScriptCompiler.getCompilationCommand | test | private String getCompilationCommand(final String input) {
return String.format("compilerWrapper.compile(%s, %s)", WroUtil.toJSMultiLineString(input),
ecmaScriptVersion);
} | java | {
"resource": ""
} |
q176899 | ResponseHeadersConfigurer.parseHeader | test | private void parseHeader(final String header) {
LOG.debug("parseHeader: {}", header);
final String headerName = header.substring(0, header.indexOf(":"));
if (!headersMap.containsKey(headerName)) {
final String value = header.substring(header.indexOf(":") + 1);
headersMap.put(headerName, StringUtils.trim(value));
}
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.