pax_global_header 0000666 0000000 0000000 00000000064 11556603426 0014522 g ustar 00root root 0000000 0000000 52 comment=6dce1664534cb1f44a75337cc37bea8e7e96a97b
felix-utils-1.1.0/ 0000775 0000000 0000000 00000000000 11556603426 0013766 5 ustar 00root root 0000000 0000000 felix-utils-1.1.0/DEPENDENCIES 0000664 0000000 0000000 00000001425 11556603426 0015541 0 ustar 00root root 0000000 0000000 Apache Felix Utils
Copyright 2010 The Apache Software Foundation
This software was developed at the Apache Software Foundation
(http://www.apache.org) and may have dependencies on other
Apache software licensed under Apache License 2.0.
I. Included Third-Party Software
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
Licensed under the Apache License 2.0.
II. Used Third-Party Software
This product uses software developed at
The Apache Software Foundation (http://www.apache.org/).
Licensed under the Apache License 2.0.
This product uses software developed at
The OSGi Alliance (http://www.osgi.org/).
Copyright (c) OSGi Alliance (2000, 2010).
Licensed under the Apache License 2.0.
III. License Summary
- Apache License 2.0
felix-utils-1.1.0/LICENSE 0000664 0000000 0000000 00000026136 11556603426 0015003 0 ustar 00root root 0000000 0000000
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
felix-utils-1.1.0/NOTICE 0000664 0000000 0000000 00000000316 11556603426 0014672 0 ustar 00root root 0000000 0000000 Apache Felix Utils
Copyright 2010 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
Licensed under the Apache License 2.0.
felix-utils-1.1.0/doc/ 0000775 0000000 0000000 00000000000 11556603426 0014533 5 ustar 00root root 0000000 0000000 felix-utils-1.1.0/doc/changelog.txt 0000664 0000000 0000000 00000000704 11556603426 0017224 0 ustar 00root root 0000000 0000000 Changes 1.0.0 to 1.1.0
----------------------
** New Feature
* New org.apache.felix.utils.collections.DictionaryAsMap class
to wrap a Dictionary as a Map
* New org.apache.felix.utils.properties.InterpolationHelper to
interpolate a Map of properties using ${xx} replacements
* New org.apache.felix.utils.properties.Properties class to
load/save properties and allow editing them without loosing
the user formatting
felix-utils-1.1.0/pom.xml 0000664 0000000 0000000 00000005336 11556603426 0015312 0 ustar 00root root 0000000 0000000
* If the filter cannot be parsed, an {@link org.osgi.framework.InvalidSyntaxException}
* will be thrown with a human readable message where the filter became
* unparsable.
*
* @param filterString the filter string.
* @exception InvalidSyntaxException If the filter parameter contains an
* invalid filter string that cannot be parsed.
*/
public static FilterImpl newInstance(String filterString)
throws InvalidSyntaxException {
return newInstance(filterString, false);
}
public static FilterImpl newInstance(String filterString, boolean ignoreCase)
throws InvalidSyntaxException {
return new Parser(filterString, ignoreCase).parse();
}
FilterImpl(int operation, String attr, Object value) {
this.op = operation;
this.attr = attr;
this.value = value;
Object conv = null;
try {
if (op == SUBSET || op == SUPERSET)
{
conv = getSet(value);
}
else if ("version".equalsIgnoreCase(attr))
{
if (value instanceof String) {
conv = VersionTable.getVersion((String) value);
} else if (value instanceof Version) {
conv = (Version) value;
}
}
} catch (Throwable t) {
// Ignore any conversion issue
}
converted = conv;
}
/**
* Filter using a service's properties.
*
* This
* The filter string is normalized by removing whitespace which does not
* affect the meaning of the filter.
*
* @return This
* The filter string is normalized by removing whitespace which does not
* affect the meaning of the filter.
*
* @return This
* This implementation returns the result of calling
*
* This implementation returns the result of calling
*
* Enhancement of the standard
* This method performs property variable substitution on the
* specified value. If the specified value contains the syntax
* ${<prop-name>}, where <prop-name>
* refers to either a configuration property or a system property,
* then the corresponding property value is substituted for the variable
* placeholder. Multiple variable placeholders may exist in the
* specified value as well as nested variable placeholders, which
* are substituted from inner most to outer most. Configuration
* properties override system properties.
*
* Enhancement of the standard Unescapes any Java literals found in the Escapes the characters in a Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) So a tab becomes the characters The only difference between Java strings and JavaScript strings
* is that in JavaScript, a single quote must be escaped. Example:
* Filter
is executed using the keys and values of the
* referenced service's properties. The keys are case insensitively
* matched with this Filter
.
*
* @param reference The reference to the service whose properties are
* used in the match.
* @return true
if the service's properties match this
* Filter
; false
otherwise.
*/
public boolean match(ServiceReference reference) {
return match0(new ServiceReferenceDictionary(reference));
}
/**
* Filter using a Dictionary
. This Filter
is
* executed using the specified Dictionary
's keys and
* values. The keys are case insensitively matched with this
* Filter
.
*
* @param dictionary The Dictionary
whose keys are used in
* the match.
* @return true
if the Dictionary
's keys and
* values match this filter; false
otherwise.
* @throws IllegalArgumentException If dictionary
contains
* case variants of the same key name.
*/
public boolean match(Dictionary dictionary) {
return match0(new CaseInsensitiveDictionary(dictionary));
}
/**
* Filter with case sensitivity using a Dictionary
. This
* Filter
is executed using the specified
* Dictionary
's keys and values. The keys are case
* sensitively matched with this Filter
.
*
* @param dictionary The Dictionary
whose keys are used in
* the match.
* @return true
if the Dictionary
's keys and
* values match this filter; false
otherwise.
* @since 1.3
*/
public boolean matchCase(Dictionary dictionary) {
return match0(dictionary);
}
/**
* Filter using a Map
. This Filter
is
* executed using the specified Map
's keys and
* values. The keys are case insensitively matched with this
* Filter
.
*
* @param map The Map
whose keys are used in
* the match.
* @return true
if the Map
's keys and
* values match this filter; false
otherwise.
* @throws IllegalArgumentException If map
contains
* case variants of the same key name.
*/
public boolean matchCase(Map map) {
return match0(map);
}
/**
* Returns this Filter
's filter string.
* Filter
's filter string.
*/
public String toString() {
String result = filterString;
if (result == null) {
filterString = result = normalize();
}
return result;
}
/**
* Returns this Filter
's normalized filter string.
* Filter
's filter string.
*/
private String normalize() {
StringBuffer sb = new StringBuffer();
sb.append('(');
switch (op) {
case AND : {
sb.append('&');
FilterImpl[] filters = (FilterImpl[]) value;
for (int i = 0, size = filters.length; i < size; i++) {
sb.append(filters[i].normalize());
}
break;
}
case OR : {
sb.append('|');
FilterImpl[] filters = (FilterImpl[]) value;
for (int i = 0, size = filters.length; i < size; i++) {
sb.append(filters[i].normalize());
}
break;
}
case NOT : {
sb.append('!');
FilterImpl filter = (FilterImpl) value;
sb.append(filter.normalize());
break;
}
case SUBSTRING : {
sb.append(attr);
sb.append('=');
String[] substrings = (String[]) value;
for (int i = 0, size = substrings.length; i < size; i++) {
String substr = substrings[i];
if (substr == null) /* * */{
sb.append('*');
}
else /* xxx */{
sb.append(encodeValue(substr));
}
}
break;
}
case EQUAL : {
sb.append(attr);
sb.append('=');
sb.append(encodeValue((String) value));
break;
}
case GREATER: {
sb.append(attr);
sb.append(">=");
sb.append(encodeValue((String) value));
break;
}
case LESS: {
sb.append(attr);
sb.append("<=");
sb.append(encodeValue((String) value));
break;
}
case APPROX : {
sb.append(attr);
sb.append("~=");
sb.append(encodeValue(approxString((String) value)));
break;
}
case PRESENT : {
sb.append(attr);
sb.append("=*");
break;
}
case SUBSET : {
sb.append(attr);
sb.append("<*");
sb.append(encodeValue(approxString((String) value)));
break;
}
case SUPERSET : {
sb.append(attr);
sb.append("*>");
sb.append(encodeValue(approxString((String) value)));
break;
}
}
sb.append(')');
return sb.toString();
}
/**
* Compares this Filter
to another Filter
.
*
* this.toString().equals(obj.toString()
.
*
* @param obj The object to compare against this Filter
.
* @return If the other object is a Filter
object, then
* returns the result of calling
* this.toString().equals(obj.toString()
;
* false
otherwise.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof FilterImpl)) {
return false;
}
return this.toString().equals(obj.toString());
}
/**
* Returns the hashCode for this Filter
.
*
* this.toString().hashCode()
.
*
* @return The hashCode of this Filter
.
*/
public int hashCode() {
return this.toString().hashCode();
}
/**
* Internal match routine. Dictionary parameter must support
* case-insensitive get.
*
* @param properties A dictionary whose keys are used in the match.
* @return If the Dictionary's keys match the filter, return
* true
. Otherwise, return false
.
*/
private boolean match0(Dictionary properties) {
switch (op) {
case AND : {
FilterImpl[] filters = (FilterImpl[]) value;
for (int i = 0, size = filters.length; i < size; i++) {
if (!filters[i].match0(properties)) {
return false;
}
}
return true;
}
case OR : {
FilterImpl[] filters = (FilterImpl[]) value;
for (int i = 0, size = filters.length; i < size; i++) {
if (filters[i].match0(properties)) {
return true;
}
}
return false;
}
case NOT : {
FilterImpl filter = (FilterImpl) value;
return !filter.match0(properties);
}
case SUBSTRING :
case EQUAL :
case GREATER:
case LESS:
case APPROX :
case SUBSET :
case SUPERSET : {
Object prop = (properties == null) ? null : properties
.get(attr);
return compare(op, prop, value);
}
case PRESENT : {
Object prop = (properties == null) ? null : properties
.get(attr);
return prop != null;
}
}
return false;
}
private boolean match0(Map properties) {
switch (op) {
case AND : {
FilterImpl[] filters = (FilterImpl[]) value;
for (int i = 0, size = filters.length; i < size; i++) {
if (!filters[i].match0(properties)) {
return false;
}
}
return true;
}
case OR : {
FilterImpl[] filters = (FilterImpl[]) value;
for (int i = 0, size = filters.length; i < size; i++) {
if (filters[i].match0(properties)) {
return true;
}
}
return false;
}
case NOT : {
FilterImpl filter = (FilterImpl) value;
return !filter.match0(properties);
}
case SUBSTRING :
case EQUAL :
case GREATER:
case LESS:
case APPROX :
case SUBSET :
case SUPERSET : {
Object prop = (properties == null) ? null : properties
.get(attr);
return compare(op, prop, value);
}
case PRESENT : {
Object prop = (properties == null) ? null : properties
.get(attr);
return prop != null;
}
}
return false;
}
/**
* Encode the value string such that '(', '*', ')' and '\' are escaped.
*
* @param value unencoded value string.
* @return encoded value string.
*/
private static String encodeValue(String value) {
boolean encoded = false;
int inlen = value.length();
int outlen = inlen << 1; /* inlen 2 */
char[] output = new char[outlen];
value.getChars(0, inlen, output, inlen);
int cursor = 0;
for (int i = inlen; i < outlen; i++) {
char c = output[i];
switch (c) {
case '(' :
case '*' :
case ')' :
case '\\' : {
output[cursor] = '\\';
cursor++;
encoded = true;
break;
}
}
output[cursor] = c;
cursor++;
}
return encoded ? new String(output, 0, cursor) : value;
}
private Collection getSet(Object value)
{
Collection s;
if (value instanceof Set)
{
s = (Set) value;
}
else if (value instanceof Collection)
{
s = (Collection) value;
if (s.size() > 1) {
s = new HashSet(s);
}
}
else if (value != null)
{
String v = value.toString();
if (v.indexOf(',') < 0)
{
s = Collections.singleton(v);
}
else {
StringTokenizer st = new StringTokenizer(value.toString(), ",");
s = new HashSet();
while (st.hasMoreTokens())
{
s.add(st.nextToken().trim());
}
}
}
else
{
s = Collections.emptySet();
}
return s;
}
private boolean compare(int operation, Object value1, Object value2) {
if (op == SUPERSET || op == SUBSET)
{
Collection s1 = getSet(value1);
Collection s2 = converted instanceof Collection ? (Collection) converted : getSet(value2);
if (op == SUPERSET)
{
return s1.containsAll(s2);
}
else
{
return s2.containsAll(s1);
}
}
if (value1 == null) {
return false;
}
if (value1 instanceof String) {
return compare_String(operation, (String) value1, value2);
}
Class clazz = value1.getClass();
if (clazz.isArray()) {
Class type = clazz.getComponentType();
if (type.isPrimitive()) {
return compare_PrimitiveArray(operation, type, value1,
value2);
}
return compare_ObjectArray(operation, (Object[]) value1, value2);
}
if (value1 instanceof Version) {
if (converted != null) {
switch (operation) {
case APPROX :
case EQUAL : {
return ((Version) value1).compareTo(converted) == 0;
}
case GREATER: {
return ((Version) value1).compareTo(converted) >= 0;
}
case LESS: {
return ((Version) value1).compareTo(converted) <= 0;
}
}
} else {
return compare_Comparable(operation, (Version) value1, value2);
}
}
if (value1 instanceof Collection) {
return compare_Collection(operation, (Collection) value1,
value2);
}
if (value1 instanceof Integer) {
return compare_Integer(operation,
((Integer) value1).intValue(), value2);
}
if (value1 instanceof Long) {
return compare_Long(operation, ((Long) value1).longValue(),
value2);
}
if (value1 instanceof Byte) {
return compare_Byte(operation, ((Byte) value1).byteValue(),
value2);
}
if (value1 instanceof Short) {
return compare_Short(operation, ((Short) value1).shortValue(),
value2);
}
if (value1 instanceof Character) {
return compare_Character(operation, ((Character) value1)
.charValue(), value2);
}
if (value1 instanceof Float) {
return compare_Float(operation, ((Float) value1).floatValue(),
value2);
}
if (value1 instanceof Double) {
return compare_Double(operation, ((Double) value1)
.doubleValue(), value2);
}
if (value1 instanceof Boolean) {
return compare_Boolean(operation, ((Boolean) value1)
.booleanValue(), value2);
}
if (value1 instanceof Comparable) {
return compare_Comparable(operation, (Comparable) value1,
value2);
}
return compare_Unknown(operation, value1, value2); // RFC 59
}
private boolean compare_Collection(int operation,
Collection collection, Object value2) {
if (op == SUBSET || op == SUPERSET)
{
Set set = new HashSet();
if (value2 != null)
{
StringTokenizer st = new StringTokenizer(value2.toString(), ",");
while (st.hasMoreTokens())
{
set.add(st.nextToken().trim());
}
}
if (op == SUBSET)
{
return set.containsAll(collection);
}
else
{
return collection.containsAll(set);
}
}
for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
if (compare(operation, iterator.next(), value2)) {
return true;
}
}
return false;
}
private boolean compare_ObjectArray(int operation, Object[] array,
Object value2) {
for (int i = 0, size = array.length; i < size; i++) {
if (compare(operation, array[i], value2)) {
return true;
}
}
return false;
}
private boolean compare_PrimitiveArray(int operation, Class type,
Object primarray, Object value2) {
if (Integer.TYPE.isAssignableFrom(type)) {
int[] array = (int[]) primarray;
for (int i = 0, size = array.length; i < size; i++) {
if (compare_Integer(operation, array[i], value2)) {
return true;
}
}
return false;
}
if (Long.TYPE.isAssignableFrom(type)) {
long[] array = (long[]) primarray;
for (int i = 0, size = array.length; i < size; i++) {
if (compare_Long(operation, array[i], value2)) {
return true;
}
}
return false;
}
if (Byte.TYPE.isAssignableFrom(type)) {
byte[] array = (byte[]) primarray;
for (int i = 0, size = array.length; i < size; i++) {
if (compare_Byte(operation, array[i], value2)) {
return true;
}
}
return false;
}
if (Short.TYPE.isAssignableFrom(type)) {
short[] array = (short[]) primarray;
for (int i = 0, size = array.length; i < size; i++) {
if (compare_Short(operation, array[i], value2)) {
return true;
}
}
return false;
}
if (Character.TYPE.isAssignableFrom(type)) {
char[] array = (char[]) primarray;
for (int i = 0, size = array.length; i < size; i++) {
if (compare_Character(operation, array[i], value2)) {
return true;
}
}
return false;
}
if (Float.TYPE.isAssignableFrom(type)) {
float[] array = (float[]) primarray;
for (int i = 0, size = array.length; i < size; i++) {
if (compare_Float(operation, array[i], value2)) {
return true;
}
}
return false;
}
if (Double.TYPE.isAssignableFrom(type)) {
double[] array = (double[]) primarray;
for (int i = 0, size = array.length; i < size; i++) {
if (compare_Double(operation, array[i], value2)) {
return true;
}
}
return false;
}
if (Boolean.TYPE.isAssignableFrom(type)) {
boolean[] array = (boolean[]) primarray;
for (int i = 0, size = array.length; i < size; i++) {
if (compare_Boolean(operation, array[i], value2)) {
return true;
}
}
return false;
}
return false;
}
private boolean compare_String(int operation, String string,
Object value2) {
switch (operation) {
case SUBSTRING : {
String[] substrings = (String[]) value2;
int pos = 0;
for (int i = 0, size = substrings.length; i < size; i++) {
String substr = substrings[i];
if (i + 1 < size) /* if this is not that last substr */{
if (substr == null) /* * */{
String substr2 = substrings[i + 1];
if (substr2 == null) /* ** */
continue; /* ignore first star */
/* xxx */
int index = string.indexOf(substr2, pos);
if (index == -1) {
return false;
}
pos = index + substr2.length();
if (i + 2 < size) // if there are more
// substrings, increment
// over the string we just
// matched; otherwise need
// to do the last substr
// check
i++;
}
else /* xxx */{
int len = substr.length();
if (string.regionMatches(pos, substr, 0, len)) {
pos += len;
}
else {
return false;
}
}
}
else /* last substr */{
if (substr == null) /* * */{
return true;
}
/* xxx */
return string.endsWith(substr);
}
}
return true;
}
case EQUAL : {
return string.equals(value2);
}
case APPROX : {
string = approxString(string);
String string2 = approxString((String) value2);
return string.equalsIgnoreCase(string2);
}
case GREATER: {
return string.compareTo((String) value2) >= 0;
}
case LESS: {
return string.compareTo((String) value2) <= 0;
}
}
return false;
}
private boolean compare_Integer(int operation, int intval, Object value2) {
if (operation == SUBSTRING) {
return false;
}
int intval2;
try {
intval2 = Integer.parseInt(((String) value2).trim());
}
catch (IllegalArgumentException e) {
return false;
}
switch (operation) {
case APPROX :
case EQUAL : {
return intval == intval2;
}
case GREATER: {
return intval >= intval2;
}
case LESS: {
return intval <= intval2;
}
}
return false;
}
private boolean compare_Long(int operation, long longval, Object value2) {
if (operation == SUBSTRING) {
return false;
}
long longval2;
try {
longval2 = Long.parseLong(((String) value2).trim());
}
catch (IllegalArgumentException e) {
return false;
}
switch (operation) {
case APPROX :
case EQUAL : {
return longval == longval2;
}
case GREATER: {
return longval >= longval2;
}
case LESS: {
return longval <= longval2;
}
}
return false;
}
private boolean compare_Byte(int operation, byte byteval, Object value2) {
if (operation == SUBSTRING) {
return false;
}
byte byteval2;
try {
byteval2 = Byte.parseByte(((String) value2).trim());
}
catch (IllegalArgumentException e) {
return false;
}
switch (operation) {
case APPROX :
case EQUAL : {
return byteval == byteval2;
}
case GREATER: {
return byteval >= byteval2;
}
case LESS: {
return byteval <= byteval2;
}
}
return false;
}
private boolean compare_Short(int operation, short shortval,
Object value2) {
if (operation == SUBSTRING) {
return false;
}
short shortval2;
try {
shortval2 = Short.parseShort(((String) value2).trim());
}
catch (IllegalArgumentException e) {
return false;
}
switch (operation) {
case APPROX :
case EQUAL : {
return shortval == shortval2;
}
case GREATER: {
return shortval >= shortval2;
}
case LESS: {
return shortval <= shortval2;
}
}
return false;
}
private boolean compare_Character(int operation, char charval,
Object value2) {
if (operation == SUBSTRING) {
return false;
}
char charval2;
try {
charval2 = ((String) value2).charAt(0);
}
catch (IndexOutOfBoundsException e) {
return false;
}
switch (operation) {
case EQUAL : {
return charval == charval2;
}
case APPROX : {
return (charval == charval2)
|| (Character.toUpperCase(charval) == Character
.toUpperCase(charval2))
|| (Character.toLowerCase(charval) == Character
.toLowerCase(charval2));
}
case GREATER: {
return charval >= charval2;
}
case LESS: {
return charval <= charval2;
}
}
return false;
}
private boolean compare_Boolean(int operation, boolean boolval,
Object value2) {
if (operation == SUBSTRING) {
return false;
}
boolean boolval2 = Boolean.valueOf(((String) value2).trim())
.booleanValue();
switch (operation) {
case APPROX :
case EQUAL :
case GREATER:
case LESS: {
return boolval == boolval2;
}
}
return false;
}
private boolean compare_Float(int operation, float floatval,
Object value2) {
if (operation == SUBSTRING) {
return false;
}
float floatval2;
try {
floatval2 = Float.parseFloat(((String) value2).trim());
}
catch (IllegalArgumentException e) {
return false;
}
switch (operation) {
case APPROX :
case EQUAL : {
return Float.compare(floatval, floatval2) == 0;
}
case GREATER: {
return Float.compare(floatval, floatval2) >= 0;
}
case LESS: {
return Float.compare(floatval, floatval2) <= 0;
}
}
return false;
}
private boolean compare_Double(int operation, double doubleval,
Object value2) {
if (operation == SUBSTRING) {
return false;
}
double doubleval2;
try {
doubleval2 = Double.parseDouble(((String) value2).trim());
}
catch (IllegalArgumentException e) {
return false;
}
switch (operation) {
case APPROX :
case EQUAL : {
return Double.compare(doubleval, doubleval2) == 0;
}
case GREATER: {
return Double.compare(doubleval, doubleval2) >= 0;
}
case LESS: {
return Double.compare(doubleval, doubleval2) <= 0;
}
}
return false;
}
private static final Class[] constructorType = new Class[] {String.class};
private boolean compare_Comparable(int operation, Comparable value1,
Object value2) {
if (operation == SUBSTRING) {
return false;
}
Constructor constructor;
try {
constructor = value1.getClass().getConstructor(constructorType);
}
catch (NoSuchMethodException e) {
return false;
}
try {
if (!constructor.isAccessible())
AccessController.doPrivileged(new SetAccessibleAction(
constructor));
value2 = constructor
.newInstance(new Object[] {((String) value2).trim()});
}
catch (IllegalAccessException e) {
return false;
}
catch (InvocationTargetException e) {
return false;
}
catch (InstantiationException e) {
return false;
}
switch (operation) {
case APPROX :
case EQUAL : {
return value1.compareTo(value2) == 0;
}
case GREATER: {
return value1.compareTo(value2) >= 0;
}
case LESS: {
return value1.compareTo(value2) <= 0;
}
}
return false;
}
private boolean compare_Unknown(int operation, Object value1,
Object value2) {
if (operation == SUBSTRING) {
return false;
}
Constructor constructor;
try {
constructor = value1.getClass().getConstructor(constructorType);
}
catch (NoSuchMethodException e) {
return false;
}
try {
if (!constructor.isAccessible())
AccessController.doPrivileged(new SetAccessibleAction(
constructor));
value2 = constructor
.newInstance(new Object[] {((String) value2).trim()});
}
catch (IllegalAccessException e) {
return false;
}
catch (InvocationTargetException e) {
return false;
}
catch (InstantiationException e) {
return false;
}
switch (operation) {
case APPROX :
case EQUAL :
case GREATER:
case LESS: {
return value1.equals(value2);
}
}
return false;
}
/**
* Map a string for an APPROX (~=) comparison.
*
* This implementation removes white spaces. This is the minimum
* implementation allowed by the OSGi spec.
*
* @param input Input string.
* @return String ready for APPROX comparison.
*/
private static String approxString(String input) {
boolean changed = false;
char[] output = input.toCharArray();
int cursor = 0;
for (int i = 0, length = output.length; i < length; i++) {
char c = output[i];
if (Character.isWhitespace(c)) {
changed = true;
continue;
}
output[cursor] = c;
cursor++;
}
return changed ? new String(output, 0, cursor) : input;
}
/**
* Parser class for OSGi filter strings. This class parses the complete
* filter string and builds a tree of Filter objects rooted at the
* parent.
*/
private static class Parser {
private final String filterstring;
private final boolean ignoreCase;
private final char[] filterChars;
private int pos;
Parser(String filterstring, boolean ignoreCase) {
this.filterstring = filterstring;
this.ignoreCase = ignoreCase;
filterChars = filterstring.toCharArray();
pos = 0;
}
FilterImpl parse() throws InvalidSyntaxException {
FilterImpl filter;
try {
filter = parse_filter();
}
catch (ArrayIndexOutOfBoundsException e) {
throw new InvalidSyntaxException("Filter ended abruptly",
filterstring);
}
if (pos != filterChars.length) {
throw new InvalidSyntaxException(
"Extraneous trailing characters: "
+ filterstring.substring(pos), filterstring);
}
return filter;
}
private FilterImpl parse_filter() throws InvalidSyntaxException {
FilterImpl filter;
skipWhiteSpace();
if (filterChars[pos] != '(') {
throw new InvalidSyntaxException("Missing '(': "
+ filterstring.substring(pos), filterstring);
}
pos++;
filter = parse_filtercomp();
skipWhiteSpace();
if (filterChars[pos] != ')') {
throw new InvalidSyntaxException("Missing ')': "
+ filterstring.substring(pos), filterstring);
}
pos++;
skipWhiteSpace();
return filter;
}
private FilterImpl parse_filtercomp() throws InvalidSyntaxException {
skipWhiteSpace();
char c = filterChars[pos];
switch (c) {
case '&' : {
pos++;
return parse_and();
}
case '|' : {
pos++;
return parse_or();
}
case '!' : {
pos++;
return parse_not();
}
}
return parse_item();
}
private FilterImpl parse_and() throws InvalidSyntaxException {
int lookahead = pos;
skipWhiteSpace();
if (filterChars[pos] != '(') {
pos = lookahead - 1;
return parse_item();
}
List operands = new ArrayList(10);
while (filterChars[pos] == '(') {
FilterImpl child = parse_filter();
operands.add(child);
}
return new FilterImpl(FilterImpl.AND, null, operands
.toArray(new FilterImpl[operands.size()]));
}
private FilterImpl parse_or() throws InvalidSyntaxException {
int lookahead = pos;
skipWhiteSpace();
if (filterChars[pos] != '(') {
pos = lookahead - 1;
return parse_item();
}
List operands = new ArrayList(10);
while (filterChars[pos] == '(') {
FilterImpl child = parse_filter();
operands.add(child);
}
return new FilterImpl(FilterImpl.OR, null, operands
.toArray(new FilterImpl[operands.size()]));
}
private FilterImpl parse_not() throws InvalidSyntaxException {
int lookahead = pos;
skipWhiteSpace();
if (filterChars[pos] != '(') {
pos = lookahead - 1;
return parse_item();
}
FilterImpl child = parse_filter();
return new FilterImpl(FilterImpl.NOT, null, child);
}
private FilterImpl parse_item() throws InvalidSyntaxException {
String attr = parse_attr();
skipWhiteSpace();
switch (filterChars[pos]) {
case '*': {
if (filterChars[pos + 1] == '>') {
pos += 2;
return new FilterImpl(FilterImpl.SUPERSET, attr,
parse_value());
}
break;
}
case '~' : {
if (filterChars[pos + 1] == '=') {
pos += 2;
return new FilterImpl(FilterImpl.APPROX, attr,
parse_value());
}
break;
}
case '>' : {
if (filterChars[pos + 1] == '=') {
pos += 2;
return new FilterImpl(FilterImpl.GREATER, attr,
parse_value());
}
break;
}
case '<' : {
if (filterChars[pos + 1] == '=') {
pos += 2;
return new FilterImpl(FilterImpl.LESS, attr,
parse_value());
}
if (filterChars[pos + 1] == '*') {
pos += 2;
return new FilterImpl(FilterImpl.SUBSET, attr,
parse_value());
}
break;
}
case '=' : {
if (filterChars[pos + 1] == '*') {
int oldpos = pos;
pos += 2;
skipWhiteSpace();
if (filterChars[pos] == ')') {
return new FilterImpl(FilterImpl.PRESENT, attr,
null);
}
pos = oldpos;
}
pos++;
Object string = parse_substring();
if (string instanceof String) {
return new FilterImpl(FilterImpl.EQUAL, attr,
string);
}
return new FilterImpl(FilterImpl.SUBSTRING, attr,
string);
}
}
throw new InvalidSyntaxException("Invalid operator: "
+ filterstring.substring(pos), filterstring);
}
private String parse_attr() throws InvalidSyntaxException {
skipWhiteSpace();
int begin = pos;
int end = pos;
char c = filterChars[pos];
while (c != '~' && c != '<' && c != '>' && c != '=' && c != '('
&& c != ')') {
if (c == '<' && filterChars[pos+1] == '*') {
break;
}
if (c == '*' && filterChars[pos+1] == '>') {
break;
}
pos++;
if (!Character.isWhitespace(c)) {
end = pos;
}
c = filterChars[pos];
}
int length = end - begin;
if (length == 0) {
throw new InvalidSyntaxException("Missing attr: "
+ filterstring.substring(pos), filterstring);
}
String str = new String(filterChars, begin, length);
if (ignoreCase)
{
str = str.toLowerCase();
}
return str;
}
private String parse_value() throws InvalidSyntaxException {
StringBuffer sb = new StringBuffer(filterChars.length - pos);
parseloop: while (true) {
char c = filterChars[pos];
switch (c) {
case ')' : {
break parseloop;
}
case '(' : {
throw new InvalidSyntaxException("Invalid value: "
+ filterstring.substring(pos), filterstring);
}
case '\\' : {
pos++;
c = filterChars[pos];
/* fall through into default */
}
default : {
sb.append(c);
pos++;
break;
}
}
}
if (sb.length() == 0) {
throw new InvalidSyntaxException("Missing value: "
+ filterstring.substring(pos), filterstring);
}
return sb.toString();
}
private Object parse_substring() throws InvalidSyntaxException {
StringBuffer sb = new StringBuffer(filterChars.length - pos);
List operands = new ArrayList(10);
parseloop: while (true) {
char c = filterChars[pos];
switch (c) {
case ')' : {
if (sb.length() > 0) {
operands.add(sb.toString());
}
break parseloop;
}
case '(' : {
throw new InvalidSyntaxException("Invalid value: "
+ filterstring.substring(pos), filterstring);
}
case '*' : {
if (sb.length() > 0) {
operands.add(sb.toString());
}
sb.setLength(0);
operands.add(null);
pos++;
break;
}
case '\\' : {
pos++;
c = filterChars[pos];
/* fall through into default */
}
default : {
sb.append(c);
pos++;
break;
}
}
}
int size = operands.size();
if (size == 0) {
return "";
}
if (size == 1) {
Object single = operands.get(0);
if (single != null) {
return single;
}
}
return operands.toArray(new String[size]);
}
private void skipWhiteSpace() {
for (int length = filterChars.length; (pos < length)
&& Character.isWhitespace(filterChars[pos]);) {
pos++;
}
}
}
/**
* This Dictionary is used for case-insensitive key lookup during filter
* evaluation. This Dictionary implementation only supports the get
* operation using a String key as no other operations are used by the
* Filter implementation.
*/
private static class CaseInsensitiveDictionary extends Dictionary {
private final Dictionary dictionary;
private final String[] keys;
/**
* Create a case insensitive dictionary from the specified dictionary.
*
* @param dictionary
* @throws IllegalArgumentException If dictionary
contains
* case variants of the same key name.
*/
CaseInsensitiveDictionary(Dictionary dictionary) {
if (dictionary == null) {
this.dictionary = null;
this.keys = new String[0];
return;
}
this.dictionary = dictionary;
List keyList = new ArrayList(dictionary.size());
for (Enumeration e = dictionary.keys(); e.hasMoreElements();) {
Object k = e.nextElement();
if (k instanceof String) {
String key = (String) k;
for (Iterator i = keyList.iterator(); i.hasNext();) {
if (key.equalsIgnoreCase((String) i.next())) {
throw new IllegalArgumentException();
}
}
keyList.add(key);
}
}
this.keys = (String[]) keyList.toArray(new String[keyList.size()]);
}
public Object get(Object o) {
String k = (String) o;
for (int i = 0, length = keys.length; i < length; i++) {
String key = keys[i];
if (key.equalsIgnoreCase(k)) {
return dictionary.get(key);
}
}
return null;
}
public boolean isEmpty() {
throw new UnsupportedOperationException();
}
public Enumeration keys() {
throw new UnsupportedOperationException();
}
public Enumeration elements() {
throw new UnsupportedOperationException();
}
public Object put(Object key, Object value) {
throw new UnsupportedOperationException();
}
public Object remove(Object key) {
throw new UnsupportedOperationException();
}
public int size() {
throw new UnsupportedOperationException();
}
}
private static class SetAccessibleAction implements PrivilegedAction {
private final AccessibleObject accessible;
SetAccessibleAction(AccessibleObject accessible) {
this.accessible = accessible;
}
public Object run() {
accessible.setAccessible(true);
return null;
}
}
/**
* This Dictionary is used for key lookup from a ServiceReference during
* filter evaluation. This Dictionary implementation only supports the get
* operation using a String key as no other operations are used by the
* Filter implementation.
*/
private static class ServiceReferenceDictionary extends Dictionary {
private final ServiceReference reference;
ServiceReferenceDictionary(ServiceReference reference) {
this.reference = reference;
}
public Object get(Object key) {
if (reference == null) {
return null;
}
return reference.getProperty((String) key);
}
public boolean isEmpty() {
throw new UnsupportedOperationException();
}
public Enumeration keys() {
throw new UnsupportedOperationException();
}
public Enumeration elements() {
throw new UnsupportedOperationException();
}
public Object put(Object key, Object value) {
throw new UnsupportedOperationException();
}
public Object remove(Object key) {
throw new UnsupportedOperationException();
}
public int size() {
throw new UnsupportedOperationException();
}
}
}
felix-utils-1.1.0/src/main/java/org/apache/felix/utils/log/ 0000775 0000000 0000000 00000000000 11556603426 0023462 5 ustar 00root root 0000000 0000000 felix-utils-1.1.0/src/main/java/org/apache/felix/utils/log/Logger.java 0000664 0000000 0000000 00000010154 11556603426 0025545 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.utils.log;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogService;
import java.io.PrintStream;
/**
* Internal logger to be used in order to avoid a mandatory dependency on OSGi LogService.
* It first tries to log to a log service implementation if there is one available and then fallback to System out/err
* in case there is no log service available.
*/
public class Logger
{
public static final int LOG_ERROR = 1;
public static final int LOG_WARNING = 2;
public static final int LOG_INFO = 3;
public static final int LOG_DEBUG = 4;
/**
* Bundle context.
*/
private final BundleContext m_context;
private boolean m_isLogClassPresent;
/**
* Constructor.
*
* @param context bundle context
*/
public Logger(BundleContext context)
{
m_context = context;
try
{
org.osgi.service.log.LogService.class.getName();
m_isLogClassPresent = true;
}
catch (NoClassDefFoundError ex)
{
m_isLogClassPresent = false;
}
}
/**
* @see LogService#log(int, String)
*/
public void log(int level, String message)
{
log(level, message, null);
}
/**
* @see LogService#log(int, String, Throwable)
*/
public void log(int level, String message, Throwable exception)
{
if (!m_isLogClassPresent || !_log(level, message, exception))
{
final PrintStream stream = getStream(level);
stream.println(message);
if (exception != null)
{
exception.printStackTrace(stream);
}
}
}
/**
* Lookup the OSGi LogService and if available use it.
*/
private boolean _log(int level, String message, Throwable exception)
{
try
{
ServiceReference reference = null;
reference = m_context.getServiceReference(LogService.class.getName());
if (reference != null)
{
final LogService logService = (LogService) m_context.getService(reference);
if (logService != null)
{
logService.log(level, message, exception);
m_context.ungetService(reference);
return true;
}
}
}
catch (NoClassDefFoundError e)
{
//ignore
}
return false;
}
/**
* Return the standard print streams to use depending on log level.
*
* @param level log level
* @return print stream corresponding to log level
*/
private PrintStream getStream(int level)
{
switch (level)
{
case LOG_ERROR:
System.err.print("ERROR: ");
return System.err;
case LOG_WARNING:
System.err.print("WARNING: ");
return System.err;
case LOG_INFO:
System.out.print("INFO: ");
return System.out;
case LOG_DEBUG:
System.out.print("DEBUG: ");
return System.out;
default:
System.out.print("UNKNOWN: ");
return System.out;
}
}
} felix-utils-1.1.0/src/main/java/org/apache/felix/utils/manifest/ 0000775 0000000 0000000 00000000000 11556603426 0024507 5 ustar 00root root 0000000 0000000 felix-utils-1.1.0/src/main/java/org/apache/felix/utils/manifest/Attribute.java 0000664 0000000 0000000 00000002237 11556603426 0027321 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.utils.manifest;
public class Attribute
{
private final String name;
private final String value;
public Attribute(String name, String value)
{
this.name = name;
this.value = value;
}
public String getName()
{
return name;
}
public String getValue()
{
return value;
}
}
felix-utils-1.1.0/src/main/java/org/apache/felix/utils/manifest/Clause.java 0000664 0000000 0000000 00000005634 11556603426 0026576 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.utils.manifest;
public class Clause
{
private final String name;
private final Directive[] directives;
private final Attribute[] attributes;
public Clause(String name, Directive[] directives, Attribute[] attributes)
{
this.name = name;
this.directives = directives;
this.attributes = attributes;
}
public String getName()
{
return name;
}
public Directive[] getDirectives()
{
return directives;
}
public Attribute[] getAttributes()
{
return attributes;
}
public String getDirective(String name)
{
for (int i = 0; i < directives.length; i++)
{
if (name.equals(directives[i].getName()))
{
return directives[i].getValue();
}
}
return null;
}
public String getAttribute(String name)
{
for (int i = 0; i < attributes.length; i++)
{
if (name.equals(attributes[i].getName()))
{
return attributes[i].getValue();
}
}
return null;
}
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append(name);
for (int i = 0; directives != null && i < directives.length; i++)
{
sb.append(";").append(directives[i].getName()).append(":=");
if (directives[i].getValue().indexOf(",") >= 0)
{
sb.append("\"").append(directives[i].getValue()).append("\"");
}
else
{
sb.append(directives[i].getValue());
}
}
for (int i = 0; attributes != null && i < attributes.length; i++)
{
sb.append(";").append(attributes[i].getName()).append("=");
if (attributes[i].getValue().indexOf(",") >= 0)
{
sb.append("\"").append(attributes[i].getValue()).append("\"");
}
else
{
sb.append(attributes[i].getValue());
}
}
return sb.toString();
}
}
felix-utils-1.1.0/src/main/java/org/apache/felix/utils/manifest/Directive.java 0000664 0000000 0000000 00000002237 11556603426 0027274 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.utils.manifest;
public class Directive
{
private final String name;
private final String value;
public Directive(String name, String value)
{
this.name = name;
this.value = value;
}
public String getName()
{
return name;
}
public String getValue()
{
return value;
}
}
felix-utils-1.1.0/src/main/java/org/apache/felix/utils/manifest/Parser.java 0000664 0000000 0000000 00000016125 11556603426 0026613 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.utils.manifest;
import java.util.ArrayList;
import java.util.List;
public final class Parser
{
private Parser() { }
public static Clause[] parseHeader(String header) throws IllegalArgumentException
{
Clause[] clauses = null;
if (header != null)
{
if (header.length() == 0)
{
throw new IllegalArgumentException("The header cannot be an empty string.");
}
String[] ss = parseDelimitedString(header, ",");
clauses = parseClauses(ss);
}
return (clauses == null) ? new Clause[0] : clauses;
}
public static Clause[] parseClauses(String[] ss) throws IllegalArgumentException
{
if (ss == null)
{
return null;
}
List completeList = new ArrayList();
for (int ssIdx = 0; ssIdx < ss.length; ssIdx++)
{
// Break string into semi-colon delimited pieces.
String[] pieces = parseDelimitedString(ss[ssIdx], ";");
// Count the number of different clauses; clauses
// will not have an '=' in their string. This assumes
// that clauses come first, before directives and
// attributes.
int pathCount = 0;
for (int pieceIdx = 0; pieceIdx < pieces.length; pieceIdx++)
{
if (pieces[pieceIdx].indexOf('=') >= 0)
{
break;
}
pathCount++;
}
// Error if no packages were specified.
if (pathCount == 0)
{
throw new IllegalArgumentException("No path specified on clause: " + ss[ssIdx]);
}
// Parse the directives/attributes.
Directive[] dirs = new Directive[pieces.length - pathCount];
Attribute[] attrs = new Attribute[pieces.length - pathCount];
int dirCount = 0, attrCount = 0;
int idx = -1;
String sep = null;
for (int pieceIdx = pathCount; pieceIdx < pieces.length; pieceIdx++)
{
// Check if it is a directive.
if ((idx = pieces[pieceIdx].indexOf(":=")) >= 0)
{
sep = ":=";
}
// Check if it is an attribute.
else if ((idx = pieces[pieceIdx].indexOf("=")) >= 0)
{
sep = "=";
}
// It is an error.
else
{
throw new IllegalArgumentException("Not a directive/attribute: " + ss[ssIdx]);
}
String key = pieces[pieceIdx].substring(0, idx).trim();
String value = pieces[pieceIdx].substring(idx + sep.length()).trim();
// Remove quotes, if value is quoted.
if (value.startsWith("\"") && value.endsWith("\""))
{
value = value.substring(1, value.length() - 1);
}
// Save the directive/attribute in the appropriate array.
if (sep.equals(":="))
{
dirs[dirCount++] = new Directive(key, value);
}
else
{
attrs[attrCount++] = new Attribute(key, value);
}
}
// Shrink directive array.
Directive[] dirsFinal = new Directive[dirCount];
System.arraycopy(dirs, 0, dirsFinal, 0, dirCount);
// Shrink attribute array.
Attribute[] attrsFinal = new Attribute[attrCount];
System.arraycopy(attrs, 0, attrsFinal, 0, attrCount);
// Create package attributes for each package and
// set directives/attributes. Add each package to
// completel list of packages.
Clause[] pkgs = new Clause[pathCount];
for (int pkgIdx = 0; pkgIdx < pathCount; pkgIdx++)
{
pkgs[pkgIdx] = new Clause(pieces[pkgIdx], dirsFinal, attrsFinal);
completeList.add(pkgs[pkgIdx]);
}
}
Clause[] pkgs = (Clause[]) completeList.toArray(new Clause[completeList.size()]);
return pkgs;
}
/**
* Parses delimited string and returns an array containing the tokens. This
* parser obeys quotes, so the delimiter character will be ignored if it is
* inside of a quote. This method assumes that the quote character is not
* included in the set of delimiter characters.
* @param value the delimited string to parse.
* @param delim the characters delimiting the tokens.
* @return an array of string tokens or null if there were no tokens.
**/
public static String[] parseDelimitedString(String value, String delim)
{
if (value == null)
{
value = "";
}
List list = new ArrayList();
int CHAR = 1;
int DELIMITER = 2;
int STARTQUOTE = 4;
int ENDQUOTE = 8;
StringBuffer sb = new StringBuffer();
int expecting = (CHAR | DELIMITER | STARTQUOTE);
for (int i = 0; i < value.length(); i++)
{
char c = value.charAt(i);
boolean isDelimiter = (delim.indexOf(c) >= 0);
boolean isQuote = (c == '"');
if (isDelimiter && ((expecting & DELIMITER) > 0))
{
list.add(sb.toString().trim());
sb.delete(0, sb.length());
expecting = (CHAR | DELIMITER | STARTQUOTE);
}
else if (isQuote && ((expecting & STARTQUOTE) > 0))
{
sb.append(c);
expecting = CHAR | ENDQUOTE;
}
else if (isQuote && ((expecting & ENDQUOTE) > 0))
{
sb.append(c);
expecting = (CHAR | STARTQUOTE | DELIMITER);
}
else if ((expecting & CHAR) > 0)
{
sb.append(c);
}
else
{
throw new IllegalArgumentException("Invalid delimited string: " + value);
}
}
if (sb.length() > 0)
{
list.add(sb.toString().trim());
}
return (String[]) list.toArray(new String[list.size()]);
}
}
felix-utils-1.1.0/src/main/java/org/apache/felix/utils/properties/ 0000775 0000000 0000000 00000000000 11556603426 0025075 5 ustar 00root root 0000000 0000000 felix-utils-1.1.0/src/main/java/org/apache/felix/utils/properties/InterpolationHelper.java 0000664 0000000 0000000 00000017512 11556603426 0031735 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.felix.utils.properties;
import org.osgi.framework.BundleContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import java.util.*;
/**
* Properties
* managing the maintain of comments, etc.
* Properties
* managing the maintain of comments, etc.
* String
to a
* Writer
.String
to unescape, may be null
* @return the processed string
* @throws IllegalArgumentException if the Writer is null
*/
protected static String unescapeJava(String str) {
if (str == null) {
return null;
}
int sz = str.length();
StringBuffer out = new StringBuffer(sz);
StringBuffer unicode = new StringBuffer(UNICODE_LEN);
boolean hadSlash = false;
boolean inUnicode = false;
for (int i = 0; i < sz; i++) {
char ch = str.charAt(i);
if (inUnicode) {
// if in unicode, then we're reading unicode
// values in somehow
unicode.append(ch);
if (unicode.length() == UNICODE_LEN) {
// unicode now contains the four hex digits
// which represents our unicode character
try {
int value = Integer.parseInt(unicode.toString(), HEX_RADIX);
out.append((char) value);
unicode.setLength(0);
inUnicode = false;
hadSlash = false;
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Unable to parse unicode value: " + unicode, nfe);
}
}
continue;
}
if (hadSlash) {
// handle an escaped value
hadSlash = false;
switch (ch) {
case '\\' :
out.append('\\');
break;
case '\'' :
out.append('\'');
break;
case '\"' :
out.append('"');
break;
case 'r' :
out.append('\r');
break;
case 'f' :
out.append('\f');
break;
case 't' :
out.append('\t');
break;
case 'n' :
out.append('\n');
break;
case 'b' :
out.append('\b');
break;
case 'u' :
// uh-oh, we're in unicode country....
inUnicode = true;
break;
default :
out.append(ch);
break;
}
continue;
} else if (ch == '\\') {
hadSlash = true;
continue;
}
out.append(ch);
}
if (hadSlash) {
// then we're in the weird case of a \ at the end of the
// string, let's output it anyway.
out.append('\\');
}
return out.toString();
}
/**
* String
using Java String rules.'\\'
and
* 't'
.
* input string: He didn't say, "Stop!"
* output string: He didn't say, \"Stop!\"
*
*
null
if null string input
*/
protected static String escapeJava(String str) {
if (str == null) {
return null;
}
int sz = str.length();
StringBuffer out = new StringBuffer(sz * 2);
for (int i = 0; i < sz; i++) {
char ch = str.charAt(i);
// handle unicode
if (ch > 0xfff) {
out.append("\\u").append(hex(ch));
} else if (ch > 0xff) {
out.append("\\u0").append(hex(ch));
} else if (ch > 0x7f) {
out.append("\\u00").append(hex(ch));
} else if (ch < 32) {
switch (ch) {
case '\b' :
out.append('\\');
out.append('b');
break;
case '\n' :
out.append('\\');
out.append('n');
break;
case '\t' :
out.append('\\');
out.append('t');
break;
case '\f' :
out.append('\\');
out.append('f');
break;
case '\r' :
out.append('\\');
out.append('r');
break;
default :
if (ch > 0xf) {
out.append("\\u00").append(hex(ch));
} else {
out.append("\\u000").append(hex(ch));
}
break;
}
} else {
switch (ch) {
case '"' :
out.append('\\');
out.append('"');
break;
case '\\' :
out.append('\\');
out.append('\\');
break;
default :
out.append(ch);
break;
}
}
}
return out.toString();
}
/**
* Returns an upper case hexadecimal String
for the given
* character.
String
*/
protected static String hex(char ch) {
return Integer.toHexString(ch).toUpperCase(Locale.ENGLISH);
}
/**
* Checks if the value is in the given array.
* *The method returns false
if a null
array is passed in.
true
if the array contains the object
*/
public static boolean contains(char[] array, char valueToFind) {
if (array == null) {
return false;
}
for (int i = 0; i < array.length; i++) {
if (valueToFind == array[i]) {
return true;
}
}
return false;
}
/**
* This class is used to read properties lines. These lines do
* not terminate with new-line chars but rather when there is no
* backslash sign a the end of the line. This is used to
* concatenate multiple lines for readability.
*/
public static class PropertiesReader extends LineNumberReader
{
/** Stores the comment lines for the currently processed property.*/
private ListPropertiesReader
and sets
* the underlaying reader and the list delimiter.
*
* @param reader the reader
*/
public PropertiesReader(Reader reader)
{
super(reader);
commentLines = new ArrayList<name>
* = <value>
)
*
* @return A string containing a property value or null
*
* @throws java.io.IOException in case of an I/O error
*/
public String readProperty() throws IOException
{
commentLines.clear();
valueLines.clear();
StringBuffer buffer = new StringBuffer();
while (true)
{
String line = readLine();
if (line == null)
{
// EOF
return null;
}
if (isCommentLine(line))
{
commentLines.add(line);
continue;
}
valueLines.add(line);
line = line.trim();
if (checkCombineLines(line))
{
line = line.substring(0, line.length() - 1);
buffer.append(line);
}
else
{
buffer.append(line);
break;
}
}
return buffer.toString();
}
/**
* Parses the next property from the input stream and stores the found
* name and value in internal fields. These fields can be obtained using
* the provided getter methods. The return value indicates whether EOF
* was reached (false) or whether further properties are
* available (true).
*
* @return a flag if further properties are available
* @throws java.io.IOException if an error occurs
*/
public boolean nextProperty() throws IOException
{
String line = readProperty();
if (line == null)
{
return false; // EOF
}
// parse the line
String[] property = parseProperty(line);
propertyName = unescapeJava(property[0]);
propertyValue = unescapeJava(property[1]);
return true;
}
/**
* Returns the comment lines that have been read for the last property.
*
* @return the comment lines for the last property returned by
* readProperty()
*/
public ListreadProperty()
*/
public List{@link #nextProperty()}
was invoked and its
* return value was true.
*
* @return the name of the last read property
*/
public String getPropertyName()
{
return propertyName;
}
/**
* Returns the value of the last read property. This method can be
* called after {@link #nextProperty()}
was invoked and
* its return value was true.
*
* @return the value of the last read property
*/
public String getPropertyValue()
{
return propertyValue;
}
/**
* Checks if the passed in line should be combined with the following.
* This is true, if the line ends with an odd number of backslashes.
*
* @param line the line
* @return a flag if the lines should be combined
*/
private static boolean checkCombineLines(String line)
{
int bsCount = 0;
for (int idx = line.length() - 1; idx >= 0 && line.charAt(idx) == '\\'; idx--)
{
bsCount++;
}
return bsCount % 2 != 0;
}
/**
* Parse a property line and return the key and the value in an array.
*
* @param line the line to parse
* @return an array with the property's key and value
*/
private static String[] parseProperty(String line)
{
// sorry for this spaghetti code, please replace it as soon as
// possible with a regexp when the Java 1.3 requirement is dropped
String[] result = new String[2];
StringBuffer key = new StringBuffer();
StringBuffer value = new StringBuffer();
// state of the automaton:
// 0: key parsing
// 1: antislash found while parsing the key
// 2: separator crossing
// 3: value parsing
int state = 0;
for (int pos = 0; pos < line.length(); pos++)
{
char c = line.charAt(pos);
switch (state)
{
case 0:
if (c == '\\')
{
state = 1;
}
else if (contains(WHITE_SPACE, c))
{
// switch to the separator crossing state
state = 2;
}
else if (contains(SEPARATORS, c))
{
// switch to the value parsing state
state = 3;
}
else
{
key.append(c);
}
break;
case 1:
if (contains(SEPARATORS, c) || contains(WHITE_SPACE, c))
{
// this is an escaped separator or white space
key.append(c);
}
else
{
// another escaped character, the '\' is preserved
key.append('\\');
key.append(c);
}
// return to the key parsing state
state = 0;
break;
case 2:
if (contains(WHITE_SPACE, c))
{
// do nothing, eat all white spaces
state = 2;
}
else if (contains(SEPARATORS, c))
{
// switch to the value parsing state
state = 3;
}
else
{
// any other character indicates we encoutered the beginning of the value
value.append(c);
// switch to the value parsing state
state = 3;
}
break;
case 3:
value.append(c);
break;
}
}
result[0] = key.toString().trim();
result[1] = value.toString().trim();
return result;
}
} // class PropertiesReader
/**
* This class is used to write properties lines.
*/
public static class PropertiesWriter extends FilterWriter
{
/**
* Constructor.
*
* @param writer a Writer object providing the underlying stream
*/
public PropertiesWriter(Writer writer)
{
super(writer);
}
/**
* Writes the given property and its value.
*
* @param key the property key
* @param value the property value
* @throws java.io.IOException if an error occurs
*/
public void writeProperty(String key, String value) throws IOException
{
write(escapeKey(key));
write(" = ");
write(escapeJava(value));
writeln(null);
}
/**
* Escape the separators in the key.
*
* @param key the key
* @return the escaped key
*/
private String escapeKey(String key)
{
StringBuffer newkey = new StringBuffer();
for (int i = 0; i < key.length(); i++)
{
char c = key.charAt(i);
if (contains(SEPARATORS, c) || contains(WHITE_SPACE, c))
{
// escape the separator
newkey.append('\\');
newkey.append(c);
}
else
{
newkey.append(c);
}
}
return newkey.toString();
}
/**
* Helper method for writing a line with the platform specific line
* ending.
*
* @param s the content of the line (may be null)
* @throws java.io.IOException if an error occurs
*/
public void writeln(String s) throws IOException
{
if (s != null)
{
write(s);
}
write(LINE_SEPARATOR);
}
} // class PropertiesWriter
/**
* TODO
*/
protected static class Layout {
private List
* Unit tests on Properties
.
*
* Test getting property. *
* * @throws Exception */ public void testGettingProperty() throws Exception { assertEquals("test", properties.get("test")); } public void testLoadSave() throws IOException { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println("# "); pw.println("# The Main "); pw.println("# "); pw.println("# Comment "); pw.println("# "); pw.println(""); pw.println("# Another comment"); pw.println(""); pw.println("# A value comment"); pw.println("key1 = val1"); pw.println(""); pw.println("# Another value comment"); pw.println("key2 = ${key1}/foo"); pw.println(""); pw.println("# A third comment"); pw.println("key3 = val3"); pw.println(""); Properties props = new Properties(); props.load(new StringReader(sw.toString())); props.save(System.err); System.err.println("====="); props.put("key2", props.get("key2")); props.put("key3", "foo"); props.save(System.err); System.err.println("====="); } } felix-utils-1.1.0/src/test/java/org/apache/felix/utils/version/ 0000775 0000000 0000000 00000000000 11556603426 0024421 5 ustar 00root root 0000000 0000000 felix-utils-1.1.0/src/test/java/org/apache/felix/utils/version/VersionCleanerTest.java 0000664 0000000 0000000 00000005243 11556603426 0031047 0 ustar 00root root 0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.felix.utils.version; import junit.framework.TestCase; public class VersionCleanerTest extends TestCase { public void testConvertVersionToOsgi() { String osgiVersion; osgiVersion = VersionCleaner.clean(null); assertEquals("0.0.0", osgiVersion); osgiVersion = VersionCleaner.clean(""); assertEquals("0.0.0", osgiVersion); osgiVersion = VersionCleaner.clean("2.1.0-SNAPSHOT"); assertEquals("2.1.0.SNAPSHOT", osgiVersion); osgiVersion = VersionCleaner.clean("2.1-SNAPSHOT"); assertEquals("2.1.0.SNAPSHOT", osgiVersion); osgiVersion = VersionCleaner.clean("2-SNAPSHOT"); assertEquals("2.0.0.SNAPSHOT", osgiVersion); osgiVersion = VersionCleaner.clean("2"); assertEquals("2.0.0", osgiVersion); osgiVersion = VersionCleaner.clean("2.1"); assertEquals("2.1.0", osgiVersion); osgiVersion = VersionCleaner.clean("2.1.3"); assertEquals("2.1.3", osgiVersion); osgiVersion = VersionCleaner.clean("2.1.3.4"); assertEquals("2.1.3.4", osgiVersion); osgiVersion = VersionCleaner.clean("4aug2000r7-dev"); assertEquals("0.0.0.4aug2000r7-dev", osgiVersion); osgiVersion = VersionCleaner.clean("1.1-alpha-2"); assertEquals("1.1.0.alpha-2", osgiVersion); osgiVersion = VersionCleaner.clean("1.0-alpha-16-20070122.203121-13"); assertEquals("1.0.0.alpha-16-20070122_203121-13", osgiVersion); osgiVersion = VersionCleaner.clean("1.0-20070119.021432-1"); assertEquals("1.0.0.20070119_021432-1", osgiVersion); osgiVersion = VersionCleaner.clean("1-20070119.021432-1"); assertEquals("1.0.0.20070119_021432-1", osgiVersion); osgiVersion = VersionCleaner.clean("1.4.1-20070217.082013-7"); assertEquals("1.4.1.20070217_082013-7", osgiVersion); } } felix-utils-1.1.0/src/test/java/org/apache/felix/utils/version/VersionRangeTest.java 0000664 0000000 0000000 00000020770 11556603426 0030534 0 ustar 00root root 0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.felix.utils.version; import junit.framework.TestCase; import org.osgi.framework.Version; public class VersionRangeTest extends TestCase { public void testVersionRange() throws Exception { String version1 = "[1.2.3, 4.5.6]"; String version2 = "(1, 2]"; String version3 = "[2,4)"; String version4 = "(1,2)"; String version5 = "2"; String version6 = "2.3"; String version7 = "[1.2.3.q, 2.3.4.p)"; String version8 = "1.2.2.5"; String version9 = "a.b.c"; String version10 = null; String version11 = ""; String version12 = "\"[1.2.3, 4.5.6]\""; VersionRange vr = new VersionRange(version1); assertEquals("The value is wrong", "1.2.3", vr.getFloor().toString()); assertFalse("The value is wrong", vr.isOpenFloor()); assertEquals("The value is wrong", "4.5.6", vr.getCeiling().toString()); assertFalse("The value is wrong", vr.isOpenCeiling()); vr = new VersionRange(version2); assertEquals("The value is wrong", "1.0.0", vr.getFloor().toString()); assertTrue("The value is wrong", vr.isOpenFloor()); assertEquals("The value is wrong", "2.0.0", vr.getCeiling().toString()); assertFalse("The value is wrong", vr.isOpenCeiling()); vr = new VersionRange(version3); assertEquals("The value is wrong", "2.0.0", vr.getFloor().toString()); assertFalse("The value is wrong", vr.isOpenFloor()); assertEquals("The value is wrong", "4.0.0", vr.getCeiling().toString()); assertTrue("The value is wrong", vr.isOpenCeiling()); vr = new VersionRange(version4); assertEquals("The value is wrong", "1.0.0", vr.getFloor().toString()); assertTrue("The value is wrong", vr.isOpenFloor()); assertEquals("The value is wrong", "2.0.0", vr.getCeiling().toString()); assertTrue("The value is wrong", vr.isOpenCeiling()); vr = new VersionRange(version5); assertEquals("The value is wrong", "2.0.0", vr.getFloor().toString()); assertFalse("The value is wrong", vr.isOpenFloor()); assertEquals("The value is wrong", VersionRange.INFINITE_VERSION, vr.getCeiling()); assertTrue("The value is wrong", vr.isOpenCeiling()); vr = new VersionRange(version6, true); assertEquals("The value is wrong", "2.3.0", vr.getFloor().toString()); assertFalse("The value is wrong", vr.isOpenFloor()); assertEquals("The value is wrong", "2.3.0", vr.getCeiling().toString()); assertFalse("The value is wrong", vr.isOpenCeiling()); vr = new VersionRange(version7); assertEquals("The value is wrong", "1.2.3.q", vr.getFloor().toString()); assertFalse("The value is wrong", vr.isOpenFloor()); assertEquals("The value is wrong", "2.3.4.p", vr.getCeiling().toString()); assertTrue("The value is wrong", vr.isOpenCeiling()); vr = new VersionRange(version8); assertEquals("The value is wrong", "1.2.2.5", vr.getFloor().toString()); assertFalse("The value is wrong", vr.isOpenFloor()); assertEquals("The value is wrong", VersionRange.INFINITE_VERSION, vr.getCeiling()); assertTrue("The value is wrong", vr.isOpenCeiling()); boolean exception = false; try { vr = new VersionRange(version9, false, false); } catch (Exception e) { exception = true; } assertTrue("The value is wrong", exception); boolean exceptionNull = false; try { vr = new VersionRange(version10, false, false); } catch (Exception e) { exceptionNull = true; } assertTrue("The value is wrong", exceptionNull); // empty version should be defaulted to >=0.0.0 vr = VersionRange.parseVersionRange(version11); assertEquals("The value is wrong", "0.0.0", vr.getFloor().toString()); assertFalse("The value is wrong", vr.isOpenFloor()); assertEquals("The value is wrong", VersionRange.INFINITE_VERSION, vr.getCeiling()); assertTrue("The value is wrong", vr.isOpenCeiling()); vr = new VersionRange(version12); assertEquals("The value is wrong", "1.2.3", vr.getFloor().toString()); assertFalse("The value is wrong", vr.isOpenFloor()); assertEquals("The value is wrong", "4.5.6", vr.getCeiling().toString()); assertFalse("The value is wrong", vr.isOpenCeiling()); } public void testInvalidVersions() throws Exception { try { new VersionRange("a", false, false); assertTrue("Should have thrown an exception", false); } catch (IllegalArgumentException e) { } } public void testMatches() { VersionRange vr = new VersionRange("[1.0.0, 2.0.0]"); assertFalse(vr.contains(new Version(0, 9, 0))); assertFalse(vr.contains(new Version(2, 1, 0))); assertTrue(vr.contains(new Version(2, 0, 0))); assertTrue(vr.contains(new Version(1, 0, 0))); assertTrue(vr.contains(new Version(1, 5, 0))); vr = new VersionRange("[1.0.0, 2.0.0)"); assertFalse(vr.contains(new Version(0, 9, 0))); assertFalse(vr.contains(new Version(2, 1, 0))); assertFalse(vr.contains(new Version(2, 0, 0))); assertTrue(vr.contains(new Version(1, 0, 0))); assertTrue(vr.contains(new Version(1, 5, 0))); vr = new VersionRange("(1.0.0, 2.0.0)"); assertFalse(vr.contains(new Version(0, 9, 0))); assertFalse(vr.contains(new Version(2, 1, 0))); assertFalse(vr.contains(new Version(2, 0, 0))); assertFalse(vr.contains(new Version(1, 0, 0))); assertTrue(vr.contains(new Version(1, 5, 0))); vr = new VersionRange("[1.0.0, 1.0.0]"); assertFalse(vr.contains(new Version(0, 9, 0))); assertFalse(vr.contains(new Version(2, 0, 0))); assertTrue(vr.contains(new Version(1, 0, 0))); assertFalse(vr.contains(new Version(1, 5, 0))); assertFalse(vr.contains(new Version(1, 9, 9))); } public void testIntersectVersionRange_Valid1() { VersionRange v1 = new VersionRange("[1.0.0,3.0.0]"); VersionRange v2 = new VersionRange("[2.0.0,3.0.0)"); VersionRange result = v1.intersect(v2); assertNotNull(result); assertEquals("[2.0.0,3.0.0)", result.toString()); } public void testIntersectVersionRange_Valid2() { VersionRange v1 = new VersionRange("[1.0.0,3.0.0)"); VersionRange v2 = new VersionRange("(2.0.0,3.0.0]"); VersionRange result = v1.intersect(v2); assertNotNull(result); assertEquals("(2.0.0,3.0.0)", result.toString()); } public void testIntersectVersionRange_Valid3() { VersionRange v1 = new VersionRange("[2.0.0,2.0.0]"); VersionRange v2 = new VersionRange("[1.0.0,3.0.0]"); VersionRange result = v1.intersect(v2); assertNotNull(result); assertEquals("[2.0.0,2.0.0]", result.toString()); } public void testIntersectVersionRange_Invalid1() { VersionRange v1 = new VersionRange("[1.0.0,2.0.0]"); VersionRange v2 = new VersionRange("(2.0.0,3.0.0]"); VersionRange result = v1.intersect(v2); assertNull(result); } public void testIntersectVersionRange_Invalid2() { VersionRange v1 = new VersionRange("[1.0.0,2.0.0)"); VersionRange v2 = new VersionRange("[2.0.0,3.0.0]"); VersionRange result = v1.intersect(v2); assertNull(result); } public void testIntersectVersionRange_Invalid3() { VersionRange v1 = new VersionRange("[1.0.0,1.0.0]"); VersionRange v2 = new VersionRange("[2.0.0,2.0.0]"); VersionRange result = v1.intersect(v2); assertNull(result); } } felix-utils-1.1.0/src/test/resources/ 0000775 0000000 0000000 00000000000 11556603426 0017546 5 ustar 00root root 0000000 0000000 felix-utils-1.1.0/src/test/resources/test.properties 0000664 0000000 0000000 00000001776 11556603426 0022656 0 ustar 00root root 0000000 0000000 ##--------------------------------------------------------------------------- ## Licensed to the Apache Software Foundation (ASF) under one or more ## contributor license agreements. See the NOTICE file distributed with ## this work for additional information regarding copyright ownership. ## The ASF licenses this file to You under the Apache License, Version 2.0 ## (the "License"); you may not use this file except in compliance with ## the License. You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ##--------------------------------------------------------------------------- # # test.properties # Used in the PropertiesTest # test=test