_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q167400 | EventStreams.repeatOnInvalidation | validation | public static <O extends Observable>
EventStream<O> repeatOnInvalidation(O observable) {
return new EventStreamBase<O>() {
@Override
protected Subscription observeInputs() {
InvalidationListener listener = obs -> emit(observable);
observable.addListener(listener);
return () -> observable.removeListener(listener);
}
@Override
protected void newObserver(Consumer<? super O> subscriber) {
subscriber.accept(observable);
}
};
} | java | {
"resource": ""
} |
q167401 | EventStreams.animationFrames | validation | public static EventStream<Long> animationFrames() {
return animationTicks()
.accumulate(t(0L, -1L), (state, now) -> state.map((d, last) -> {
return t(last == -1L ? 0L : now - last, now);
}))
.map(t -> t._1);
} | java | {
"resource": ""
} |
q167402 | EventStreams.merge | validation | public static <T> EventStream<T> merge(
ObservableSet<? extends EventStream<T>> set) {
return new EventStreamBase<T>() {
@Override
protected Subscription observeInputs() {
return Subscription.dynamic(set, s -> s.subscribe(this::emit));
}
};
} | java | {
"resource": ""
} |
q167403 | Collections.wrap | validation | @Deprecated
public static <E> ObservableList<E> wrap(javafx.collections.ObservableList<E> delegate) {
return LiveList.suspendable(delegate);
} | java | {
"resource": ""
} |
q167404 | Indicator.onWhile | validation | public <T> T onWhile(Supplier<T> f) {
try(Guard g = on()) {
return f.get();
}
} | java | {
"resource": ""
} |
q167405 | ProxyObservable.observe | validation | @Override
public final Subscription observe(O observer) {
P adapted = adaptObserver(observer);
underlying.addObserver(adapted);
return () -> underlying.removeObserver(adapted);
} | java | {
"resource": ""
} |
q167406 | Metadata.copy | validation | public Metadata copy()
{
Metadata result = new Metadata();
result.setEncoding(encoding);
result.setTrailingSlash(trailingSlash);
result.setLeadingSlash(leadingSlash);
return result;
} | java | {
"resource": ""
} |
q167407 | AbstractClassFinder.stripKnownPrefix | validation | protected String stripKnownPrefix(String str, String prefix)
{
int startIndex = str.lastIndexOf(prefix);
if (startIndex != -1)
{
return str.substring(startIndex + prefix.length());
}
return null;
} | java | {
"resource": ""
} |
q167408 | DigesterPrettyConfigParser.configureDigester | validation | private Digester configureDigester(final Digester digester)
{
/*
* We use the context class loader to resolve classes. This fixes
* ClassNotFoundExceptions on Geronimo.
*/
digester.setUseContextClassLoader(true);
/*
* Parse RewriteRules
*/
digester.addObjectCreate("pretty-config/rewrite", RewriteRule.class);
digester.addSetProperties("pretty-config/rewrite");
digester.addSetNext("pretty-config/rewrite", "addRewriteRule");
/*
* Create Mapping Object
*/
digester.addObjectCreate("pretty-config/url-mapping", UrlMapping.class);
digester.addSetProperties("pretty-config/url-mapping");
digester.addCallMethod("pretty-config/url-mapping/pattern", "setPattern", 1);
digester.addCallParam("pretty-config/url-mapping/pattern", 0, "value");
digester.addCallMethod("pretty-config/url-mapping/pattern", "setPattern", 0);
/*
* Parse View Id
*/
digester.addCallMethod("pretty-config/url-mapping/view-id", "setViewId", 1);
digester.addCallParam("pretty-config/url-mapping/view-id", 0, "value");
digester.addCallMethod("pretty-config/url-mapping/view-id", "setViewId", 0);
/*
* Parse Path Validators
*/
digester.addObjectCreate("pretty-config/url-mapping/pattern/validate", PathValidator.class);
digester.addSetProperties("pretty-config/url-mapping/pattern/validate");
digester.addSetNext("pretty-config/url-mapping/pattern/validate", "addPathValidator");
/*
* Parse Query Params
*/
digester.addObjectCreate("pretty-config/url-mapping/query-param", QueryParameter.class);
digester.addSetProperties("pretty-config/url-mapping/query-param");
digester.addCallMethod("pretty-config/url-mapping/query-param", "setExpression", 0);
digester.addSetNext("pretty-config/url-mapping/query-param", "addQueryParam");
/*
* Parse Action Methods
*/
digester.addObjectCreate("pretty-config/url-mapping/action", UrlAction.class);
digester.addSetProperties("pretty-config/url-mapping/action");
digester.addCallMethod("pretty-config/url-mapping/action", "setAction", 0);
digester.addSetNext("pretty-config/url-mapping/action", "addAction");
/*
* Add Mapping to Builder
*/
digester.addSetNext("pretty-config/url-mapping", "addMapping");
return digester;
} | java | {
"resource": ""
} |
q167409 | PrettyAnnotationHandler.processClassMappingAnnotations | validation | public String[] processClassMappingAnnotations(Class<?> clazz)
{
// list of all mapping IDs found on the class
List<String> classMappingIds = new ArrayList<String>();
// get reference to @URLMapping annotation
URLMapping mappingAnnotation = (URLMapping) clazz.getAnnotation(URLMapping.class);
// process annotation if it exists
if (mappingAnnotation != null)
{
String mappingId = processPrettyMappingAnnotation(clazz, mappingAnnotation);
classMappingIds.add(mappingId);
}
// container annotation
URLMappings mappingsAnnotation = (URLMappings) clazz.getAnnotation(URLMappings.class);
if (mappingsAnnotation != null)
{
// process all contained @URLMapping annotations
for (URLMapping child : mappingsAnnotation.mappings())
{
String mappingId = processPrettyMappingAnnotation(clazz, child);
classMappingIds.add(mappingId);
}
}
// return list of mappings found
return classMappingIds.toArray(new String[classMappingIds.size()]);
} | java | {
"resource": ""
} |
q167410 | PrettyAnnotationHandler.join | validation | private static String join(String[] values, String separator)
{
StringBuilder result = new StringBuilder();
if (values != null)
{
for (int i = 0; i < values.length; i++)
{
if (i > 0)
{
result.append(separator);
}
result.append(values[i]);
}
}
return result.toString();
} | java | {
"resource": ""
} |
q167411 | UserAgentUtil.initDeviceScan | validation | public void initDeviceScan()
{
// Save these properties to speed processing
this.isWebkit = detectWebkit();
this.isIphone = detectIphone();
this.isAndroid = detectAndroid();
this.isAndroidPhone = detectAndroidPhone();
// Generally, these tiers are the most useful for web development
this.isMobilePhone = detectMobileQuick();
this.isTierTablet = detectTierTablet();
this.isTierIphone = detectTierIphone();
// Optional: Comment these out if you NEVER use them
this.isTierRichCss = detectTierRichCss();
this.isTierGenericMobile = detectTierOtherPhones();
this.initCompleted = true;
} | java | {
"resource": ""
} |
q167412 | UserAgentUtil.detectIphone | validation | public boolean detectIphone()
{
if ((this.initCompleted == true) ||
(this.isIphone == true))
return this.isIphone;
// The iPad and iPod touch say they're an iPhone! So let's disambiguate.
if (userAgent.indexOf(deviceIphone) != -1 &&
!detectIpad() &&
!detectIpod()) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q167413 | UserAgentUtil.detectWebkit | validation | public boolean detectWebkit()
{
if ((this.initCompleted == true) ||
(this.isWebkit == true))
return this.isWebkit;
if (userAgent.indexOf(engineWebKit) != -1) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q167414 | UserAgentUtil.detectWindowsMobile | validation | public boolean detectWindowsMobile()
{
if (detectWindowsPhone()) {
return false;
}
// Most devices use 'Windows CE', but some report 'iemobile'
// and some older ones report as 'PIE' for Pocket IE.
// We also look for instances of HTC and Windows for many of their WinMo devices.
if (userAgent.indexOf(deviceWinMob) != -1
|| userAgent.indexOf(deviceWinMob) != -1
|| userAgent.indexOf(deviceIeMob) != -1
|| userAgent.indexOf(enginePie) != -1
|| (userAgent.indexOf(manuHtc) != -1 && userAgent.indexOf(deviceWindows) != -1)
|| (detectWapWml() && userAgent.indexOf(deviceWindows) != -1)) {
return true;
}
// Test for Windows Mobile PPC but not old Macintosh PowerPC.
if (userAgent.indexOf(devicePpc) != -1 &&
!(userAgent.indexOf(deviceMacPpc) != -1))
return true;
return false;
} | java | {
"resource": ""
} |
q167415 | UserAgentUtil.detectBlackBerry | validation | public boolean detectBlackBerry()
{
if (userAgent.indexOf(deviceBB) != -1 ||
httpAccept.indexOf(vndRIM) != -1)
return true;
if (detectBlackBerry10Phone())
return true;
return false;
} | java | {
"resource": ""
} |
q167416 | UserAgentUtil.detectS60OssBrowser | validation | public boolean detectS60OssBrowser()
{
// First, test for WebKit, then make sure it's either Symbian or S60.
if (detectWebkit()
&& (userAgent.indexOf(deviceSymbian) != -1
|| userAgent.indexOf(deviceS60) != -1)) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q167417 | UserAgentUtil.detectPalmOS | validation | public boolean detectPalmOS()
{
// Make sure it's not WebOS first
if (detectPalmWebOS())
return false;
// Most devices nowadays report as 'Palm', but some older ones reported as Blazer or Xiino.
if (userAgent.indexOf(devicePalm) != -1
|| userAgent.indexOf(engineBlazer) != -1
|| userAgent.indexOf(engineXiino) != -1) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q167418 | UserAgentUtil.detectOperaAndroidPhone | validation | public boolean detectOperaAndroidPhone()
{
if (userAgent.indexOf(engineOpera) != -1
&& (userAgent.indexOf(deviceAndroid) != -1
&& userAgent.indexOf(mobi) != -1)) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q167419 | UserAgentUtil.detectOperaAndroidTablet | validation | public boolean detectOperaAndroidTablet()
{
if (userAgent.indexOf(engineOpera) != -1
&& (userAgent.indexOf(deviceAndroid) != -1
&& userAgent.indexOf(deviceTablet) != -1)) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q167420 | UserAgentUtil.detectMaemoTablet | validation | public boolean detectMaemoTablet()
{
if (userAgent.indexOf(maemo) != -1) {
return true;
}
else if (userAgent.indexOf(linux) != -1
&& userAgent.indexOf(deviceTablet) != -1
&& !detectWebOSTablet()
&& !detectAndroid()) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q167421 | UserAgentUtil.detectMobileQuick | validation | public boolean detectMobileQuick()
{
// Let's exclude tablets
if (detectTierTablet())
return false;
if ((initCompleted == true) ||
(isMobilePhone == true))
return isMobilePhone;
// Most mobile browsing is done on smartphones
if (detectSmartphone())
return true;
if (detectWapWml()
|| detectBrewDevice()
|| detectOperaMobile())
return true;
if ((userAgent.indexOf(engineObigo) != -1)
|| (userAgent.indexOf(engineNetfront) != -1)
|| (userAgent.indexOf(engineUpBrowser) != -1)
|| (userAgent.indexOf(engineOpenWeb) != -1))
return true;
if (detectDangerHiptop()
|| detectMidpCapable()
|| detectMaemoTablet()
|| detectArchos())
return true;
if ((userAgent.indexOf(devicePda) != -1) &&
(userAgent.indexOf(disUpdate) < 0)) // no index found
return true;
if (userAgent.indexOf(mobile) != -1)
return true;
// We also look for Kindle devices
if (detectKindle()
|| detectAmazonSilk())
return true;
return false;
} | java | {
"resource": ""
} |
q167422 | UserAgentUtil.detectTierIphone | validation | public boolean detectTierIphone()
{
if ((this.initCompleted == true) ||
(this.isTierIphone == true))
return this.isTierIphone;
if (detectIphoneOrIpod()
|| detectAndroidPhone()
|| detectWindowsPhone()
|| detectBlackBerry10Phone()
|| (detectBlackBerryWebKit()
&& detectBlackBerryTouch())
|| detectPalmWebOS()
|| detectBada()
|| detectTizen()
|| detectGamingHandheld()) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q167423 | UserAgentUtil.detectTierOtherPhones | validation | public boolean detectTierOtherPhones()
{
if ((this.initCompleted == true) ||
(this.isTierGenericMobile == true))
return this.isTierGenericMobile;
// Exclude devices in the other 2 categories
if (detectMobileLong()
&& !detectTierIphone()
&& !detectTierRichCss())
return true;
return false;
} | java | {
"resource": ""
} |
q167424 | Expressions.isEL | validation | public static boolean isEL(final String value)
{
if (value == null)
{
return false;
}
return elPattern.matcher(value).matches();
} | java | {
"resource": ""
} |
q167425 | Expressions.containsEL | validation | public static boolean containsEL(final String value)
{
if (value == null)
{
return false;
}
return elPattern.matcher(value).find();
} | java | {
"resource": ""
} |
q167426 | LocationBehavior.buildScriptInternal | validation | private String buildScriptInternal(final String url)
{
StringBuilder builder = new StringBuilder();
builder.append("window.location.href = '");
builder.append(url);
builder.append("'; return false;");
return builder.toString();
} | java | {
"resource": ""
} |
q167427 | El.method | validation | public static El method(final String retrieve, final String submit)
{
return new ElMethod(new ConstantExpression(retrieve), new ConstantExpression(submit));
} | java | {
"resource": ""
} |
q167428 | ByteCodeFilter.containsFieldDescriptor | validation | private boolean containsFieldDescriptor(String str)
{
for (String descriptor : fieldDescriptors) {
if (str.contains(descriptor)) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q167429 | ProxyServlet.copyResponseHeaders | validation | protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletResponse servletResponse)
{
for (Header header : proxyResponse.getAllHeaders())
{
if (hopByHopHeaders.containsHeader(header.getName()))
continue;
servletResponse.addHeader(header.getName(), header.getValue());
}
} | java | {
"resource": ""
} |
q167430 | ProxyServlet.encodeUriQuery | validation | protected static CharSequence encodeUriQuery(CharSequence in)
{
/*
* Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things. TODO:
* replace/compare to with Rewrite Encoding
*/
StringBuilder outBuf = null;
Formatter formatter = null;
for (int i = 0; i < in.length(); i++)
{
char c = in.charAt(i);
boolean escape = true;
if (c < 128)
{
if (asciiQueryChars.get(c))
{
escape = false;
}
}
else if (!Character.isISOControl(c) && !Character.isSpaceChar(c))
{
/*
* not-ascii
*/
escape = false;
}
if (!escape)
{
if (outBuf != null)
outBuf.append(c);
}
else
{
/*
* escape
*/
if (outBuf == null)
{
outBuf = new StringBuilder(in.length() + 5 * 3);
outBuf.append(in, 0, i);
formatter = new Formatter(outBuf);
}
/*
* leading %, 0 padded, width 2, capital hex
*/
formatter.format("%%%02X", (int) c);// TODO
}
}
return outBuf != null ? outBuf : in;
} | java | {
"resource": ""
} |
q167431 | URLBuilder.toURI | validation | public URI toURI()
{
try {
URI uri = new URI(toURL());
return uri;
}
catch (URISyntaxException e) {
throw new IllegalStateException("URL cannot be parsed.", e);
}
} | java | {
"resource": ""
} |
q167432 | QueryString.build | validation | public static QueryString build(final String url)
{
QueryString queryString = new QueryString();
queryString.addParameters(url);
return queryString;
} | java | {
"resource": ""
} |
q167433 | QueryString.getParameter | validation | public String getParameter(final String name)
{
List<String> values = parameters.get(name);
if (values == null)
{
return null;
}
if (values.size() == 0)
{
return "";
}
return values.get(0);
} | java | {
"resource": ""
} |
q167434 | QueryString.getParameterValues | validation | public String[] getParameterValues(final String name)
{
List<String> values = parameters.get(name);
if (values == null)
{
return null;
}
return values.toArray(new String[values.size()]);
} | java | {
"resource": ""
} |
q167435 | QueryString.addParameters | validation | public void addParameters(String url)
{
if ((url != null) && !"".equals(url))
{
url = url.trim();
if (url.length() > 1)
{
if (url.contains("?"))
{
url = url.substring(url.indexOf('?') + 1);
}
String pairs[] = url.split("&(amp;)?");
for (String pair : pairs)
{
String name;
String value;
int pos = pair.indexOf('=');
// for "n=", the value is "", for "n", the value is null
if (pos == -1)
{
name = pair;
value = null;
}
else
{
try
{
// FIXME This probably shouldn't be happening here.
name = URLDecoder.decode(pair.substring(0, pos), "UTF-8");
value = URLDecoder.decode(pair.substring(pos + 1, pair.length()), "UTF-8");
}
catch (IllegalArgumentException e)
{
// thrown by URLDecoder if character decoding fails
log.warn("Ignoring invalid query parameter: " + pair);
continue;
}
catch (UnsupportedEncodingException e)
{
throw new PrettyException(
"UTF-8 encoding not supported. Something is seriously wrong with your environment.");
}
}
List<String> list = parameters.get(name);
if (list == null)
{
list = new ArrayList<String>();
parameters.put(name, list);
}
list.add(value);
}
}
}
return;
} | java | {
"resource": ""
} |
q167436 | RewriteViewHandler.deriveViewId | validation | @Override
public String deriveViewId(final FacesContext context, final String rawViewId)
{
String canonicalViewId = new URLDuplicatePathCanonicalizer().canonicalize(rawViewId);
return parent.deriveViewId(context, canonicalViewId);
} | java | {
"resource": ""
} |
q167437 | UrlMapping.getPatternParser | validation | public URLPatternParser getPatternParser()
{
if ((parser == null) && (pattern != null))
{
this.parser = new URLPatternParser(pattern);
}
return parser;
} | java | {
"resource": ""
} |
q167438 | UrlMapping.getValidatorsForPathParam | validation | public List<PathValidator> getValidatorsForPathParam(final PathParameter param)
{
List<PathValidator> result = new ArrayList<PathValidator>();
for (PathValidator pv : pathValidators)
{
if (pv.getIndex() == param.getPosition())
{
result.add(pv);
}
}
return result;
} | java | {
"resource": ""
} |
q167439 | QueryStringBuilder.createFromEncoded | validation | public static QueryStringBuilder createFromEncoded(final String parameters)
{
QueryStringBuilder queryString = new QueryStringBuilder();
queryString.addParameters(parameters);
return queryString;
} | java | {
"resource": ""
} |
q167440 | QueryStringBuilder.extractQuery | validation | public static String extractQuery(String url)
{
if (url != null)
{
int index = url.indexOf('?');
if (index >= 0)
{
url = url.substring(index + 1);
}
}
return url;
} | java | {
"resource": ""
} |
q167441 | QueryStringBuilder.addParameter | validation | public void addParameter(final String name, final String... values)
{
Map<String, String[]> parameter = new LinkedHashMap<String, String[]>();
parameter.put(name, values);
addParameterArrays(parameter);
} | java | {
"resource": ""
} |
q167442 | DispatchType.getDispatcherTypeProviders | validation | @SuppressWarnings("unchecked")
private List<DispatcherTypeProvider> getDispatcherTypeProviders(HttpServletRewrite event)
{
List<DispatcherTypeProvider> providers = (List<DispatcherTypeProvider>)
event.getRequest().getAttribute(PROVIDER_KEY);
if (providers == null) {
providers = Iterators.asList(ServiceLoader.loadTypesafe(DispatcherTypeProvider.class).iterator());
Collections.sort(providers, new WeightedComparator());
event.getRequest().setAttribute(PROVIDER_KEY, providers);
}
return providers;
} | java | {
"resource": ""
} |
q167443 | Conditions.getNegationCount | validation | public static int getNegationCount(final EvaluationContext context)
{
if (context == null)
return 0;
Integer count = (Integer)context.get(NEGATION_COUNT_KEY);
return count == null ? 0 : count;
} | java | {
"resource": ""
} |
q167444 | Navigate.with | validation | public Navigate with(CharSequence name, Object value)
{
Assert.notNull(name, "name must not be null");
if (value != null) {
parameters.put(name.toString(), value.toString());
}
return this;
} | java | {
"resource": ""
} |
q167445 | Navigate.buildStandardOutcome | validation | private String buildStandardOutcome()
{
StringBuilder outcome = new StringBuilder();
outcome.append(viewId);
boolean first = true;
for (Entry<String, List<String>> param : parameters.entrySet()) {
for (String value : param.getValue()) {
outcome.append(first ? '?' : '&');
outcome.append(param.getKey());
outcome.append('=');
outcome.append(value);
first = false;
}
}
return outcome.toString();
} | java | {
"resource": ""
} |
q167446 | WebClassesFinder.handleClassEntry | validation | private void handleClassEntry(String entryName, ClassVisitor visitor)
{
// build class name from relative name
String className = getClassName(entryName.substring(CLASSES_FOLDER.length()));
// check filter
if (mustProcessClass(className) && !processedClasses.contains(className))
{
// mark this class as processed
processedClasses.add(className);
// the class file stream
InputStream classFileStream = null;
// close the stream in finally block
try
{
/*
* Try to open the .class file. if this isn't possible, we will scan it anyway.
*/
classFileStream = servletContext.getResourceAsStream(entryName);
if (classFileStream == null)
{
if (log.isDebugEnabled())
{
log.debug("Could not obtain InputStream for class file: " + entryName);
}
}
// analyze the class (with or without classFileStream)
processClass(className, classFileStream, visitor);
}
finally
{
try
{
if (classFileStream != null)
{
classFileStream.close();
}
}
catch (IOException e)
{
if (log.isDebugEnabled())
{
log.debug("Failed to close input stream: " + e.getMessage());
}
}
}
}
} | java | {
"resource": ""
} |
q167447 | AddressBuilder.queryLiteral | validation | AddressBuilderQuery queryLiteral(String query)
{
if (query != null)
{
if (query.startsWith("?"))
query = query.substring(1);
/*
* Linked hash map is important here in order to retain the order of query parameters.
*/
Map<CharSequence, List<CharSequence>> params = new LinkedHashMap<CharSequence, List<CharSequence>>();
query = decodeHTMLAmpersands(query);
int index = 0;
while ((index = query.indexOf('&')) >= 0 || !query.isEmpty())
{
String pair = query;
if (index >= 0)
{
pair = query.substring(0, index);
query = query.substring(index);
if (!query.isEmpty())
query = query.substring(1);
}
else
query = "";
String name;
String value;
int pos = pair.indexOf('=');
// for "n=", the value is "", for "n", the value is null
if (pos == -1)
{
name = pair;
value = null;
}
else
{
name = pair.substring(0, pos);
value = pair.substring(pos + 1, pair.length());
}
List<CharSequence> list = params.get(name);
if (list == null)
{
list = new ArrayList<CharSequence>();
params.put(name, list);
}
list.add(value);
}
for (Entry<CharSequence, List<CharSequence>> entry : params.entrySet()) {
query(entry.getKey(), entry.getValue().toArray());
}
}
return new AddressBuilderQuery(this);
} | java | {
"resource": ""
} |
q167448 | EncodeQuery.excluding | validation | public EncodeQuery excluding(final String... params)
{
if ((params != null) && (params.length > 0))
this.excludedParams.addAll(Arrays.asList(params));
return this;
} | java | {
"resource": ""
} |
q167449 | ExtractedValuesURLBuilder.buildURL | validation | public URL buildURL(final UrlMapping mapping)
{
URL result = null;
String expression = "";
Object value = null;
try
{
FacesContext context = FacesContext.getCurrentInstance();
URLPatternParser parser = mapping.getPatternParser();
List<PathParameter> parameters = parser.getPathParameters();
List<String> parameterValues = new ArrayList<String>();
for (PathParameter injection : parameters)
{
// read value of the path parameter
expression = injection.getExpression().getELExpression();
value = elUtils.getValue(context, expression);
if (value == null)
{
throw new PrettyException("PrettyFaces: Exception occurred while building URL for MappingId < "
+ mapping.getId() + " >, Required value " + " < " + expression + " > was null");
}
// convert the value to a string using the correct converter
Converter converter = context.getApplication().createConverter(value.getClass());
if (converter != null)
{
String convertedValue = converter.getAsString(context, new NullComponent(), value);
if (convertedValue == null)
{
throw new PrettyException("PrettyFaces: The converter <" + converter.getClass().getName()
+ "> returned null while converting the object <" + value.toString() + ">!");
}
value = convertedValue;
}
parameterValues.add(value.toString());
}
result = parser.getMappedURL(parameterValues).encode();
}
catch (ELException e)
{
throw new PrettyException("PrettyFaces: Exception occurred while building URL for MappingId < "
+ mapping.getId() + " >, Error occurred while extracting values from backing bean" + " < "
+ expression + ":" + value + " >", e);
}
return result;
} | java | {
"resource": ""
} |
q167450 | PrettyContext.sendError | validation | public void sendError(int code, String message, HttpServletResponse response)
{
Assert.notNull(response, "HttpServletResponse argument was null");
try
{
if (message != null)
{
response.sendError(code, message);
}
else
{
response.sendError(code);
}
}
catch (IOException e)
{
throw new IllegalStateException("Failed to send error code: " + code, e);
}
} | java | {
"resource": ""
} |
q167451 | ClassVisitorImpl.visit | validation | @Override
public void visit(Class<?> clazz)
{
ClassContextImpl context = new ClassContextImpl(builder, clazz);
context.put(clazz, payload);
if (log.isTraceEnabled())
{
log.trace("Scanning class: {}", clazz.getName());
}
// first process the class
visit(clazz, context);
// only process fields and classes if a rule building has been started
if (context.hasRuleBuildingStarted()) {
// walk up the inheritance hierarchy
Class<?> currentType = clazz;
while (currentType != null) {
// then process the fields
for (Field field : currentType.getDeclaredFields())
{
visit(field, new FieldContextImpl(context, field));
}
// then the methods
for (Method method : currentType.getDeclaredMethods())
{
MethodContextImpl methodContext = new MethodContextImpl(context, method);
visit(method, methodContext);
// then the method parameters
for (int i = 0; i < method.getParameterTypes().length; i++)
{
ParameterImpl parameter = new ParameterImpl(method, method.getParameterTypes()[i],
method.getParameterAnnotations()[i], i);
visit(parameter, new ParameterContextImpl(methodContext, parameter));
}
}
currentType = currentType.getSuperclass();
}
}
} | java | {
"resource": ""
} |
q167452 | RewriteNavigationHandler.prependContextPath | validation | private String prependContextPath(ExternalContext externalContext, String url)
{
String contextPath = externalContext.getRequestContextPath();
if ("/".equals(contextPath) || (url.startsWith(contextPath))) {
return url;
}
return contextPath + url;
} | java | {
"resource": ""
} |
q167453 | OutboundRewriteRuleAdaptor.stripContextPath | validation | private String stripContextPath(final String contextPath, String uri)
{
if (!contextPath.equals("/") && uri.startsWith(contextPath))
{
uri = uri.substring(contextPath.length());
}
return uri;
} | java | {
"resource": ""
} |
q167454 | LocaleTransposition.translate | validation | private String translate(String lang, String value)
{
String translatation = null;
if (value != null)
{
if (!bundleMap.containsKey(lang))
{
Locale locale = new Locale(lang);
try
{
ResourceBundle loadedBundle = ResourceBundle.getBundle(bundleName, locale,
ResourceBundle.Control.getNoFallbackControl(ResourceBundle.Control.FORMAT_DEFAULT));
bundleMap.put(lang, loadedBundle);
}
catch (MissingResourceException e)
{
return null;
}
}
try
{
// can we received more than one path section? e.g./search/service/
translatation = bundleMap.get(lang).getString(value);
}
catch (MissingResourceException mrEx)
{
// ignore
}
}
return translatation;
} | java | {
"resource": ""
} |
q167455 | DynaviewEngine.buildDynaViewId | validation | public String buildDynaViewId(final String facesServletMapping)
{
StringBuffer result = new StringBuffer();
Map<Pattern, String> patterns = new LinkedHashMap<Pattern, String>();
Pattern pathMapping = Pattern.compile("^(/.*/)\\*$");
Pattern extensionMapping = Pattern.compile("^\\*(\\..*)$");
Pattern defaultMapping = Pattern.compile("^/$");
patterns.put(pathMapping, "$1" + DYNAVIEW + ".jsf");
patterns.put(extensionMapping, "/" + DYNAVIEW + "$1");
patterns.put(defaultMapping, "/" + DYNAVIEW + ".jsf");
boolean matched = false;
Iterator<Pattern> iterator = patterns.keySet().iterator();
while ((matched == false) && iterator.hasNext())
{
Pattern p = iterator.next();
Matcher m = p.matcher(facesServletMapping);
if (m.matches())
{
String replacement = patterns.get(p);
m.appendReplacement(result, replacement);
matched = true;
}
}
if (matched == false)
{
// This is an exact url-mapping, use it.
result.append(facesServletMapping);
}
return result.toString();
} | java | {
"resource": ""
} |
q167456 | DynaviewEngine.processDynaView | validation | public void processDynaView(final PrettyContext prettyContext, final FacesContext facesContext)
{
log.trace("Requesting DynaView processing for: " + prettyContext.getRequestURL());
String viewId = "";
try
{
viewId = prettyContext.getCurrentViewId();
log.trace("Invoking DynaView method: " + viewId);
Object result = computeDynaViewId(facesContext);
if (result instanceof String)
{
viewId = (String) result;
log.trace("Forwarding to DynaView: " + viewId);
prettyContext.setDynaviewProcessed(true);
facesContext.getExternalContext().dispatch(viewId);
facesContext.responseComplete();
}
}
catch (Exception e)
{
log.error("Failed to process dynaview", e);
PrettyRedirector prettyRedirector = new PrettyRedirector();
prettyRedirector.send404(facesContext);
throw new PrettyException("Could not forward to view: " + viewId + "", e);
}
} | java | {
"resource": ""
} |
q167457 | CdiServiceLocator.getRequiredType | validation | private Type getRequiredType(Class<?> clazz)
{
TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
if (typeParameters.length > 0) {
Type[] actualTypeParameters = new Type[typeParameters.length];
for (int i = 0; i < typeParameters.length; i++) {
actualTypeParameters[i] = new WildcardTypeImpl(new Type[] { Object.class }, new Type[] {});
}
return new ParameterizedTypeImpl(clazz, actualTypeParameters, null);
}
return clazz;
} | java | {
"resource": ""
} |
q167458 | AnnotationProxyFactory.getAnnotationProxy | validation | @SuppressWarnings("unchecked")
public static <T extends Annotation> T getAnnotationProxy(Annotation customAnnotation, Class<T> referenceAnnotation) {
InvocationHandler handler = new AnnotationInvocationHandler(customAnnotation);
return (T)Proxy.newProxyInstance(referenceAnnotation.getClassLoader(), new Class[] { referenceAnnotation }, handler);
} | java | {
"resource": ""
} |
q167459 | ObjectGraphWalker.getFilteredFields | validation | private Collection<Field> getFilteredFields(Class<?> refClass) {
SoftReference<Collection<Field>> ref = fieldCache.get(refClass);
Collection<Field> fieldList = ref != null ? ref.get() : null;
if (fieldList != null) {
return fieldList;
} else {
Collection<Field> result;
result = sizeOfFilter.filterFields(refClass, getAllFields(refClass));
if (USE_VERBOSE_DEBUG_LOGGING && LOG.isDebugEnabled()) {
for (Field field : result) {
if (Modifier.isTransient(field.getModifiers())) {
LOG.debug("SizeOf engine walking transient field '{}' of class {}", field.getName(), refClass.getName());
}
}
}
fieldCache.put(refClass, new SoftReference<>(result));
return result;
}
} | java | {
"resource": ""
} |
q167460 | ObjectGraphWalker.getAllFields | validation | private static Collection<Field> getAllFields(Class<?> refClass) {
Collection<Field> fields = new ArrayList<>();
for (Class<?> klazz = refClass; klazz != null; klazz = klazz.getSuperclass()) {
for (Field field : klazz.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers()) &&
!field.getType().isPrimitive()) {
try {
field.setAccessible(true);
} catch (SecurityException e) {
LOG.error("Security settings prevent Ehcache from accessing the subgraph beneath '{}'" +
" - cache sizes may be underestimated as a result", field, e);
continue;
}
fields.add(field);
}
}
}
return fields;
} | java | {
"resource": ""
} |
q167461 | WeakIdentityConcurrentMap.put | validation | public V put(K key, V value) {
cleanUp();
return map.put(new IdentityWeakReference<>(key, queue), value);
} | java | {
"resource": ""
} |
q167462 | WeakIdentityConcurrentMap.remove | validation | public V remove(K key) {
cleanUp();
return map.remove(new IdentityWeakReference<>(key, queue));
} | java | {
"resource": ""
} |
q167463 | AgentLoader.loadAgent | validation | static boolean loadAgent() {
synchronized (AgentLoader.class.getName().intern()) {
if (!agentIsAvailable() && VIRTUAL_MACHINE_LOAD_AGENT != null) {
try {
warnIfOSX();
String name = ManagementFactory.getRuntimeMXBean().getName();
Object vm = VIRTUAL_MACHINE_ATTACH.invoke(null, name.substring(0, name.indexOf('@')));
try {
File agent = getAgentFile();
LOGGER.info("Trying to load agent @ {}", agent);
if (agent != null) {
VIRTUAL_MACHINE_LOAD_AGENT.invoke(vm, agent.getAbsolutePath());
}
} finally {
VIRTUAL_MACHINE_DETACH.invoke(vm);
}
} catch (InvocationTargetException ite) {
Throwable cause = ite.getCause();
LOGGER.info("Failed to attach to VM and load the agent: {}: {}", cause.getClass(), cause.getMessage());
} catch (Throwable t) {
LOGGER.info("Failed to attach to VM and load the agent: {}: {}", t.getClass(), t.getMessage());
}
}
final boolean b = agentIsAvailable();
if (b) {
LOGGER.info("Agent successfully loaded and available!");
}
return b;
}
} | java | {
"resource": ""
} |
q167464 | AgentLoader.agentIsAvailable | validation | static boolean agentIsAvailable() {
try {
if (instrumentation == null) {
instrumentation = (Instrumentation)System.getProperties().get(INSTRUMENTATION_INSTANCE_SYSTEM_PROPERTY_NAME);
}
if (instrumentation == null) {
Class<?> sizeOfAgentClass = ClassLoader.getSystemClassLoader().loadClass(SIZEOF_AGENT_CLASSNAME);
Method getInstrumentationMethod = sizeOfAgentClass.getMethod("getInstrumentation");
instrumentation = (Instrumentation)getInstrumentationMethod.invoke(sizeOfAgentClass);
}
return instrumentation != null;
} catch (SecurityException e) {
LOGGER.warn("Couldn't access the system classloader because of the security policies applied by " +
"the security manager. You either want to loosen these, so ClassLoader.getSystemClassLoader() and " +
"reflection API calls are permitted or the sizing will be done using some other mechanism.\n" +
"Alternatively, set the system property org.ehcache.sizeof.agent.instrumentationSystemProperty to true " +
"to have the agent put the required instances in the System Properties for the loader to access.");
return false;
} catch (Throwable e) {
return false;
}
} | java | {
"resource": ""
} |
q167465 | ResourceUtils.copyFile | validation | public static void copyFile( PlexusIoResource in, File outFile )
throws IOException
{
InputStream input = null;
OutputStream output = null;
try
{
input = in.getContents();
output = new FileOutputStream( outFile );
IOUtil.copy( input, output );
}
finally
{
IOUtil.close( input );
IOUtil.close( output );
}
} | java | {
"resource": ""
} |
q167466 | ResourceUtils.isSame | validation | public static boolean isSame( PlexusIoResource resource, File file )
{
if ( resource instanceof FileSupplier )
{
File resourceFile = ((FileSupplier) resource).getFile();
return file.equals( resourceFile );
}
return false;
} | java | {
"resource": ""
} |
q167467 | WarArchiver.addWebinf | validation | public void addWebinf( File directoryName, String[] includes, String[] excludes )
throws ArchiverException
{
addDirectory( directoryName, "WEB-INF/", includes, excludes );
} | java | {
"resource": ""
} |
q167468 | WarArchiver.initZipOutputStream | validation | protected void initZipOutputStream( ZipArchiveOutputStream zOut )
throws ArchiverException, IOException
{
// If no webxml file is specified, it's an error.
if ( expectWebXml && deploymentDescriptor == null && !isInUpdateMode() )
{
throw new ArchiverException( "webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)" );
}
super.initZipOutputStream( zOut );
} | java | {
"resource": ""
} |
q167469 | WarArchiver.zipFile | validation | protected void zipFile( ArchiveEntry entry, ZipArchiveOutputStream zOut, String vPath )
throws IOException, ArchiverException
{
// If the file being added is WEB-INF/web.xml, we warn if it's
// not the one specified in the "webxml" attribute - or if
// it's being added twice, meaning the same file is specified
// by the "webxml" attribute and in a <fileset> element.
if ( vPath.equalsIgnoreCase( "WEB-INF/web.xml" ) )
{
if ( descriptorAdded || ( expectWebXml
&& ( deploymentDescriptor == null
|| !ResourceUtils.isCanonicalizedSame( entry.getResource(), deploymentDescriptor ) ) ) )
{
getLogger().warn( "Warning: selected " + archiveType
+ " files include a WEB-INF/web.xml which will be ignored "
+ "\n(webxml attribute is missing from "
+ archiveType + " task, or ignoreWebxml attribute is specified as 'true')" );
}
else
{
super.zipFile( entry, zOut, vPath );
descriptorAdded = true;
}
}
else
{
super.zipFile( entry, zOut, vPath );
}
} | java | {
"resource": ""
} |
q167470 | Manifest.getDefaultManifest | validation | public static Manifest getDefaultManifest()
throws ArchiverException
{
try
{
String defManifest = "/org/codehaus/plexus/archiver/jar/defaultManifest.mf";
InputStream in = Manifest.class.getResourceAsStream( defManifest );
if ( in == null )
{
throw new ArchiverException( "Could not find default manifest: " + defManifest );
}
try
{
Manifest defaultManifest = new Manifest( new InputStreamReader( in, "UTF-8" ) );
defaultManifest.getMainAttributes().putValue( "Created-By", System.getProperty(
"java.vm.version" ) + " (" + System.getProperty( "java.vm.vendor" ) + ")" );
return defaultManifest;
}
catch ( UnsupportedEncodingException e )
{
return new Manifest( new InputStreamReader( in ) );
}
finally
{
IOUtil.close( in );
}
}
catch ( ManifestException e )
{
throw new ArchiverException( "Default manifest is invalid !!", e );
}
catch ( IOException e )
{
throw new ArchiverException( "Unable to read default manifest", e );
}
} | java | {
"resource": ""
} |
q167471 | Manifest.addConfiguredSection | validation | public void addConfiguredSection( Section section )
throws ManifestException
{
String sectionName = section.getName();
if ( sectionName == null )
{
throw new ManifestException( "Sections must have a name" );
}
Attributes attributes = getOrCreateAttributes( sectionName );
for ( String s : section.attributes.keySet() )
{
Attribute attribute = section.getAttribute( s );
attributes.putValue( attribute.getName(), attribute.getValue() );
}
} | java | {
"resource": ""
} |
q167472 | Manifest.write | validation | public void write( PrintWriter writer )
throws IOException
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
super.write( byteArrayOutputStream );
for ( byte b : byteArrayOutputStream.toByteArray() )
{
writer.write( (char) b );
}
} | java | {
"resource": ""
} |
q167473 | Manifest.getWarnings | validation | Enumeration<String> getWarnings()
{
Vector<String> warnings = new Vector<String>();
Enumeration<String> warnEnum = mainSection.getWarnings();
while ( warnEnum.hasMoreElements() )
{
warnings.addElement( warnEnum.nextElement() );
}
return warnings.elements();
} | java | {
"resource": ""
} |
q167474 | Manifest.getSection | validation | public ExistingSection getSection( String name )
{
Attributes attributes = getAttributes( name );
if ( attributes != null )
{
return new ExistingSection( attributes, name );
}
return null;
} | java | {
"resource": ""
} |
q167475 | DirectoryArchiver.copyFile | validation | protected void copyFile( final ArchiveEntry entry, final String vPath )
throws ArchiverException, IOException
{
// don't add "" to the archive
if ( vPath.length() <= 0 )
{
return;
}
final PlexusIoResource in = entry.getResource();
final File outFile = new File( vPath );
final long inLastModified = in.getLastModified();
final long outLastModified = outFile.lastModified();
if ( ResourceUtils.isUptodate( inLastModified, outLastModified ) )
{
return;
}
if ( !in.isDirectory() )
{
if ( !outFile.getParentFile().exists() )
{
// create the parent directory...
if ( !outFile.getParentFile().mkdirs() )
{
// Failure, unable to create specified directory for some unknown reason.
throw new ArchiverException( "Unable to create directory or parent directory of " + outFile );
}
}
ResourceUtils.copyFile( entry.getInputStream(), outFile );
if ( !isIgnorePermissions() )
{
ArchiveEntryUtils.chmod( outFile, entry.getMode(), getLogger(), isUseJvmChmod() );
}
}
else
{ // file is a directory
if ( outFile.exists() )
{
if ( !outFile.isDirectory() )
{
// should we just delete the file and replace it with a directory?
// throw an exception, let the user delete the file manually.
throw new ArchiverException( "Expected directory and found file at copy destination of "
+ in.getName() + " to " + outFile );
}
}
else if ( !outFile.mkdirs() )
{
// Failure, unable to create specified directory for some unknown reason.
throw new ArchiverException( "Unable to create directory or parent directory of " + outFile );
}
}
outFile.setLastModified( inLastModified == PlexusIoResource.UNKNOWN_MODIFICATION_DATE ? System.currentTimeMillis()
: inLastModified );
} | java | {
"resource": ""
} |
q167476 | JarArchiver.addConfiguredManifest | validation | public void addConfiguredManifest( Manifest newManifest )
throws ManifestException
{
if ( configuredManifest == null )
{
configuredManifest = newManifest;
}
else
{
JdkManifestFactory.merge( configuredManifest, newManifest, false );
}
savedConfiguredManifest = configuredManifest;
} | java | {
"resource": ""
} |
q167477 | JarArchiver.zipFile | validation | protected void zipFile( InputStream is, ZipArchiveOutputStream zOut, String vPath, long lastModified, File fromArchive,
int mode, String symlinkDestination )
throws IOException, ArchiverException
{
if ( MANIFEST_NAME.equalsIgnoreCase( vPath ) )
{
if ( !doubleFilePass || skipWriting )
{
filesetManifest( fromArchive, is );
}
}
else if ( INDEX_NAME.equalsIgnoreCase( vPath ) && index )
{
getLogger().warn( "Warning: selected " + archiveType + " files include a META-INF/INDEX.LIST which will"
+ " be replaced by a newly generated one." );
}
else
{
if ( index && ( !vPath.contains( "/" ) ) )
{
rootEntries.addElement( vPath );
}
super.zipFile( is, zOut, vPath, lastModified, fromArchive, mode, symlinkDestination );
}
} | java | {
"resource": ""
} |
q167478 | JarArchiver.cleanUp | validation | protected void cleanUp()
throws IOException
{
super.cleanUp();
// we want to save this info if we are going to make another pass
if ( !doubleFilePass || !skipWriting )
{
manifest = null;
configuredManifest = savedConfiguredManifest;
filesetManifest = null;
originalManifest = null;
}
rootEntries.removeAllElements();
} | java | {
"resource": ""
} |
q167479 | JarArchiver.reset | validation | public void reset()
{
super.reset();
configuredManifest = null;
filesetManifestConfig = null;
mergeManifestsMain = false;
manifestFile = null;
index = false;
} | java | {
"resource": ""
} |
q167480 | JarArchiver.writeIndexLikeList | validation | protected final void writeIndexLikeList( List<String> dirs, List<String> files, PrintWriter writer )
{
// JarIndex is sorting the directories by ascending order.
// it has no value but cosmetic since it will be read into a
// hashtable by the classloader, but we'll do so anyway.
Collections.sort( dirs );
Collections.sort( files );
Iterator iter = dirs.iterator();
while ( iter.hasNext() )
{
String dir = (String) iter.next();
// try to be smart, not to be fooled by a weird directory name
dir = dir.replace( '\\', '/' );
if ( dir.startsWith( "./" ) )
{
dir = dir.substring( 2 );
}
while ( dir.startsWith( "/" ) )
{
dir = dir.substring( 1 );
}
int pos = dir.lastIndexOf( '/' );
if ( pos != -1 )
{
dir = dir.substring( 0, pos );
}
// name newline
writer.println( dir );
}
iter = files.iterator();
while ( iter.hasNext() )
{
writer.println( iter.next() );
}
} | java | {
"resource": ""
} |
q167481 | JarArchiver.grabFilesAndDirs | validation | protected static void grabFilesAndDirs( String file, List<String> dirs, List<String> files )
throws IOException
{
File zipFile = new File( file );
if ( !zipFile.exists() )
{
Logger logger = new ConsoleLogger( Logger.LEVEL_INFO, "console" );
logger.error( "JarArchive skipping non-existing file: " + zipFile.getAbsolutePath() );
}
else if ( zipFile.isDirectory() )
{
Logger logger = new ConsoleLogger( Logger.LEVEL_INFO, "console" );
logger.info( "JarArchiver skipping indexJar " + zipFile + " because it is not a jar" );
}
else
{
org.apache.commons.compress.archivers.zip.ZipFile zf = null;
try
{
zf = new org.apache.commons.compress.archivers.zip.ZipFile( file, "utf-8" );
Enumeration<ZipArchiveEntry> entries = zf.getEntries();
HashSet<String> dirSet = new HashSet<String>();
while ( entries.hasMoreElements() )
{
ZipArchiveEntry ze = entries.nextElement();
String name = ze.getName();
// avoid index for manifest-only jars.
if ( !name.equals( META_INF_NAME ) && !name.equals( META_INF_NAME + '/' ) && !name.equals(
INDEX_NAME ) && !name.equals( MANIFEST_NAME ) )
{
if ( ze.isDirectory() )
{
dirSet.add( name );
}
else if ( !name.contains( "/" ) )
{
files.add( name );
}
else
{
// a file, not in the root
// since the jar may be one without directory
// entries, add the parent dir of this file as
// well.
dirSet.add( name.substring( 0, name.lastIndexOf( "/" ) + 1 ) );
}
}
}
dirs.addAll( dirSet );
}
finally
{
if ( zf != null )
{
zf.close();
}
}
}
} | java | {
"resource": ""
} |
q167482 | TarUnArchiver.decompress | validation | private InputStream decompress( UntarCompressionMethod compression, final File file, final InputStream istream )
throws IOException, ArchiverException
{
if ( compression == UntarCompressionMethod.GZIP )
{
return new GZIPInputStream( istream );
}
else if ( compression == UntarCompressionMethod.BZIP2 )
{
return new BZip2CompressorInputStream( istream );
}
else if ( compression == UntarCompressionMethod.SNAPPY )
{
return new SnappyInputStream( istream );
}
return istream;
} | java | {
"resource": ""
} |
q167483 | GZipCompressor.compress | validation | public void compress()
throws ArchiverException
{
try
{
zOut = new GZIPOutputStream( Streams.bufferedOutputStream( new FileOutputStream( getDestFile() ) ));
compress( getSource(), zOut );
}
catch ( IOException ioe )
{
String msg = "Problem creating gzip " + ioe.getMessage();
throw new ArchiverException( msg, ioe );
}
} | java | {
"resource": ""
} |
q167484 | JdkManifestFactory.mergeAttributes | validation | public static void mergeAttributes( java.util.jar.Attributes target, java.util.jar.Attributes section )
{
for ( Object o : section.keySet() )
{
java.util.jar.Attributes.Name key = (Attributes.Name) o;
final Object value = section.get( o );
// the merge file always wins
target.put( key, value );
}
} | java | {
"resource": ""
} |
q167485 | EarArchiver.setAppxml | validation | public void setAppxml( File descr )
throws ArchiverException
{
deploymentDescriptor = descr;
if ( !deploymentDescriptor.exists() )
{
throw new ArchiverException( "Deployment descriptor: " + deploymentDescriptor + " does not exist." );
}
addFile( descr, "META-INF/application.xml" );
} | java | {
"resource": ""
} |
q167486 | EarArchiver.addArchive | validation | public void addArchive( File fileName )
throws ArchiverException
{
addDirectory( fileName.getParentFile(), "/", new String[]{fileName.getName()}, null );
} | java | {
"resource": ""
} |
q167487 | EarArchiver.addArchives | validation | public void addArchives( File directoryName, String[] includes, String[] excludes )
throws ArchiverException
{
addDirectory( directoryName, "/", includes, excludes );
} | java | {
"resource": ""
} |
q167488 | SnappyCompressor.compress | validation | public void compress()
throws ArchiverException
{
try
{
zOut = new SnappyOutputStream( bufferedOutputStream( fileOutputStream( getDestFile() ) ) );
compress( getSource(), zOut );
}
catch ( IOException ioe )
{
String msg = "Problem creating snappy " + ioe.getMessage();
throw new ArchiverException( msg, ioe );
}
} | java | {
"resource": ""
} |
q167489 | AbstractZipArchiver.addResources | validation | @SuppressWarnings({"JavaDoc"})
protected final void addResources( ResourceIterator resources, ZipArchiveOutputStream zOut )
throws IOException, ArchiverException
{
File base = null;
while ( resources.hasNext() )
{
ArchiveEntry entry = resources.next();
String name = entry.getName();
name = name.replace( File.separatorChar, '/' );
if ( "".equals( name ) )
{
continue;
}
if ( entry.getResource().isDirectory() && !name.endsWith( "/" ) )
{
name = name + "/";
}
addParentDirs( entry, base, name, zOut, "" );
if ( entry.getResource().isFile() )
{
zipFile( entry, zOut, name );
}
else
{
zipDir( entry.getResource(), zOut, name, entry.getMode() );
}
}
} | java | {
"resource": ""
} |
q167490 | AbstractZipArchiver.addParentDirs | validation | @SuppressWarnings({"JavaDoc"})
private void addParentDirs( ArchiveEntry archiveEntry, File baseDir, String entry, ZipArchiveOutputStream zOut,
String prefix )
throws IOException
{
if ( !doFilesonly && getIncludeEmptyDirs() )
{
Stack<String> directories = new Stack<String>();
// Don't include the last entry itself if it's
// a dir; it will be added on its own.
int slashPos = entry.length() - ( entry.endsWith( "/" ) ? 1 : 0 );
while ( ( slashPos = entry.lastIndexOf( '/', slashPos - 1 ) ) != -1 )
{
String dir = entry.substring( 0, slashPos + 1 );
if ( addedDirs.contains( prefix + dir ) )
{
break;
}
directories.push( dir );
}
while ( !directories.isEmpty() )
{
String dir = directories.pop();
File f;
if ( baseDir != null )
{
f = new File( baseDir, dir );
}
else
{
f = new File( dir );
}
// the
// At this point we could do something like read the atr
final PlexusIoResource res = new AnonymousResource( f);
zipDir( res, zOut, prefix + dir, archiveEntry.getDefaultDirMode() );
}
}
} | java | {
"resource": ""
} |
q167491 | AbstractZipArchiver.zipFile | validation | @SuppressWarnings({"JavaDoc"})
protected void zipFile( InputStream in, ZipArchiveOutputStream zOut, String vPath, long lastModified, File fromArchive,
int mode, String symlinkDestination )
throws IOException, ArchiverException
{
getLogger().debug( "adding entry " + vPath );
entries.put( vPath, vPath );
if ( !skipWriting )
{
ZipArchiveEntry ze = new ZipArchiveEntry( vPath );
setTime(ze, lastModified);
byte[] header = new byte[4];
int read = in.read(header);
boolean compressThis = doCompress;
if (!recompressAddedZips && isZipHeader(header)){
compressThis = false;
}
ze.setMethod( compressThis ? ZipArchiveEntry.DEFLATED : ZipArchiveEntry.STORED );
ze.setUnixMode( UnixStat.FILE_FLAG | mode );
/*
* ZipOutputStream.putNextEntry expects the ZipEntry to
* know its size and the CRC sum before you start writing
* the data when using STORED mode - unless it is seekable.
*
* This forces us to process the data twice.
*/
if (ze.isUnixSymlink()){
zOut.putArchiveEntry( ze );
ZipEncoding enc = ZipEncodingHelper.getZipEncoding( getEncoding() );
final byte[] bytes = enc.encode( symlinkDestination).array();
zOut.write( bytes, 0, bytes.length);
} else if (zOut.isSeekable() || compressThis) {
zOut.putArchiveEntry( ze );
if (read > 0) zOut.write(header, 0, read);
IOUtil.copy( in, zOut, 8 * 1024);
} else {
if (in.markSupported())
{
in.mark( Integer.MAX_VALUE );
readWithZipStats(in, header, read, ze, null);
in.reset();
zOut.putArchiveEntry( ze);
if (read > 0) zOut.write(header, 0, read);
IOUtil.copy(in, zOut, 8 * 1024);
}
else
{
// Store data into a byte[]
// todo: explain how on earth this code works with zip streams > 128KB ???
ByteArrayOutputStream bos = new ByteArrayOutputStream(128 * 1024);
readWithZipStats(in, header,read, ze, bos);
zOut.putArchiveEntry(ze);
if (read > 0) zOut.write(header, 0, read);
bos.writeTo( zOut);
}
}
zOut.closeArchiveEntry();
}
} | java | {
"resource": ""
} |
q167492 | AbstractZipArchiver.createEmptyZip | validation | @SuppressWarnings({"JavaDoc"})
protected boolean createEmptyZip( File zipFile )
throws ArchiverException
{
// In this case using java.util.zip will not work
// because it does not permit a zero-entry archive.
// Must create it manually.
getLogger().info( "Note: creating empty " + archiveType + " archive " + zipFile );
OutputStream os = null;
try
{
os = new FileOutputStream( zipFile );
// Cf. PKZIP specification.
byte[] empty = new byte[22];
empty[0] = 80; // P
empty[1] = 75; // K
empty[2] = 5;
empty[3] = 6;
// remainder zeros
os.write( empty );
}
catch ( IOException ioe )
{
throw new ArchiverException( "Could not create empty ZIP archive " + "(" + ioe.getMessage() + ")", ioe );
}
finally
{
IOUtil.close( os );
}
return true;
} | java | {
"resource": ""
} |
q167493 | AbstractZipArchiver.reset | validation | public void reset()
{
setDestFile( null );
// duplicate = "add";
archiveType = "zip";
doCompress = true;
doUpdate = false;
doFilesonly = false;
encoding = null;
} | java | {
"resource": ""
} |
q167494 | Compressor.compressFile | validation | private void compressFile( InputStream in, OutputStream zOut )
throws IOException
{
byte[] buffer = new byte[8 * 1024];
int count = 0;
do
{
zOut.write( buffer, 0, count );
count = in.read( buffer, 0, buffer.length );
}
while ( count != -1 );
} | java | {
"resource": ""
} |
q167495 | Compressor.compress | validation | protected void compress( PlexusIoResource resource, OutputStream zOut )
throws IOException
{
InputStream in = Streams.bufferedInputStream( resource.getContents() );
try
{
compressFile( in, zOut );
}
finally
{
IOUtil.close( in );
}
} | java | {
"resource": ""
} |
q167496 | Decoder.setMaxHeaderTableSize | validation | public void setMaxHeaderTableSize(int maxHeaderTableSize) {
maxDynamicTableSize = maxHeaderTableSize;
if (maxDynamicTableSize < encoderMaxDynamicTableSize) {
// decoder requires less space than encoder
// encoder MUST signal this change
maxDynamicTableSizeChangeRequired = true;
dynamicTable.setCapacity(maxDynamicTableSize);
}
} | java | {
"resource": ""
} |
q167497 | Decoder.decodeULE128 | validation | private static int decodeULE128(InputStream in) throws IOException {
in.mark(5);
int result = 0;
int shift = 0;
while (shift < 32) {
if (in.available() == 0) {
// Buffer does not contain entire integer,
// reset reader index and return -1.
in.reset();
return -1;
}
byte b = (byte) in.read();
if (shift == 28 && (b & 0xF8) != 0) {
break;
}
result |= (b & 0x7F) << shift;
if ((b & 0x80) == 0) {
return result;
}
shift += 7;
}
// Value exceeds Integer.MAX_VALUE
in.reset();
throw DECOMPRESSION_EXCEPTION;
} | java | {
"resource": ""
} |
q167498 | StaticTable.getIndex | validation | static int getIndex(byte[] name) {
String nameString = new String(name, 0, name.length, ISO_8859_1);
Integer index = STATIC_INDEX_BY_NAME.get(nameString);
if (index == null) {
return -1;
}
return index;
} | java | {
"resource": ""
} |
q167499 | StaticTable.getIndex | validation | static int getIndex(byte[] name, byte[] value) {
int index = getIndex(name);
if (index == -1) {
return -1;
}
// Note this assumes all entries for a given header field are sequential.
while (index <= length) {
HeaderField entry = getEntry(index);
if (!HpackUtil.equals(name, entry.name)) {
break;
}
if (HpackUtil.equals(value, entry.value)) {
return index;
}
index++;
}
return -1;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.