repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/DivideFunction.java | /*
* @(#)DivideFunction.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.DoubleAttribute;
import org.wso2.balana.attr.IntegerAttribute;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A class that implements all the *-divide functions. It takes two operands of the appropriate type
* and returns the quotient of the operands. If either of the operands is indeterminate, an
* indeterminate result is returned.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class DivideFunction extends FunctionBase {
/**
* Standard identifier for the integer-divide function.
*/
public static final String NAME_INTEGER_DIVIDE = FUNCTION_NS + "integer-divide";
/**
* Standard identifier for the double-divide function.
*/
public static final String NAME_DOUBLE_DIVIDE = FUNCTION_NS + "double-divide";
// inernal identifiers for each of the supported functions
private static final int ID_INTEGER_DIVIDE = 0;
private static final int ID_DOUBLE_DIVIDE = 1;
/**
* Creates a new <code>DivideFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public DivideFunction(String functionName) {
super(functionName, getId(functionName), getArgumentType(functionName), false, 2,
getArgumentType(functionName), false);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*/
private static int getId(String functionName) {
if (functionName.equals(NAME_INTEGER_DIVIDE))
return ID_INTEGER_DIVIDE;
else if (functionName.equals(NAME_DOUBLE_DIVIDE))
return ID_DOUBLE_DIVIDE;
else
throw new IllegalArgumentException("unknown divide function " + functionName);
}
/**
* Private helper that returns the type used for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String getArgumentType(String functionName) {
if (functionName.equals(NAME_INTEGER_DIVIDE))
return IntegerAttribute.identifier;
else
return DoubleAttribute.identifier;
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_INTEGER_DIVIDE);
set.add(NAME_DOUBLE_DIVIDE);
return set;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have real values, perform the divide operation
// in the manner appropriate for the type of the arguments.
switch (getFunctionId()) {
case ID_INTEGER_DIVIDE: {
long dividend = ((IntegerAttribute) argValues[0]).getValue();
long divisor = ((IntegerAttribute) argValues[1]).getValue();
if (divisor == 0) {
result = makeProcessingError("divide by zero");
break;
}
long quotient = dividend / divisor;
result = new EvaluationResult(new IntegerAttribute(quotient));
break;
}
case ID_DOUBLE_DIVIDE: {
double dividend = ((DoubleAttribute) argValues[0]).getValue();
double divisor = ((DoubleAttribute) argValues[1]).getValue();
if (divisor == 0) {
result = makeProcessingError("divide by zero");
break;
}
double quotient = dividend / divisor;
result = new EvaluationResult(new DoubleAttribute(quotient));
break;
}
}
return result;
}
}
| 6,675 | 36.717514 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/NumericConvertFunction.java | /*
* @(#)NumericConvertFunction.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.DoubleAttribute;
import org.wso2.balana.attr.IntegerAttribute;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A class that implements all the numeric type conversion functions (double-to-integer and
* integer-to-double). It takes one argument of the appropriate type, converts that argument to the
* other type, and returns the result. If the argument is indeterminate, an indeterminate result is
* returned.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class NumericConvertFunction extends FunctionBase {
/**
* Standard identifier for the double-to-integer function.
*/
public static final String NAME_DOUBLE_TO_INTEGER = FUNCTION_NS + "double-to-integer";
/**
* Standard identifier for the integer-to-double function.
*/
public static final String NAME_INTEGER_TO_DOUBLE = FUNCTION_NS + "integer-to-double";
// private identifiers for the supported functions
private static final int ID_DOUBLE_TO_INTEGER = 0;
private static final int ID_INTEGER_TO_DOUBLE = 1;
/**
* Creates a new <code>NumericConvertFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknwon
*/
public NumericConvertFunction(String functionName) {
super(functionName, getId(functionName), getArgumentType(functionName), false, 1,
getReturnType(functionName), false);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*/
private static int getId(String functionName) {
if (functionName.equals(NAME_DOUBLE_TO_INTEGER))
return ID_DOUBLE_TO_INTEGER;
else if (functionName.equals(NAME_INTEGER_TO_DOUBLE))
return ID_INTEGER_TO_DOUBLE;
else
throw new IllegalArgumentException("unknown convert function " + functionName);
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_DOUBLE_TO_INTEGER);
set.add(NAME_INTEGER_TO_DOUBLE);
return set;
}
/**
* Private helper that returns the type used for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String getArgumentType(String functionName) {
if (functionName.equals(NAME_DOUBLE_TO_INTEGER))
return DoubleAttribute.identifier;
else
return IntegerAttribute.identifier;
}
/**
* Private helper that returns the return type for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String getReturnType(String functionName) {
if (functionName.equals(NAME_DOUBLE_TO_INTEGER))
return IntegerAttribute.identifier;
else
return DoubleAttribute.identifier;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have real values, perform the numeric conversion
// operation in the manner appropriate for this function.
switch (getFunctionId()) {
case ID_DOUBLE_TO_INTEGER: {
double arg0 = ((DoubleAttribute) argValues[0]).getValue();
long longValue = (long) arg0;
result = new EvaluationResult(new IntegerAttribute(longValue));
break;
}
case ID_INTEGER_TO_DOUBLE: {
long arg0 = ((IntegerAttribute) argValues[0]).getValue();
double doubleValue = (double) arg0;
result = new EvaluationResult(new DoubleAttribute(doubleValue));
break;
}
}
return result;
}
}
| 6,891 | 38.159091 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/StringFunction.java | /*
* @(#)StringFunction.java
*
* Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.StringAttribute;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* This class implements the string-concatenate function from XACML 2.0.
*
* @since 2.0
* @author Seth Proctor
*/
public class StringFunction extends FunctionBase {
/**
* Standard identifier for the string-concatenate function.
*/
public static final String NAME_STRING_CONCATENATE = FUNCTION_NS_2 + "string-concatenate";
// private identifiers for the supported functions
private static final int ID_STRING_CONCATENATE = 0;
/**
* Creates a new <code>StringFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public StringFunction(String functionName) {
super(functionName, ID_STRING_CONCATENATE, StringAttribute.identifier, false, -1, 2,
StringAttribute.identifier, false);
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_STRING_CONCATENATE);
return set;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
switch (getFunctionId()) {
case ID_STRING_CONCATENATE:
String str = ((StringAttribute) argValues[0]).getValue();
StringBuffer buffer = new StringBuffer(str);
for (int i = 1; i < argValues.length; i++) {
buffer.append(((StringAttribute) (argValues[i])).getValue());
}
result = new EvaluationResult(new StringAttribute(buffer.toString()));
break;
}
return result;
}
}
| 4,351 | 35.266667 | 97 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/MultiplyFunction.java | /*
* @(#)MultiplyFunction.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.DoubleAttribute;
import org.wso2.balana.attr.IntegerAttribute;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A class that implements all the *-multiply functions. It takes two operands of the appropriate
* type and returns the product of the operands. If either of the operands is indeterminate, an
* indeterminate result is returned.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class MultiplyFunction extends FunctionBase {
/**
* Standard identifier for the integer-multiply function.
*/
public static final String NAME_INTEGER_MULTIPLY = FUNCTION_NS + "integer-multiply";
/**
* Standard identifier for the double-multiply function.
*/
public static final String NAME_DOUBLE_MULTIPLY = FUNCTION_NS + "double-multiply";
// inernal identifiers for each of the supported functions
private static final int ID_INTEGER_MULTIPLY = 0;
private static final int ID_DOUBLE_MULTIPLY = 1;
/**
* Creates a new <code>MultiplyFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public MultiplyFunction(String functionName) {
super(functionName, getId(functionName), getArgumentType(functionName), false, 2,
getArgumentType(functionName), false);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*/
private static int getId(String functionName) {
if (functionName.equals(NAME_INTEGER_MULTIPLY))
return ID_INTEGER_MULTIPLY;
else if (functionName.equals(NAME_DOUBLE_MULTIPLY))
return ID_DOUBLE_MULTIPLY;
else
throw new IllegalArgumentException("unknown multiply function " + functionName);
}
/**
* Private helper that returns the type used for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String getArgumentType(String functionName) {
if (functionName.equals(NAME_INTEGER_MULTIPLY))
return IntegerAttribute.identifier;
else
return DoubleAttribute.identifier;
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_INTEGER_MULTIPLY);
set.add(NAME_DOUBLE_MULTIPLY);
return set;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have real values, perform the multiply operation
// in the manner appropriate for the type of the arguments.
switch (getFunctionId()) {
case ID_INTEGER_MULTIPLY: {
long arg0 = ((IntegerAttribute) argValues[0]).getValue();
long arg1 = ((IntegerAttribute) argValues[1]).getValue();
long product = arg0 * arg1;
result = new EvaluationResult(new IntegerAttribute(product));
break;
}
case ID_DOUBLE_MULTIPLY: {
double arg0 = ((DoubleAttribute) argValues[0]).getValue();
double arg1 = ((DoubleAttribute) argValues[1]).getValue();
double product = arg0 * arg1;
result = new EvaluationResult(new DoubleAttribute(product));
break;
}
}
return result;
}
}
| 6,420 | 37.915152 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/ExpressionHandler.java | /*
* ExpressionHandler.java
*
* Created by: seth proctor (stp)
* Created on: Wed Dec 29, 2004 8:24:30 PM
* Desc:
*
*/
package org.wso2.balana.cond;
import org.wso2.balana.*;
import org.wso2.balana.attr.AttributeDesignatorFactory;
import org.wso2.balana.attr.AttributeFactory;
import org.wso2.balana.attr.AttributeSelector;
import org.w3c.dom.Node;
import org.wso2.balana.attr.AttributeSelectorFactory;
import java.net.URI;
/**
* This is a package-private utility class that handles parsing all the possible expression types.
* It was added becuase in 2.0 multiple classes needed this. Note that this could also be added to
* Expression and that interface could be made an abstract class, but that would require substantial
* change.
*
* @since 2.0
* @author Seth Proctor
*/
public class ExpressionHandler {
/**
* Parses an expression, recursively handling any sub-elements. This is provided as a utility
* class, but in practice is used only by <code>Apply</code>, <code>Condition</code>, and
* <code>VariableDefinition</code>.
*
* @param root the DOM root of an ExpressionType XML type
* @param metaData the meta-data associated with the containing policy
* @param manager <code>VariableManager</code> used to connect references and definitions while
* parsing
*
* @return an <code>Expression</code> or null if the root node cannot be parsed as a valid
* Expression
* @throws org.wso2.balana.ParsingException
*/
public static Expression parseExpression(Node root, PolicyMetaData metaData,
VariableManager manager) throws ParsingException {
String name = DOMHelper.getLocalName(root);
if (name.equals("Apply")) {
return Apply.getInstance(root, metaData, manager);
} else if (name.equals("AttributeValue")) {
try {
return Balana.getInstance().getAttributeFactory().createValue(root);
} catch (UnknownIdentifierException uie) {
throw new ParsingException("Unknown DataType", uie);
}
} else if("AttributeDesignator".equals(name)){
return AttributeDesignatorFactory.getFactory().getAbstractDesignator(root, metaData);
} else if (name.equals("SubjectAttributeDesignator")) {
return AttributeDesignatorFactory.getFactory().getAbstractDesignator(root, metaData);
} else if (name.equals("ResourceAttributeDesignator")) {
return AttributeDesignatorFactory.getFactory().getAbstractDesignator(root, metaData);
} else if (name.equals("ActionAttributeDesignator")) {
return AttributeDesignatorFactory.getFactory().getAbstractDesignator(root, metaData);
} else if (name.equals("EnvironmentAttributeDesignator")) {
return AttributeDesignatorFactory.getFactory().getAbstractDesignator(root, metaData);
} else if (name.equals("AttributeSelector")) {
return AttributeSelectorFactory.getFactory().getAbstractSelector(root, metaData);
} else if (name.equals("Function")) {
return getFunction(root, metaData, FunctionFactory.getGeneralInstance());
} else if (name.equals("VariableReference")) {
return VariableReference.getInstance(root, metaData, manager);
}
// return null if it was none of these
return null;
}
/**
* Helper method that tries to get a function instance
*/
public static Function getFunction(Node root, PolicyMetaData metaData, FunctionFactory factory)
throws ParsingException {
String functionName;
try {
Node functionNode = root.getAttributes().getNamedItem("FunctionId");
functionName = functionNode.getNodeValue();
} catch (Exception e) {
throw new ParsingException("Error parsing required FunctionId in " +
"FunctionType", e);
}
try {
// try to get an instance of the given function
return factory.createFunction(functionName);
} catch (UnknownIdentifierException uie) {
throw new ParsingException("Unknown FunctionId", uie);
} catch (FunctionTypeException fte) {
// try creating as an abstract function
try {
FunctionFactory ff = FunctionFactory.getGeneralInstance();
return ff.createAbstractFunction(functionName, root, metaData.getXPathIdentifier());
} catch (Exception e) {
// any exception at this point is a failure
throw new ParsingException("failed to create abstract function" + " "
+ functionName, e);
}
}
}
}
| 4,778 | 39.846154 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/ConditionBagFunction.java | /*
* @(#)ConditionBagFunction.java
*
* Copyright 2004-206 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.BagAttribute;
import org.wso2.balana.attr.BooleanAttribute;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
/**
* Specific <code>BagFunction</code> class that supports the single condition bag function:
* type-is-in.
*
* @since 1.2
* @author Seth Proctor
*/
public class ConditionBagFunction extends BagFunction {
// mapping of function name to its associated argument type
private static HashMap argMap;
/**
* Static initializer that sets up the argument info for all the supported functions.
*/
static {
argMap = new HashMap();
for (int i = 0; i < baseTypes.length; i++) {
String[] args = { baseTypes[i], baseTypes[i] };
argMap.put(FUNCTION_NS + simpleTypes[i] + NAME_BASE_IS_IN, args);
}
for (int i = 0; i < baseTypes2.length; i++) {
String[] args = { baseTypes2[i], baseTypes2[i] };
argMap.put(FUNCTION_NS_2 + simpleTypes2[i] + NAME_BASE_IS_IN, args);
}
}
/**
* Constructor that is used to create one of the condition standard bag functions. The name
* supplied must be one of the standard XACML functions supported by this class, including the
* full namespace, otherwise an exception is thrown. Look in <code>BagFunction</code> for
* details about the supported names.
*
* @param functionName the name of the function to create
*
* @throws IllegalArgumentException if the function is unknown
*/
public ConditionBagFunction(String functionName) {
super(functionName, 0, getArguments(functionName));
}
/**
* Constructor that is used to create instances of condition bag functions for new
* (non-standard) datatypes. This is equivalent to using the <code>getInstance</code> methods in
* <code>BagFunction</code> and is generally only used by the run-time configuration code.
*
* @param functionName the name of the new function
* @param datatype the full identifier for the supported datatype
*/
public ConditionBagFunction(String functionName, String datatype) {
super(functionName, 0, new String[] { datatype, datatype });
}
/**
* Private helper that returns the argument types for the given standard function.
*/
private static String[] getArguments(String functionName) {
String[] args = (String[]) (argMap.get(functionName));
if (args == null)
throw new IllegalArgumentException("unknown bag function: " + functionName);
return args;
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
return Collections.unmodifiableSet(argMap.keySet());
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// *-is-in takes a bag and an element of baseType and
// returns a single boolean value
AttributeValue item = (AttributeValue) (argValues[0]);
BagAttribute bag = (BagAttribute) (argValues[1]);
return new EvaluationResult(BooleanAttribute.getInstance(bag.contains(item)));
}
}
| 5,967 | 38.006536 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/GeneralBagFunction.java | /*
* @(#)GeneralBagFunction.java
*
* Copyright 2004-2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.BagAttribute;
import org.wso2.balana.attr.IntegerAttribute;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Specific <code>BagFunction</code> class that supports all of the general-purpose bag functions:
* type-one-and-only, type-bag-size, and type-bag.
*
* @since 1.2
* @author Seth Proctor
*/
public class GeneralBagFunction extends BagFunction {
// private identifiers for the supported functions
private static final int ID_BASE_ONE_AND_ONLY = 0;
private static final int ID_BASE_BAG_SIZE = 1;
private static final int ID_BASE_BAG = 2;
// mapping of function name to its associated parameters
private static HashMap paramMap;
private static Set supportedIds;
/**
* Static initializer that sets up the paramater info for all the supported functions.
*/
static {
paramMap = new HashMap();
for (int i = 0; i < baseTypes.length; i++) {
String baseType = baseTypes[i];
String functionBaseName = FUNCTION_NS + simpleTypes[i];
paramMap.put(functionBaseName + NAME_BASE_ONE_AND_ONLY, new BagParameters(
ID_BASE_ONE_AND_ONLY, baseType, true, 1, baseType, false));
paramMap.put(functionBaseName + NAME_BASE_BAG_SIZE, new BagParameters(ID_BASE_BAG_SIZE,
baseType, true, 1, IntegerAttribute.identifier, false));
paramMap.put(functionBaseName + NAME_BASE_BAG, new BagParameters(ID_BASE_BAG, baseType,
false, -1, baseType, true));
}
for (int i = 0; i < baseTypes2.length; i++) {
String baseType = baseTypes2[i];
String functionBaseName = FUNCTION_NS_2 + simpleTypes2[i];
paramMap.put(functionBaseName + NAME_BASE_ONE_AND_ONLY, new BagParameters(
ID_BASE_ONE_AND_ONLY, baseType, true, 1, baseType, false));
paramMap.put(functionBaseName + NAME_BASE_BAG_SIZE, new BagParameters(ID_BASE_BAG_SIZE,
baseType, true, 1, IntegerAttribute.identifier, false));
paramMap.put(functionBaseName + NAME_BASE_BAG, new BagParameters(ID_BASE_BAG, baseType,
false, -1, baseType, true));
}
supportedIds = Collections.unmodifiableSet(new HashSet(paramMap.keySet()));
paramMap.put(NAME_BASE_ONE_AND_ONLY, new BagParameters(ID_BASE_ONE_AND_ONLY, null, true, 1,
null, false));
paramMap.put(NAME_BASE_BAG_SIZE, new BagParameters(ID_BASE_BAG_SIZE, null, true, 1,
IntegerAttribute.identifier, false));
paramMap.put(NAME_BASE_BAG, new BagParameters(ID_BASE_BAG, null, false, -1, null, true));
};
/**
* Constructor that is used to create one of the general-purpose standard bag functions. The
* name supplied must be one of the standard XACML functions supported by this class, including
* the full namespace, otherwise an exception is thrown. Look in <code>BagFunction</code> for
* details about the supported names.
*
* @param functionName the name of the function to create
*
* @throws IllegalArgumentException if the function is unknown
*/
public GeneralBagFunction(String functionName) {
super(functionName, getId(functionName), getArgumentType(functionName),
getIsBag(functionName), getNumArgs(functionName), getReturnType(functionName),
getReturnsBag(functionName));
}
/**
* Constructor that is used to create instances of general-purpose bag functions for new
* (non-standard) datatypes. This is equivalent to using the <code>getInstance</code> methods in
* <code>BagFunction</code> and is generally only used by the run-time configuration code.
*
* @param functionName the name of the new function
* @param datatype the full identifier for the supported datatype
* @param functionType which kind of Bag function, based on the <code>NAME_BASE_*</code> fields
*/
public GeneralBagFunction(String functionName, String datatype, String functionType) {
super(functionName, getId(functionType), datatype, getIsBag(functionType),
getNumArgs(functionType), getCustomReturnType(functionType, datatype),
getReturnsBag(functionType));
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*/
private static int getId(String functionName) {
BagParameters params = (BagParameters) (paramMap.get(functionName));
if (params == null)
throw new IllegalArgumentException("unknown bag function: " + functionName);
return params.id;
}
/**
* Private helper that returns the argument type for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String getArgumentType(String functionName) {
return ((BagParameters) (paramMap.get(functionName))).arg;
}
/**
* Private helper that returns if the given standard function takes a bag. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static boolean getIsBag(String functionName) {
return ((BagParameters) (paramMap.get(functionName))).argIsBag;
}
/**
* Private helper that returns the argument count for the given standard function. Note that
* this doesn't check on the return value since the method always is called after getId, so we
* assume that the function is present.
*/
private static int getNumArgs(String functionName) {
return ((BagParameters) (paramMap.get(functionName))).params;
}
/**
* Private helper that returns the return type for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String getReturnType(String functionName) {
return ((BagParameters) (paramMap.get(functionName))).returnType;
}
/**
* Private helper that returns if the return type is a bag for the given standard function. Note
* that this doesn't check on the return value since the method always is called after getId, so
* we assume that the function is present.
*/
private static boolean getReturnsBag(String functionName) {
return ((BagParameters) (paramMap.get(functionName))).returnsBag;
}
/**
* Private helper used by the custom datatype constructor to figure out what the return type is.
* Note that this doesn't check on the return value since the method always is called after
* getId, so we assume that the function is present.
*/
private static String getCustomReturnType(String functionType, String datatype) {
String ret = ((BagParameters) (paramMap.get(functionType))).returnType;
if (ret == null)
return datatype;
else
return ret;
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
return supportedIds;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have real values, perform the requested operation.
AttributeValue attrResult = null;
switch (getFunctionId()) {
// *-one-and-only takes a single bag and returns a
// single value of baseType
case ID_BASE_ONE_AND_ONLY: {
BagAttribute bag = (BagAttribute) (argValues[0]);
if (bag.size() != 1)
return makeProcessingError(getFunctionName() + " expects "
+ "a bag that contains a single " + "element, got a bag with " + bag.size()
+ " elements");
attrResult = (AttributeValue) (bag.iterator().next());
break;
}
// *-size takes a single bag and returns an integer
case ID_BASE_BAG_SIZE: {
BagAttribute bag = (BagAttribute) (argValues[0]);
attrResult = new IntegerAttribute(bag.size());
break;
}
// *-bag takes any number of elements of baseType and
// returns a bag containing those elements
case ID_BASE_BAG: {
List<AttributeValue> argsList = Arrays.asList(argValues);
attrResult = new BagAttribute(getReturnType(), argsList);
break;
}
}
return new EvaluationResult(attrResult);
}
/**
* Private class that is used for mapping each function to it set of parameters.
*/
private static class BagParameters {
public int id;
public String arg;
public boolean argIsBag;
public int params;
public String returnType;
public boolean returnsBag;
public BagParameters(int id, String arg, boolean argIsBag, int params, String returnType,
boolean returnsBag) {
this.id = id;
this.arg = arg;
this.argIsBag = argIsBag;
this.params = params;
this.returnType = returnType;
this.returnsBag = returnsBag;
}
}
}
| 12,336 | 39.582237 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/FunctionBase.java | /*
* @(#)FunctionBase.java
*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.Indenter;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.ctx.Status;
import java.net.URI;
import java.net.URISyntaxException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* An abstract utility superclass for functions. Supplies several useful methods, making it easier
* to implement a <code>Function</code>. You can extend this class or implement
* <code>Function</code> directly, depending on your needs.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public abstract class FunctionBase implements Function {
/**
* The standard namespace where all XACML 1.0 spec-defined functions live
*/
public static final String FUNCTION_NS = "urn:oasis:names:tc:xacml:1.0:function:";
/**
* The standard namespace where all XACML 2.0 spec-defined functions live
*/
public static final String FUNCTION_NS_2 = "urn:oasis:names:tc:xacml:2.0:function:";
/**
* The standard namespace where all XACML 3.0 spec-defined functions live
*/
public static final String FUNCTION_NS_3 = "urn:oasis:names:tc:xacml:3.0:function:";
// A List used by makeProcessingError() to save some steps.
private static List processingErrList = null;
// the name of this function
private String functionName;
// the id used by this function
private int functionId;
// the return type of this function, and whether it's a bag
private String returnType;
private boolean returnsBag;
// flag that tells us which of the two constructors was used
private boolean singleType;
// parameter data if we're only using a single type
private String paramType;
private boolean paramIsBag;
private int numParams;
private int minParams;
// paramater data if we're using different types
private String[] paramTypes;
private boolean[] paramsAreBags;
/**
* Constructor that sets up the function as having some number of parameters all of the same
* given type. If <code>numParams</code> is -1, then the length is variable
*
* @param functionName the name of this function as used by the factory and any XACML policies
* @param functionId an optional identifier that can be used by your code for convenience
* @param paramType the type of all parameters to this function, as used by the factory and any
* XACML documents
* @param paramIsBag whether or not every parameter is actually a bag of values
* @param numParams the number of parameters required by this function, or -1 if any number are
* allowed
* @param returnType the type returned by this function, as used by the factory and any XACML
* documents
* @param returnsBag whether or not this function returns a bag of values
*/
public FunctionBase(String functionName, int functionId, String paramType, boolean paramIsBag,
int numParams, String returnType, boolean returnsBag) {
this(functionName, functionId, returnType, returnsBag);
singleType = true;
this.paramType = paramType;
this.paramIsBag = paramIsBag;
this.numParams = numParams;
this.minParams = 0;
}
/**
* Constructor that sets up the function as having some number of parameters all of the same
* given type. If <code>numParams</code> is -1, then the length is variable, and then
* <code>minParams</code> may be used to specify a minimum number of parameters. If
* <code>numParams</code> is not -1, then <code>minParams</code> is ignored.
*
* @param functionName the name of this function as used by the factory and any XACML policies
* @param functionId an optional identifier that can be used by your code for convenience
* @param paramType the type of all parameters to this function, as used by the factory and any
* XACML documents
* @param paramIsBag whether or not every parameter is actually a bag of values
* @param numParams the number of parameters required by this function, or -1 if any number are
* allowed
* @param minParams the minimum number of parameters required if <code>numParams</code> is -1
* @param returnType the type returned by this function, as used by the factory and any XACML
* documents
* @param returnsBag whether or not this function returns a bag of values
*/
public FunctionBase(String functionName, int functionId, String paramType, boolean paramIsBag,
int numParams, int minParams, String returnType, boolean returnsBag) {
this(functionName, functionId, returnType, returnsBag);
singleType = true;
this.paramType = paramType;
this.paramIsBag = paramIsBag;
this.numParams = numParams;
this.minParams = minParams;
}
/**
* Constructor that sets up the function as having different types for each given parameter.
*
* @param functionName the name of this function as used by the factory and any XACML policies
* @param functionId an optional identifier that can be used by your code for convenience
* @param paramTypes the type of each parameter, in order, required by this function, as used by
* the factory and any XACML documents
* @param paramIsBag whether or not each parameter is actually a bag of values
* @param returnType the type returned by this function, as used by the factory and any XACML
* documents
* @param returnsBag whether or not this function returns a bag of values
*/
public FunctionBase(String functionName, int functionId, String[] paramTypes,
boolean[] paramIsBag, String returnType, boolean returnsBag) {
this(functionName, functionId, returnType, returnsBag);
singleType = false;
this.paramTypes = paramTypes;
this.paramsAreBags = paramIsBag;
}
/**
* Constructor that sets up some basic values for functions that will take care of parameter
* checking on their own. If you use this constructor for your function class, then you must
* override the two check methods to make sure that parameters are correct.
*
* @param functionName the name of this function as used by the factory and any XACML policies
* @param functionId an optional identifier that can be used by your code for convenience
* @param returnType the type returned by this function, as used by the factory and any XACML
* documents
* @param returnsBag whether or not this function returns a bag of values
*/
public FunctionBase(String functionName, int functionId, String returnType, boolean returnsBag) {
this.functionName = functionName;
this.functionId = functionId;
this.returnType = returnType;
this.returnsBag = returnsBag;
}
/**
* Returns the full identifier of this function, as known by the factories.
*
* @return the function's identifier
*
* @throws IllegalArgumentException if the identifier isn't a valid URI
*/
public URI getIdentifier() {
// this is to get around the exception handling problems, but may
// change if this code changes to include exceptions from the
// constructors
try {
return new URI(functionName);
} catch (URISyntaxException use) {
throw new IllegalArgumentException("invalid URI");
}
}
/**
* Returns the name of the function to be handled by this particular object.
*
* @return the function name
*/
public String getFunctionName() {
return functionName;
}
/**
* Returns the Identifier of the function to be handled by this particular object.
*
* @return the function Id
*/
public int getFunctionId() {
return functionId;
}
/**
* Returns the same value as <code>getReturnType</code>. This is here to support the
* <code>Expression</code> interface.
*
* @return the return type
*/
public URI getType() {
return getReturnType();
}
/**
* Get the attribute type returned by this function.
*
* @return a <code>URI</code> indicating the attribute type returned by this function
*/
public URI getReturnType() {
try {
return new URI(returnType);
} catch (Exception e) {
return null;
}
}
/**
* Returns true if this function returns a bag of values.
*
* @return true if the function returns a bag, false otherwise
*/
public boolean returnsBag() {
return returnsBag;
}
/**
* Returns the return type for this particular object.
*
* @return the return type
*/
public String getReturnTypeAsString() {
return returnType;
}
/**
* Create an <code>EvaluationResult</code> that indicates a processing error with the specified
* message. This method may be useful to subclasses.
*
* @param message a description of the error (<code>null</code> if none)
* @return the desired <code>EvaluationResult</code>
*/
protected static EvaluationResult makeProcessingError(String message) {
// Build up the processing error Status.
if (processingErrList == null) {
String[] errStrings = { Status.STATUS_PROCESSING_ERROR };
processingErrList = Arrays.asList(errStrings);
}
Status errStatus = new Status(processingErrList, message);
EvaluationResult processingError = new EvaluationResult(errStatus);
return processingError;
}
/**
* Evaluates each of the parameters, in order, filling in the argument array with the resulting
* values. If any error occurs, this method returns the error, otherwise null is returned,
* signalling that evaluation was successful for all inputs, and the resulting argument list can
* be used.
*
* @param params a <code>List</code> of <code>Evaluatable</code> objects representing the
* parameters to evaluate
* @param context the representation of the request
* @param args an array as long as the params <code>List</code> that will, on return, contain
* the <code>AttributeValue</code>s generated from evaluating all parameters
*
* @return <code>null</code> if no errors were encountered, otherwise an
* <code>EvaluationResult</code> representing the error
*/
protected EvaluationResult evalArgs(List<Evaluatable> params, EvaluationCtx context, AttributeValue[] args) {
Iterator it = params.iterator();
int index = 0;
while (it.hasNext()) {
// get and evaluate the next parameter
Evaluatable eval = (Evaluatable) (it.next());
EvaluationResult result = eval.evaluate(context);
// If there was an error, pass it back...
if (result.indeterminate()){
return result;
}
// ...otherwise save it and keep going
args[index++] = result.getAttributeValue();
}
// if no error occurred then we got here, so we return no errors
return null;
}
/**
* Default handling of input checking. This does some simple checking based on the type of
* constructor used. If you need anything more complex, or if you used the simple constructor,
* then you must override this method.
*
* @param inputs a <code>List></code> of <code>Evaluatable</code>s
*
* @throws IllegalArgumentException if the inputs won't work
*/
public void checkInputs(List inputs) throws IllegalArgumentException {
// first off, see what kind of function we are
if (singleType) {
// first, check the length of the inputs, if appropriate
if (numParams != -1) {
if (inputs.size() != numParams)
throw new IllegalArgumentException("wrong number of args" + " to "
+ functionName);
} else {
if (inputs.size() < minParams)
throw new IllegalArgumentException("not enough args" + " to " + functionName);
}
// now, make sure everything is of the same, correct type
Iterator it = inputs.iterator();
while (it.hasNext()) {
Evaluatable eval = (Evaluatable) (it.next());
if ((!eval.getType().toString().equals(paramType))
|| (eval.returnsBag() != paramIsBag))
throw new IllegalArgumentException("illegal parameter");
}
} else {
// first, check the length of the inputs
if (paramTypes.length != inputs.size())
throw new IllegalArgumentException("wrong number of args" + " to " + functionName);
// now, make sure everything is of the same, correct type
Iterator it = inputs.iterator();
int i = 0;
while (it.hasNext()) {
Evaluatable eval = (Evaluatable) (it.next());
if ((!eval.getType().toString().equals(paramTypes[i]))
|| (eval.returnsBag() != paramsAreBags[i]))
throw new IllegalArgumentException("illegal parameter");
i++;
}
}
}
/**
* Default handling of input checking. This does some simple checking based on the type of
* constructor used. If you need anything more complex, or if you used the simple constructor,
* then you must override this method.
*
* @param inputs a <code>List></code> of <code>Evaluatable</code>s
*
* @throws IllegalArgumentException if the inputs won't work
*/
public void checkInputsNoBag(List inputs) throws IllegalArgumentException {
// first off, see what kind of function we are
if (singleType) {
// first check to see if we need bags
if (paramIsBag)
throw new IllegalArgumentException(functionName + "needs" + "bags on input");
// now check on the length
if (numParams != -1) {
if (inputs.size() != numParams)
throw new IllegalArgumentException("wrong number of args" + " to "
+ functionName);
} else {
if (inputs.size() < minParams)
throw new IllegalArgumentException("not enough args" + " to " + functionName);
}
// finally check param list
Iterator it = inputs.iterator();
while (it.hasNext()) {
Evaluatable eval = (Evaluatable) (it.next());
if (!eval.getType().toString().equals(paramType))
throw new IllegalArgumentException("illegal parameter");
}
} else {
// first, check the length of the inputs
if (paramTypes.length != inputs.size())
throw new IllegalArgumentException("wrong number of args" + " to " + functionName);
// now, make sure everything is of the same, correct type
Iterator it = inputs.iterator();
int i = 0;
while (it.hasNext()) {
Evaluatable eval = (Evaluatable) (it.next());
if ((!eval.getType().toString().equals(paramTypes[i])) || (paramsAreBags[i]))
throw new IllegalArgumentException("illegal parameter");
i++;
}
}
}
/**
* Encodes this <code>FunctionBase</code> into its XML form
*
* @return <code>String</code>
*/
public String encode() {
StringBuilder builder = new StringBuilder();
encode(builder);
return builder.toString();
}
/**
* Encodes this <code>FunctionBase</code> into its XML form and writes this out to the provided
* <code>StringBuilder<code>
*
* @param builder string stream into which the XML-encoded data is written
*/
public void encode(StringBuilder builder) {
builder.append("<Function FunctionId=\"").append(getFunctionName()).append("\"/>\n");
}
}
| 18,421 | 38.874459 | 113 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/FunctionProxy.java | /*
* @(#)FunctionProxy.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.w3c.dom.Node;
/**
* Used by abstract functions to define how new functions are created by the factory. Note that all
* functions using XPath are defined to be abstract functions, so they must be created using this
* interface.
*
* @since 1.0
* @author Seth Proctor
*/
public interface FunctionProxy {
/**
* Creates an instance of some abstract function. If the function being created is not using
* XPath, then the version parameter can be ignored, otherwise a value must be present and the
* version must be acceptable.
*
* @param root the DOM root of the apply statement containing the function
* @param xpathVersion the version specified in the contianing policy, or null if no version was
* specified
*
* @return the function
*
* @throws Exception if the underlying code experienced any error
*/
public Function getInstance(Node root, String xpathVersion) throws Exception;
}
| 2,836 | 41.984848 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/URLStringCatFunction.java | /*
* @(#)URLStringCatFunction.java
*
* Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AnyURIAttribute;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.StringAttribute;
import org.wso2.balana.ctx.Status;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Represents the XACML 2.0 url-string-concatenate function.
*
* @since 2.0
* @author Seth Proctor
*/
public class URLStringCatFunction extends FunctionBase {
/**
* Standard identifier for the url-string-concatenate function.
*/
public static final String NAME_URI_STRING_CONCATENATE = FUNCTION_NS_2
+ "uri-string-concatenate";
/**
* Creates an instance of this function.
*/
public URLStringCatFunction() {
super(NAME_URI_STRING_CONCATENATE, 0, AnyURIAttribute.identifier, false);
}
/**
* Checks the inputs of this function.
*
* @param inputs a <code>List></code> of <code>Evaluatable</code>s
*
* @throws IllegalArgumentException if the inputs won't work
*/
public void checkInputs(List inputs) throws IllegalArgumentException {
// scan the list to make sure nothing returns a bag
Iterator it = inputs.iterator();
while (it.hasNext()) {
if (((Expression) (it.next())).returnsBag())
throw new IllegalArgumentException(NAME_URI_STRING_CONCATENATE
+ " doesn't accept bags");
}
// nothing is a bag, so check using the no-bag method
checkInputsNoBag(inputs);
}
/**
* Checks the inputs of this function assuming no parameters are bags.
*
* @param inputs a <code>List></code> of <code>Evaluatable</code>s
*
* @throws IllegalArgumentException if the inputs won't work
*/
public void checkInputsNoBag(List inputs) throws IllegalArgumentException {
// make sure it's long enough
if (inputs.size() < 2)
throw new IllegalArgumentException("not enough args to " + NAME_URI_STRING_CONCATENATE);
// check that the parameters are of the correct types...
Iterator it = inputs.iterator();
// ...the first argument must be a URI...
if (!((Expression) (it.next())).getType().toString().equals(AnyURIAttribute.identifier))
throw new IllegalArgumentException("illegal parameter");
// ...and all following arguments must be strings
while (it.hasNext()) {
if (!((Expression) (it.next())).getType().toString().equals(StringAttribute.identifier))
throw new IllegalArgumentException("illegal parameter");
}
}
/**
* Evaluates the function given the input data. This function expects an
* <code>AnyURIAttribute</code> followed by one or more <code>StringAttribute</code>s, and
* returns an <code>AnyURIAttribute</code>.
*
* @param inputs the input agrument list
* @param context the representation of the request
*
* @return the result of evaluation
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// the first argument is always a URI
String str = ((AnyURIAttribute) (argValues[0])).getValue().toString();
// the remaining arguments are strings
StringBuffer buffer = new StringBuffer(str);
for (int i = 1; i < argValues.length; i++) {
buffer.append(((StringAttribute) (argValues[i])).getValue());
}
// finally, try to convert the string back to a URI
try {
return new EvaluationResult(new AnyURIAttribute(new URI(str)));
} catch (URISyntaxException use) {
List code = new ArrayList();
code.add(Status.STATUS_PROCESSING_ERROR);
String message = NAME_URI_STRING_CONCATENATE + " didn't produce" + " a valid URI: "
+ str;
return new EvaluationResult(new Status(code, message));
}
}
}
| 5,680 | 34.50625 | 91 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/MatchFunction.java | /*
* @(#)MatchFunction.java
*
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.XACMLConstants;
import org.wso2.balana.attr.AnyURIAttribute;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.BooleanAttribute;
import org.wso2.balana.attr.DNSNameAttribute;
import org.wso2.balana.attr.IPAddressAttribute;
import org.wso2.balana.attr.RFC822NameAttribute;
import org.wso2.balana.attr.StringAttribute;
import org.wso2.balana.attr.X500NameAttribute;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import javax.security.auth.x500.X500Principal;
/**
* Implements the standard matching and regular expression functions.
*
* @since 1.0
* @author Seth Proctor
* @author Yassir Elley
*/
public class MatchFunction extends FunctionBase {
/**
* Standard identifier for the regexp-string-match function.
*/
public static final String NAME_REGEXP_STRING_MATCH = FUNCTION_NS + "regexp-string-match";
/**
* Standard identifier for the x500Name-match function.
*/
public static final String NAME_X500NAME_MATCH = FUNCTION_NS + "x500Name-match";
/**
* Standard identifier for the rfc822Name-match function.
*/
public static final String NAME_RFC822NAME_MATCH = FUNCTION_NS + "rfc822Name-match";
/**
* Standard identifier for the string-regexp-match function. NOTE: this in the 1.0 namespace
* right now because of a bug in the XACML 2.0 specification, but this will be changed to the
* 2.0 namespace as soon as the errata is recognized.
*/
public static final String NAME_STRING_REGEXP_MATCH = FUNCTION_NS + "string-regexp-match";
/**
* Standard identifier for the anyURI-regexp-match function.
*/
public static final String NAME_ANYURI_REGEXP_MATCH = FUNCTION_NS_2 + "anyURI-regexp-match";
/**
* Standard identifier for the ipAddress-regexp-match function.
*/
public static final String NAME_IPADDRESS_REGEXP_MATCH = FUNCTION_NS_2
+ "ipAddress-regexp-match";
/**
* Standard identifier for the dnsName-regexp-match function.
*/
public static final String NAME_DNSNAME_REGEXP_MATCH = FUNCTION_NS_2 + "dnsName-regexp-match";
/**
* Standard identifier for the rfc822Name-regexp-match function.
*/
public static final String NAME_RFC822NAME_REGEXP_MATCH = FUNCTION_NS_2
+ "rfc822Name-regexp-match";
/**
* Standard identifier for the x500Name-regexp-match function.
*/
public static final String NAME_X500NAME_REGEXP_MATCH = FUNCTION_NS_2 + "x500Name-regexp-match";
// private identifiers for the supported functions
private static final int ID_REGEXP_STRING_MATCH = 0;
private static final int ID_X500NAME_MATCH = 1;
private static final int ID_RFC822NAME_MATCH = 2;
private static final int ID_STRING_REGEXP_MATCH = 3;
private static final int ID_ANYURI_REGEXP_MATCH = 4;
private static final int ID_IPADDRESS_REGEXP_MATCH = 5;
private static final int ID_DNSNAME_REGEXP_MATCH = 6;
private static final int ID_RFC822NAME_REGEXP_MATCH = 7;
private static final int ID_X500NAME_REGEXP_MATCH = 8;
// private mappings for the input arguments
private static final String regexpParams[] = { StringAttribute.identifier,
StringAttribute.identifier };
private static final String x500Params[] = { X500NameAttribute.identifier,
X500NameAttribute.identifier };
private static final String rfc822Params[] = { StringAttribute.identifier,
RFC822NameAttribute.identifier };
private static final String stringRegexpParams[] = { StringAttribute.identifier,
StringAttribute.identifier };
private static final String anyURIRegexpParams[] = { StringAttribute.identifier,
AnyURIAttribute.identifier };
private static final String ipAddressRegexpParams[] = { StringAttribute.identifier,
IPAddressAttribute.identifier };
private static final String dnsNameRegexpParams[] = { StringAttribute.identifier,
DNSNameAttribute.identifier };
private static final String rfc822NameRegexpParams[] = { StringAttribute.identifier,
RFC822NameAttribute.identifier };
private static final String x500NameRegexpParams[] = { StringAttribute.identifier,
X500NameAttribute.identifier };
// private mapping for bag input options
private static final boolean bagParams[] = { false, false };
/**
* Creates a new <code>MatchFunction</code> based on the given name.
*
* @param functionName the name of the standard match function, including the complete namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public MatchFunction(String functionName) {
super(functionName, getId(functionName), getArgumentTypes(functionName), bagParams,
BooleanAttribute.identifier, false);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*/
private static int getId(String functionName) {
if (functionName.equals(NAME_REGEXP_STRING_MATCH))
return ID_REGEXP_STRING_MATCH;
else if (functionName.equals(NAME_X500NAME_MATCH))
return ID_X500NAME_MATCH;
else if (functionName.equals(NAME_RFC822NAME_MATCH))
return ID_RFC822NAME_MATCH;
else if (functionName.equals(NAME_STRING_REGEXP_MATCH))
return ID_STRING_REGEXP_MATCH;
else if (functionName.equals(NAME_ANYURI_REGEXP_MATCH))
return ID_ANYURI_REGEXP_MATCH;
else if (functionName.equals(NAME_IPADDRESS_REGEXP_MATCH))
return ID_IPADDRESS_REGEXP_MATCH;
else if (functionName.equals(NAME_DNSNAME_REGEXP_MATCH))
return ID_DNSNAME_REGEXP_MATCH;
else if (functionName.equals(NAME_RFC822NAME_REGEXP_MATCH))
return ID_RFC822NAME_REGEXP_MATCH;
else if (functionName.equals(NAME_X500NAME_REGEXP_MATCH))
return ID_X500NAME_REGEXP_MATCH;
throw new IllegalArgumentException("unknown match function: " + functionName);
}
/**
* Private helper that returns the types used for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String[] getArgumentTypes(String functionName) {
if (functionName.equals(NAME_REGEXP_STRING_MATCH))
return regexpParams;
else if (functionName.equals(NAME_X500NAME_MATCH))
return x500Params;
else if (functionName.equals(NAME_RFC822NAME_MATCH))
return rfc822Params;
else if (functionName.equals(NAME_STRING_REGEXP_MATCH))
return stringRegexpParams;
else if (functionName.equals(NAME_ANYURI_REGEXP_MATCH))
return anyURIRegexpParams;
else if (functionName.equals(NAME_IPADDRESS_REGEXP_MATCH))
return ipAddressRegexpParams;
else if (functionName.equals(NAME_DNSNAME_REGEXP_MATCH))
return dnsNameRegexpParams;
else if (functionName.equals(NAME_RFC822NAME_REGEXP_MATCH))
return rfc822NameRegexpParams;
else if (functionName.equals(NAME_X500NAME_REGEXP_MATCH))
return x500NameRegexpParams;
return null;
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_REGEXP_STRING_MATCH);
set.add(NAME_X500NAME_MATCH);
set.add(NAME_RFC822NAME_MATCH);
set.add(NAME_STRING_REGEXP_MATCH);
set.add(NAME_ANYURI_REGEXP_MATCH);
set.add(NAME_IPADDRESS_REGEXP_MATCH);
set.add(NAME_DNSNAME_REGEXP_MATCH);
set.add(NAME_RFC822NAME_MATCH);
set.add(NAME_X500NAME_MATCH);
return set;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
// make sure we didn't get an error in processing the args
if (result != null)
return result;
// now that we're setup, we can do the matching operations
boolean boolResult = false;
switch (getFunctionId()) {
case ID_REGEXP_STRING_MATCH:
case ID_STRING_REGEXP_MATCH: {
// arg0 is a regular expression; arg1 is a general string
String arg0 = ((StringAttribute) (argValues[0])).getValue();
String arg1 = ((StringAttribute) (argValues[1])).getValue();
if (context.isSearching() && arg1.equals(XACMLConstants.ANY)) {
boolResult = true;
} else {
boolResult = regexpHelper(arg0, arg1);
}
break;
}
case ID_X500NAME_MATCH: {
X500Principal arg0 = ((X500NameAttribute) (argValues[0])).getValue();
X500Principal arg1 = ((X500NameAttribute) (argValues[1])).getValue();
boolResult = arg1.getName(X500Principal.CANONICAL).endsWith(
arg0.getName(X500Principal.CANONICAL));
break;
}
case ID_RFC822NAME_MATCH: {
String arg0 = ((StringAttribute) (argValues[0])).getValue();
String arg1 = ((RFC822NameAttribute) (argValues[1])).getValue();
if (arg0.indexOf('@') != -1) {
// this is case #1 : a whole address
String normalized = (new RFC822NameAttribute(arg0)).getValue();
boolResult = normalized.equals(arg1);
} else if (arg0.charAt(0) == '.') {
// this is case #3 : a sub-domain
boolResult = arg1.endsWith(arg0.toLowerCase());
} else {
// this is case #2 : any mailbox at a specific domain
String mailDomain = arg1.substring(arg1.indexOf('@') + 1);
boolResult = arg0.toLowerCase().equals(mailDomain);
}
break;
}
case ID_ANYURI_REGEXP_MATCH: {
// arg0 is a regular expression; arg1 is a general string
String arg0 = ((StringAttribute) (argValues[0])).getValue();
String arg1 = ((AnyURIAttribute) (argValues[1])).encode();
boolResult = regexpHelper(arg0, arg1);
break;
}
case ID_IPADDRESS_REGEXP_MATCH: {
// arg0 is a regular expression; arg1 is a general string
String arg0 = ((StringAttribute) (argValues[0])).getValue();
String arg1 = ((IPAddressAttribute) (argValues[1])).encode();
boolResult = regexpHelper(arg0, arg1);
break;
}
case ID_DNSNAME_REGEXP_MATCH: {
// arg0 is a regular expression; arg1 is a general string
String arg0 = ((StringAttribute) (argValues[0])).getValue();
String arg1 = ((DNSNameAttribute) (argValues[1])).encode();
boolResult = regexpHelper(arg0, arg1);
break;
}
case ID_RFC822NAME_REGEXP_MATCH: {
// arg0 is a regular expression; arg1 is a general string
String arg0 = ((StringAttribute) (argValues[0])).getValue();
String arg1 = ((RFC822NameAttribute) (argValues[1])).encode();
boolResult = regexpHelper(arg0, arg1);
break;
}
case ID_X500NAME_REGEXP_MATCH: {
// arg0 is a regular expression; arg1 is a general string
String arg0 = ((StringAttribute) (argValues[0])).getValue();
String arg1 = ((X500NameAttribute) (argValues[1])).encode();
boolResult = regexpHelper(arg0, arg1);
break;
}
}
// Return the result as a BooleanAttribute.
return EvaluationResult.getInstance(boolResult);
}
/**
*
*/
private boolean regexpHelper(String xpr, String str) {
// the regular expression syntax required by XACML differs
// from the syntax supported by java.util.regex.Pattern
// in several ways; the next several code blocks transform
// the XACML syntax into a semantically equivalent Pattern syntax
StringBuffer buf = new StringBuffer(xpr);
// in order to handle the requirement that the string is
// considered to match the pattern if any substring matches
// the pattern, we prepend ".*" and append ".*" to the reg exp,
// but only if there isn't an anchor (^ or $) in place
if (xpr.charAt(0) != '^')
buf = buf.insert(0, ".*");
if (xpr.charAt(xpr.length() - 1) != '$')
buf = buf.insert(buf.length(), ".*");
// in order to handle Unicode blocks, we replace all
// instances of "\p{Is" with "\p{In" in the reg exp
int idx = -1;
idx = buf.indexOf("\\p{Is", 0);
while (idx != -1) {
buf = buf.replace(idx, idx + 5, "\\p{In");
idx = buf.indexOf("\\p{Is", idx);
}
// in order to handle Unicode blocks, we replace all instances
// of "\P{Is" with "\P{In" in the reg exp
idx = -1;
idx = buf.indexOf("\\P{Is", 0);
while (idx != -1) {
buf = buf.replace(idx, idx + 5, "\\P{In");
idx = buf.indexOf("\\P{Is", idx);
}
// in order to handle character class subtraction, we
// replace all instances of "-[" with "&&[^" in the reg exp
idx = -1;
idx = buf.indexOf("-[", 0);
while (idx != -1) {
buf = buf.replace(idx, idx + 2, "&&[^");
idx = buf.indexOf("-[", idx);
}
return Pattern.matches(buf.toString(), str);
}
}
| 16,394 | 38.128878 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/MapFunctionProxy.java | /*
* @(#)MapFunctionProxy.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.w3c.dom.Node;
/**
* A basic proxy class that supports map, the only standard abstract function. This is useful if
* you're configuring the PDP at runtime.
*
* @since 1.2
* @author Seth Proctor
*/
public class MapFunctionProxy implements FunctionProxy {
/**
* Default constructor.
*/
public MapFunctionProxy() {
}
public Function getInstance(Node root, String xpathVersion) throws Exception {
return MapFunction.getInstance(root);
}
}
| 2,345 | 37.459016 | 96 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/AddFunction.java | /*
* @(#)AddFunction.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.DoubleAttribute;
import org.wso2.balana.attr.IntegerAttribute;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A class that implements all the *-add functions. It takes two or more operands of the appropriate
* type and returns the sum of the operands. If any of the operands is indeterminate, an
* indeterminate result is returned.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class AddFunction extends FunctionBase {
/**
* Standard identifier for the integer-add function.
*/
public static final String NAME_INTEGER_ADD = FUNCTION_NS + "integer-add";
/**
* Standard identifier for the double-add function.
*/
public static final String NAME_DOUBLE_ADD = FUNCTION_NS + "double-add";
// inernal identifiers for each of the supported functions
private static final int ID_INTEGER_ADD = 0;
private static final int ID_DOUBLE_ADD = 1;
/**
* Creates a new <code>AddFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public AddFunction(String functionName) {
super(functionName, getId(functionName), getArgumentType(functionName), false, -1, 2,
getArgumentType(functionName), false);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*/
private static int getId(String functionName) {
if (functionName.equals(NAME_INTEGER_ADD))
return ID_INTEGER_ADD;
else if (functionName.equals(NAME_DOUBLE_ADD))
return ID_DOUBLE_ADD;
else
throw new IllegalArgumentException("unknown add function " + functionName);
}
/**
* Private helper that returns the type used for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String getArgumentType(String functionName) {
if (functionName.equals(NAME_INTEGER_ADD))
return IntegerAttribute.identifier;
else
return DoubleAttribute.identifier;
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_INTEGER_ADD);
set.add(NAME_DOUBLE_ADD);
return set;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have real values, perform the add operation
switch (getFunctionId()) {
case ID_INTEGER_ADD: {
long sum = 0;
for (int index = 0; index < argValues.length; index++) {
long arg = ((IntegerAttribute) argValues[index]).getValue();
sum += arg;
}
result = new EvaluationResult(new IntegerAttribute(sum));
break;
}
case ID_DOUBLE_ADD: {
double sum = 0;
for (int index = 0; index < argValues.length; index++) {
double arg = ((DoubleAttribute) argValues[index]).getValue();
sum = sum + arg;
}
result = new EvaluationResult(new DoubleAttribute(sum));
break;
}
}
return result;
}
}
| 5,813 | 33.402367 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/FunctionTypeException.java | /*
* @(#)FunctionTypeException.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
/**
* Exception that gets thrown if one of the createFunction methods on the
* <code>FunctionFactory</code> was called, but the other method should have been called instead.
*
* @since 1.0
* @author Seth Proctor
*/
public class FunctionTypeException extends Exception {
/**
* Constructs a new <code>FunctionTypeException</code> with no message or cause.
*/
public FunctionTypeException() {
}
/**
* Constructs a new <code>FunctionTypeException</code> with a message, but no cause. The message
* is saved for later retrieval by the {@link java.lang#Throwable.getMessage()
* Throwable.getMessage()} method.
*
* @param message the detail message (<code>null</code> if nonexistent or unknown)
*/
public FunctionTypeException(String message) {
super(message);
}
/**
* Constructs a new <code>FunctionTypeException</code> with a cause, but no message. The cause
* is saved for later retrieval by the {@link java.lang#Throwable.getCause()
* Throwable.getCause()} method.
*
* @param cause the cause (<code>null</code> if nonexistent or unknown)
*/
public FunctionTypeException(Throwable cause) {
super(cause);
}
/**
* Constructs a new <code>FunctionTypeException</code> with a message and a cause. The message
* and cause are saved for later retrieval by the {@link java.lang#Throwable.getMessage()
* Throwable.getMessage()} and {@link java.lang#Throwable.getCause() Throwable.getCause()}
* methods.
*
* @param message the detail message (<code>null</code> if nonexistent or unknown)
* @param cause the cause (<code>null</code> if nonexistent or unknown)
*/
public FunctionTypeException(String message, Throwable cause) {
super(message, cause);
}
}
| 3,697 | 40.088889 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/ModFunction.java | /*
* @(#)ModFunction.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.IntegerAttribute;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A class that implements the integer-mod function. It takes two integer operands and returns the
* remainder. If either of the operands is indeterminate, an indeterminate result is returned.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class ModFunction extends FunctionBase {
/**
* Standard identifier for the integer-mod function.
*/
public static final String NAME_INTEGER_MOD = FUNCTION_NS + "integer-mod";
/**
* Creates a new <code>ModFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public ModFunction(String functionName) {
super(NAME_INTEGER_MOD, 0, IntegerAttribute.identifier, false, 2,
IntegerAttribute.identifier, false);
if (!functionName.equals(NAME_INTEGER_MOD))
throw new IllegalArgumentException("unknown mod function: " + functionName);
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_INTEGER_MOD);
return set;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have real values, perform the mod operation
long arg0 = ((IntegerAttribute) argValues[0]).getValue();
long arg1 = ((IntegerAttribute) argValues[1]).getValue();
return new EvaluationResult(new IntegerAttribute(arg0 % arg1));
}
}
| 4,508 | 38.208696 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/RoundFunction.java | /*
* @(#)RoundFunction.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.DoubleAttribute;
import org.wso2.balana.ctx.EvaluationCtx;
/**
* A class that implements the round function. It takes one double operand, rounds that value to an
* integer and returns that integer. If the operand is indeterminate, an indeterminate result is
* returned.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class RoundFunction extends FunctionBase {
/**
* Standard identifier for the round function.
*/
public static final String NAME_ROUND = FUNCTION_NS + "round";
/**
* Creates a new <code>RoundFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public RoundFunction(String functionName) {
super(NAME_ROUND, 0, DoubleAttribute.identifier, false, 1, DoubleAttribute.identifier,
false);
if (!functionName.equals(NAME_ROUND))
throw new IllegalArgumentException("unknown round function: " + functionName);
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_ROUND);
return set;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have real values, perform the round operation
double arg = ((DoubleAttribute) argValues[0]).getValue();
BigDecimal roundValue = new BigDecimal(arg);
return new EvaluationResult(new DoubleAttribute(roundValue.setScale(0, RoundingMode.HALF_EVEN).doubleValue()));
}
}
| 4,591 | 38.247863 | 119 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/StringNormalizeFunction.java | /*
* @(#)StringNormalizeFunction.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.StringAttribute;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A class that implements all the string conversion functions (string-normalize-space and
* string-normalize-to-lower-case). It takes string argument, normalizes that value, and returns the
* result. If the argument is indeterminate, an indeterminate result is returned.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class StringNormalizeFunction extends FunctionBase {
/**
* Standard identifier for the string-normalize-space function.
*/
public static final String NAME_STRING_NORMALIZE_SPACE = FUNCTION_NS + "string-normalize-space";
/**
* Standard identifier for the string-normalize-to-lower-case function.
*/
public static final String NAME_STRING_NORMALIZE_TO_LOWER_CASE = FUNCTION_NS
+ "string-normalize-to-lower-case";
// private identifiers for the supported functions
private static final int ID_STRING_NORMALIZE_SPACE = 0;
private static final int ID_STRING_NORMALIZE_TO_LOWER_CASE = 1;
/**
* Creates a new <code>StringNormalizeFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public StringNormalizeFunction(String functionName) {
super(functionName, getId(functionName), StringAttribute.identifier, false, 1,
StringAttribute.identifier, false);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*/
private static int getId(String functionName) {
if (functionName.equals(NAME_STRING_NORMALIZE_SPACE))
return ID_STRING_NORMALIZE_SPACE;
else if (functionName.equals(NAME_STRING_NORMALIZE_TO_LOWER_CASE))
return ID_STRING_NORMALIZE_TO_LOWER_CASE;
else
throw new IllegalArgumentException("unknown normalize function " + functionName);
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_STRING_NORMALIZE_SPACE);
set.add(NAME_STRING_NORMALIZE_TO_LOWER_CASE);
return set;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have real values, perform the numeric conversion
// operation in the manner appropriate for this function.
switch (getFunctionId()) {
case ID_STRING_NORMALIZE_SPACE: {
String str = ((StringAttribute) argValues[0]).getValue();
// Trim whitespace from start and end of string
int startIndex = 0;
int endIndex = str.length() - 1;
while ((startIndex <= endIndex) && Character.isWhitespace(str.charAt(startIndex)))
startIndex++;
while ((startIndex <= endIndex) && Character.isWhitespace(str.charAt(endIndex)))
endIndex--;
String strResult = str.substring(startIndex, endIndex + 1);
result = new EvaluationResult(new StringAttribute(strResult));
break;
}
case ID_STRING_NORMALIZE_TO_LOWER_CASE: {
String str = ((StringAttribute) argValues[0]).getValue();
// Convert string to lower case
String strResult = str.toLowerCase();
result = new EvaluationResult(new StringAttribute(strResult));
break;
}
}
return result;
}
}
| 6,452 | 39.33125 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/DateMathFunction.java | /*
* @(#)DateMathFunction.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.DateAttribute;
import org.wso2.balana.attr.DateTimeAttribute;
import org.wso2.balana.attr.DayTimeDurationAttribute;
import org.wso2.balana.attr.YearMonthDurationAttribute;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
/**
* A class that implements several of the date math functions. They all take two arguments. The
* first is a DateTimeAttribute or a DateAttribute (as the case may be) and the second is a
* DayTimeDurationAttribute or a YearMonthDurationAttribute (as the case may be). The function adds
* or subtracts the second argument to/from the first and returns a value of the same type as the
* first argument. If either of the arguments evaluates to indeterminate, an indeterminate result is
* returned.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class DateMathFunction extends FunctionBase {
/**
* Standard identifier for the dateTime-add-dayTimeDuration function.
*/
public static final String NAME_DATETIME_ADD_DAYTIMEDURATION = FUNCTION_NS
+ "dateTime-add-dayTimeDuration";
/**
* Standard identifier for the dateTime-subtract-dayTimeDuration function.
*/
public static final String NAME_DATETIME_SUBTRACT_DAYTIMEDURATION = FUNCTION_NS
+ "dateTime-subtract-dayTimeDuration";
/**
* Standard identifier for the dateTime-add-yearMonthDuration function.
*/
public static final String NAME_DATETIME_ADD_YEARMONTHDURATION = FUNCTION_NS
+ "dateTime-add-yearMonthDuration";
/**
* Standard identifier for the dateTime-subtract-yearMonthDuration function.
*/
public static final String NAME_DATETIME_SUBTRACT_YEARMONTHDURATION = FUNCTION_NS
+ "dateTime-subtract-yearMonthDuration";
/**
* Standard identifier for the date-add-yearMonthDuration function.
*/
public static final String NAME_DATE_ADD_YEARMONTHDURATION = FUNCTION_NS
+ "date-add-yearMonthDuration";
/**
* Standard identifier for the date-subtract-yearMonthDuration function.
*/
public static final String NAME_DATE_SUBTRACT_YEARMONTHDURATION = FUNCTION_NS
+ "date-subtract-yearMonthDuration";
// private identifiers for the supported functions
private static final int ID_DATETIME_ADD_DAYTIMEDURATION = 0;
private static final int ID_DATETIME_SUBTRACT_DAYTIMEDURATION = 1;
private static final int ID_DATETIME_ADD_YEARMONTHDURATION = 2;
private static final int ID_DATETIME_SUBTRACT_YEARMONTHDURATION = 3;
private static final int ID_DATE_ADD_YEARMONTHDURATION = 4;
private static final int ID_DATE_SUBTRACT_YEARMONTHDURATION = 5;
// Argument types
private static final String dateTimeDayTimeDurationArgTypes[] = { DateTimeAttribute.identifier,
DayTimeDurationAttribute.identifier };
private static final String dateTimeYearMonthDurationArgTypes[] = {
DateTimeAttribute.identifier, YearMonthDurationAttribute.identifier };
private static final String dateYearMonthDurationArgTypes[] = { DateAttribute.identifier,
YearMonthDurationAttribute.identifier };
// nothing here uses a bag
private static final boolean bagParams[] = { false, false };
// mapping from name to provide identifiers and argument types
private static HashMap<String,Integer> idMap;
private static HashMap<String,String[]> typeMap;
/**
* Static initializer to setup the id and type maps
*/
static {
idMap = new HashMap<String,Integer>();
idMap.put(NAME_DATETIME_ADD_DAYTIMEDURATION,
Integer.valueOf(ID_DATETIME_ADD_DAYTIMEDURATION));
idMap.put(NAME_DATETIME_SUBTRACT_DAYTIMEDURATION,
Integer.valueOf(ID_DATETIME_SUBTRACT_DAYTIMEDURATION));
idMap.put(NAME_DATETIME_ADD_YEARMONTHDURATION,
Integer.valueOf(ID_DATETIME_ADD_YEARMONTHDURATION));
idMap.put(NAME_DATETIME_SUBTRACT_YEARMONTHDURATION,
Integer.valueOf(ID_DATETIME_SUBTRACT_YEARMONTHDURATION));
idMap.put(NAME_DATE_ADD_YEARMONTHDURATION, Integer.valueOf(ID_DATE_ADD_YEARMONTHDURATION));
idMap.put(NAME_DATE_SUBTRACT_YEARMONTHDURATION,
Integer.valueOf(ID_DATE_SUBTRACT_YEARMONTHDURATION));
typeMap = new HashMap<String,String[]>();
typeMap.put(NAME_DATETIME_ADD_DAYTIMEDURATION, dateTimeDayTimeDurationArgTypes);
typeMap.put(NAME_DATETIME_SUBTRACT_DAYTIMEDURATION, dateTimeDayTimeDurationArgTypes);
typeMap.put(NAME_DATETIME_ADD_YEARMONTHDURATION, dateTimeYearMonthDurationArgTypes);
typeMap.put(NAME_DATETIME_SUBTRACT_YEARMONTHDURATION, dateTimeYearMonthDurationArgTypes);
typeMap.put(NAME_DATE_ADD_YEARMONTHDURATION, dateYearMonthDurationArgTypes);
typeMap.put(NAME_DATE_SUBTRACT_YEARMONTHDURATION, dateYearMonthDurationArgTypes);
};
/**
* Creates a new <code>DateMathFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public DateMathFunction(String functionName) {
super(functionName, getId(functionName), getArgumentTypes(functionName), bagParams,
getReturnType(functionName), false);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*/
private static int getId(String functionName) {
Integer i = (Integer) (idMap.get(functionName));
if (i == null)
throw new IllegalArgumentException("unknown datemath function " + functionName);
return i.intValue();
}
/**
* Private helper that returns the types used for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String[] getArgumentTypes(String functionName) {
return (String[]) (typeMap.get(functionName));
}
/**
* Private helper that returns the return type for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String getReturnType(String functionName) {
if (functionName.equals(NAME_DATE_ADD_YEARMONTHDURATION)
|| functionName.equals(NAME_DATE_SUBTRACT_YEARMONTHDURATION))
return DateAttribute.identifier;
else
return DateTimeAttribute.identifier;
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
return Collections.unmodifiableSet(idMap.keySet());
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have real values, perform the date math operation.
AttributeValue attrResult = null;
switch (getFunctionId()) {
// These two functions are basically the same except for sign.
// And they both need to deal with sign anyway, so they share
// their code.
case ID_DATETIME_ADD_DAYTIMEDURATION:
case ID_DATETIME_SUBTRACT_DAYTIMEDURATION: {
DateTimeAttribute dateTime = (DateTimeAttribute) argValues[0];
DayTimeDurationAttribute duration = (DayTimeDurationAttribute) argValues[1];
// Decide what sign goes with duration
int sign = 1;
if (getFunctionId() == ID_DATETIME_SUBTRACT_DAYTIMEDURATION)
sign = -sign;
if (duration.isNegative())
sign = -sign;
long millis = sign * duration.getTotalSeconds();
long nanoseconds = dateTime.getNanoseconds();
nanoseconds = nanoseconds + (sign * duration.getNanoseconds());
if (nanoseconds >= 1000000000) {
nanoseconds -= 1000000000;
millis += 1000;
}
if (nanoseconds < 0) {
nanoseconds += 1000000000;
millis -= 1000;
}
millis = millis + dateTime.getValue().getTime();
attrResult = new DateTimeAttribute(new Date(millis), (int) nanoseconds,
dateTime.getTimeZone(), dateTime.getDefaultedTimeZone());
break;
}
case ID_DATETIME_ADD_YEARMONTHDURATION:
case ID_DATETIME_SUBTRACT_YEARMONTHDURATION: {
DateTimeAttribute dateTime = (DateTimeAttribute) argValues[0];
YearMonthDurationAttribute duration = (YearMonthDurationAttribute) argValues[1];
// Decide what sign goes with duration
int sign = 1;
if (getFunctionId() == ID_DATETIME_SUBTRACT_YEARMONTHDURATION)
sign = -sign;
if (duration.isNegative())
sign = -sign;
// Add (or subtract) the years and months.
Calendar cal = new GregorianCalendar();
cal.setTime(dateTime.getValue());
long years = sign * duration.getYears();
long months = sign * duration.getMonths();
if ((years > Integer.MAX_VALUE) || (years < Integer.MIN_VALUE))
return makeProcessingError("years too large");
if ((months > Integer.MAX_VALUE) || (months < Integer.MIN_VALUE))
return makeProcessingError("months too large");
cal.add(Calendar.YEAR, (int) years);
cal.add(Calendar.MONTH, (int) months);
attrResult = new DateTimeAttribute(cal.getTime(), dateTime.getNanoseconds(),
dateTime.getTimeZone(), dateTime.getDefaultedTimeZone());
break;
}
case ID_DATE_ADD_YEARMONTHDURATION:
case ID_DATE_SUBTRACT_YEARMONTHDURATION: {
DateAttribute date = (DateAttribute) argValues[0];
YearMonthDurationAttribute duration = (YearMonthDurationAttribute) argValues[1];
// Decide what sign goes with duration
int sign = 1;
if (getFunctionId() == ID_DATE_SUBTRACT_YEARMONTHDURATION)
sign = -sign;
if (duration.isNegative())
sign = -sign;
// Add (or subtract) the years and months.
Calendar cal = new GregorianCalendar();
cal.setTime(date.getValue());
long years = sign * duration.getYears();
long months = sign * duration.getMonths();
if ((years > Integer.MAX_VALUE) || (years < Integer.MIN_VALUE))
return makeProcessingError("years too large");
if ((months > Integer.MAX_VALUE) || (months < Integer.MIN_VALUE))
return makeProcessingError("months too large");
cal.add(Calendar.YEAR, (int) years);
cal.add(Calendar.MONTH, (int) months);
attrResult = new DateAttribute(cal.getTime(), date.getTimeZone(),
date.getDefaultedTimeZone());
break;
}
}
return new EvaluationResult(attrResult);
}
}
| 12,745 | 37.741641 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/ComparisonFunction.java | /*
* @(#)ComparisonFunction.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.BooleanAttribute;
import org.wso2.balana.attr.DateAttribute;
import org.wso2.balana.attr.DateTimeAttribute;
import org.wso2.balana.attr.DoubleAttribute;
import org.wso2.balana.attr.IntegerAttribute;
import org.wso2.balana.attr.StringAttribute;
import org.wso2.balana.attr.TimeAttribute;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
/**
* A class that implements all of the standard comparison functions.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class ComparisonFunction extends FunctionBase {
/**
* Standard identifier for the integer-greater-than function.
*/
public static final String NAME_INTEGER_GREATER_THAN = FUNCTION_NS + "integer-greater-than";
/**
* Standard identifier for the integer-greater-than-or-equal function.
*/
public static final String NAME_INTEGER_GREATER_THAN_OR_EQUAL = FUNCTION_NS
+ "integer-greater-than-or-equal";
/**
* Standard identifier for the integer-less-than function.
*/
public static final String NAME_INTEGER_LESS_THAN = FUNCTION_NS + "integer-less-than";
/**
* Standard identifier for the integer-less-than-or-equal function.
*/
public static final String NAME_INTEGER_LESS_THAN_OR_EQUAL = FUNCTION_NS
+ "integer-less-than-or-equal";
/**
* Standard identifier for the double-greater-than function.
*/
public static final String NAME_DOUBLE_GREATER_THAN = FUNCTION_NS + "double-greater-than";
/**
* Standard identifier for the double-greater-than-or-equal function.
*/
public static final String NAME_DOUBLE_GREATER_THAN_OR_EQUAL = FUNCTION_NS
+ "double-greater-than-or-equal";
/**
* Standard identifier for the double-less-than function.
*/
public static final String NAME_DOUBLE_LESS_THAN = FUNCTION_NS + "double-less-than";
/**
* Standard identifier for the double-less-than-or-equal function.
*/
public static final String NAME_DOUBLE_LESS_THAN_OR_EQUAL = FUNCTION_NS
+ "double-less-than-or-equal";
/**
* Standard identifier for the string-greater-than function.
*/
public static final String NAME_STRING_GREATER_THAN = FUNCTION_NS + "string-greater-than";
/**
* Standard identifier for the string-greater-than-or-equal function.
*/
public static final String NAME_STRING_GREATER_THAN_OR_EQUAL = FUNCTION_NS
+ "string-greater-than-or-equal";
/**
* Standard identifier for the string-less-than function.
*/
public static final String NAME_STRING_LESS_THAN = FUNCTION_NS + "string-less-than";
/**
* Standard identifier for the string-less-than-or-equal function.
*/
public static final String NAME_STRING_LESS_THAN_OR_EQUAL = FUNCTION_NS
+ "string-less-than-or-equal";
/**
* Standard identifier for the time-greater-than function.
*/
public static final String NAME_TIME_GREATER_THAN = FUNCTION_NS + "time-greater-than";
/**
* Standard identifier for the time-greater-than-or-equal function.
*/
public static final String NAME_TIME_GREATER_THAN_OR_EQUAL = FUNCTION_NS
+ "time-greater-than-or-equal";
/**
* Standard identifier for the time-less-than function.
*/
public static final String NAME_TIME_LESS_THAN = FUNCTION_NS + "time-less-than";
/**
* Standard identifier for the time-less-than-or-equal function.
*/
public static final String NAME_TIME_LESS_THAN_OR_EQUAL = FUNCTION_NS
+ "time-less-than-or-equal";
/**
* Standard identifier for the dateTime-greater-than function.
*/
public static final String NAME_DATETIME_GREATER_THAN = FUNCTION_NS + "dateTime-greater-than";
/**
* Standard identifier for the dateTime-greater-than-or-equal function.
*/
public static final String NAME_DATETIME_GREATER_THAN_OR_EQUAL = FUNCTION_NS
+ "dateTime-greater-than-or-equal";
/**
* Standard identifier for the dateTime-less-than function.
*/
public static final String NAME_DATETIME_LESS_THAN = FUNCTION_NS + "dateTime-less-than";
/**
* Standard identifier for the dateTime-less-than-or-equal function.
*/
public static final String NAME_DATETIME_LESS_THAN_OR_EQUAL = FUNCTION_NS
+ "dateTime-less-than-or-equal";
/**
* Standard identifier for the date-greater-than function.
*/
public static final String NAME_DATE_GREATER_THAN = FUNCTION_NS + "date-greater-than";
/**
* Standard identifier for the date-greater-than-or-equal function.
*/
public static final String NAME_DATE_GREATER_THAN_OR_EQUAL = FUNCTION_NS
+ "date-greater-than-or-equal";
/**
* Standard identifier for the date-less-than function.
*/
public static final String NAME_DATE_LESS_THAN = FUNCTION_NS + "date-less-than";
/**
* Standard identifier for the date-less-than-or-equal function.
*/
public static final String NAME_DATE_LESS_THAN_OR_EQUAL = FUNCTION_NS
+ "date-less-than-or-equal";
// private identifiers for the supported functions
private static final int ID_INTEGER_GREATER_THAN = 0;
private static final int ID_INTEGER_GREATER_THAN_OR_EQUAL = 1;
private static final int ID_INTEGER_LESS_THAN = 2;
private static final int ID_INTEGER_LESS_THAN_OR_EQUAL = 3;
private static final int ID_DOUBLE_GREATER_THAN = 4;
private static final int ID_DOUBLE_GREATER_THAN_OR_EQUAL = 5;
private static final int ID_DOUBLE_LESS_THAN = 6;
private static final int ID_DOUBLE_LESS_THAN_OR_EQUAL = 7;
private static final int ID_STRING_GREATER_THAN = 8;
private static final int ID_STRING_GREATER_THAN_OR_EQUAL = 9;
private static final int ID_STRING_LESS_THAN = 10;
private static final int ID_STRING_LESS_THAN_OR_EQUAL = 11;
private static final int ID_TIME_GREATER_THAN = 12;
private static final int ID_TIME_GREATER_THAN_OR_EQUAL = 13;
private static final int ID_TIME_LESS_THAN = 14;
private static final int ID_TIME_LESS_THAN_OR_EQUAL = 15;
private static final int ID_DATE_GREATER_THAN = 16;
private static final int ID_DATE_GREATER_THAN_OR_EQUAL = 17;
private static final int ID_DATE_LESS_THAN = 18;
private static final int ID_DATE_LESS_THAN_OR_EQUAL = 19;
private static final int ID_DATETIME_GREATER_THAN = 20;
private static final int ID_DATETIME_GREATER_THAN_OR_EQUAL = 21;
private static final int ID_DATETIME_LESS_THAN = 22;
private static final int ID_DATETIME_LESS_THAN_OR_EQUAL = 23;
// mappings from name to private identifier and argument datatype
private static HashMap<String, Integer> idMap;
private static HashMap<String, String> typeMap;
/**
* Static initializer to setup the two maps.
*/
static {
idMap = new HashMap<String, Integer>();
idMap.put(NAME_INTEGER_GREATER_THAN, Integer.valueOf(ID_INTEGER_GREATER_THAN));
idMap.put(NAME_INTEGER_GREATER_THAN_OR_EQUAL,
Integer.valueOf(ID_INTEGER_GREATER_THAN_OR_EQUAL));
idMap.put(NAME_INTEGER_LESS_THAN, Integer.valueOf(ID_INTEGER_LESS_THAN));
idMap.put(NAME_INTEGER_LESS_THAN_OR_EQUAL, Integer.valueOf(ID_INTEGER_LESS_THAN_OR_EQUAL));
idMap.put(NAME_DOUBLE_GREATER_THAN, Integer.valueOf(ID_DOUBLE_GREATER_THAN));
idMap.put(NAME_DOUBLE_GREATER_THAN_OR_EQUAL,
Integer.valueOf(ID_DOUBLE_GREATER_THAN_OR_EQUAL));
idMap.put(NAME_DOUBLE_LESS_THAN, Integer.valueOf(ID_DOUBLE_LESS_THAN));
idMap.put(NAME_DOUBLE_LESS_THAN_OR_EQUAL, Integer.valueOf(ID_DOUBLE_LESS_THAN_OR_EQUAL));
idMap.put(NAME_STRING_GREATER_THAN, Integer.valueOf(ID_STRING_GREATER_THAN));
idMap.put(NAME_STRING_GREATER_THAN_OR_EQUAL,
Integer.valueOf(ID_STRING_GREATER_THAN_OR_EQUAL));
idMap.put(NAME_STRING_LESS_THAN, Integer.valueOf(ID_STRING_LESS_THAN));
idMap.put(NAME_STRING_LESS_THAN_OR_EQUAL, Integer.valueOf(ID_STRING_LESS_THAN_OR_EQUAL));
idMap.put(NAME_TIME_GREATER_THAN, Integer.valueOf(ID_TIME_GREATER_THAN));
idMap.put(NAME_TIME_GREATER_THAN_OR_EQUAL, Integer.valueOf(ID_TIME_GREATER_THAN_OR_EQUAL));
idMap.put(NAME_TIME_LESS_THAN, Integer.valueOf(ID_TIME_LESS_THAN));
idMap.put(NAME_TIME_LESS_THAN_OR_EQUAL, Integer.valueOf(ID_TIME_LESS_THAN_OR_EQUAL));
idMap.put(NAME_DATE_GREATER_THAN, Integer.valueOf(ID_DATE_GREATER_THAN));
idMap.put(NAME_DATE_GREATER_THAN_OR_EQUAL, Integer.valueOf(ID_DATE_GREATER_THAN_OR_EQUAL));
idMap.put(NAME_DATE_LESS_THAN, Integer.valueOf(ID_DATE_LESS_THAN));
idMap.put(NAME_DATE_LESS_THAN_OR_EQUAL, Integer.valueOf(ID_DATE_LESS_THAN_OR_EQUAL));
idMap.put(NAME_DATETIME_GREATER_THAN, Integer.valueOf(ID_DATETIME_GREATER_THAN));
idMap.put(NAME_DATETIME_GREATER_THAN_OR_EQUAL,
Integer.valueOf(ID_DATETIME_GREATER_THAN_OR_EQUAL));
idMap.put(NAME_DATETIME_LESS_THAN, Integer.valueOf(ID_DATETIME_LESS_THAN));
idMap.put(NAME_DATETIME_LESS_THAN_OR_EQUAL, Integer.valueOf(ID_DATETIME_LESS_THAN_OR_EQUAL));
typeMap = new HashMap<String, String>();
typeMap.put(NAME_INTEGER_GREATER_THAN, IntegerAttribute.identifier);
typeMap.put(NAME_INTEGER_GREATER_THAN_OR_EQUAL, IntegerAttribute.identifier);
typeMap.put(NAME_INTEGER_LESS_THAN, IntegerAttribute.identifier);
typeMap.put(NAME_INTEGER_LESS_THAN_OR_EQUAL, IntegerAttribute.identifier);
typeMap.put(NAME_DOUBLE_GREATER_THAN, DoubleAttribute.identifier);
typeMap.put(NAME_DOUBLE_GREATER_THAN_OR_EQUAL, DoubleAttribute.identifier);
typeMap.put(NAME_DOUBLE_LESS_THAN, DoubleAttribute.identifier);
typeMap.put(NAME_DOUBLE_LESS_THAN_OR_EQUAL, DoubleAttribute.identifier);
typeMap.put(NAME_STRING_GREATER_THAN, StringAttribute.identifier);
typeMap.put(NAME_STRING_GREATER_THAN_OR_EQUAL, StringAttribute.identifier);
typeMap.put(NAME_STRING_LESS_THAN, StringAttribute.identifier);
typeMap.put(NAME_STRING_LESS_THAN_OR_EQUAL, StringAttribute.identifier);
typeMap.put(NAME_TIME_GREATER_THAN, TimeAttribute.identifier);
typeMap.put(NAME_TIME_GREATER_THAN_OR_EQUAL, TimeAttribute.identifier);
typeMap.put(NAME_TIME_LESS_THAN, TimeAttribute.identifier);
typeMap.put(NAME_TIME_LESS_THAN_OR_EQUAL, TimeAttribute.identifier);
typeMap.put(NAME_DATETIME_GREATER_THAN, DateTimeAttribute.identifier);
typeMap.put(NAME_DATETIME_GREATER_THAN_OR_EQUAL, DateTimeAttribute.identifier);
typeMap.put(NAME_DATETIME_LESS_THAN, DateTimeAttribute.identifier);
typeMap.put(NAME_DATETIME_LESS_THAN_OR_EQUAL, DateTimeAttribute.identifier);
typeMap.put(NAME_DATE_GREATER_THAN, DateAttribute.identifier);
typeMap.put(NAME_DATE_GREATER_THAN_OR_EQUAL, DateAttribute.identifier);
typeMap.put(NAME_DATE_LESS_THAN, DateAttribute.identifier);
typeMap.put(NAME_DATE_LESS_THAN_OR_EQUAL, DateAttribute.identifier);
};
/**
* Creates a new <code>ComparisonFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function isn't known
*/
public ComparisonFunction(String functionName) {
super(functionName, getId(functionName), getArgumentType(functionName), false, 2,
BooleanAttribute.identifier, false);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*/
private static int getId(String functionName) {
Integer i = (Integer) (idMap.get(functionName));
if (i == null)
throw new IllegalArgumentException("unknown comparison function " + functionName);
return i.intValue();
}
/**
* Private helper that returns the type used for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String getArgumentType(String functionName) {
return (String) (typeMap.get(functionName));
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
return Collections.unmodifiableSet(idMap.keySet());
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have real values, perform the comparison operation
boolean boolResult = false;
switch (getFunctionId()) {
case ID_INTEGER_GREATER_THAN: {
long arg0 = ((IntegerAttribute) (argValues[0])).getValue();
long arg1 = ((IntegerAttribute) (argValues[1])).getValue();
boolResult = (arg0 > arg1);
break;
}
case ID_INTEGER_GREATER_THAN_OR_EQUAL: {
long arg0 = ((IntegerAttribute) (argValues[0])).getValue();
long arg1 = ((IntegerAttribute) (argValues[1])).getValue();
boolResult = (arg0 >= arg1);
break;
}
case ID_INTEGER_LESS_THAN: {
long arg0 = ((IntegerAttribute) (argValues[0])).getValue();
long arg1 = ((IntegerAttribute) (argValues[1])).getValue();
boolResult = (arg0 < arg1);
break;
}
case ID_INTEGER_LESS_THAN_OR_EQUAL: {
long arg0 = ((IntegerAttribute) (argValues[0])).getValue();
long arg1 = ((IntegerAttribute) (argValues[1])).getValue();
boolResult = (arg0 <= arg1);
break;
}
case ID_DOUBLE_GREATER_THAN: {
double arg0 = ((DoubleAttribute) (argValues[0])).getValue();
double arg1 = ((DoubleAttribute) (argValues[1])).getValue();
boolResult = (doubleCompare(arg0, arg1) > 0);
break;
}
case ID_DOUBLE_GREATER_THAN_OR_EQUAL: {
double arg0 = ((DoubleAttribute) (argValues[0])).getValue();
double arg1 = ((DoubleAttribute) (argValues[1])).getValue();
boolResult = (doubleCompare(arg0, arg1) >= 0);
break;
}
case ID_DOUBLE_LESS_THAN: {
double arg0 = ((DoubleAttribute) (argValues[0])).getValue();
double arg1 = ((DoubleAttribute) (argValues[1])).getValue();
boolResult = (doubleCompare(arg0, arg1) < 0);
break;
}
case ID_DOUBLE_LESS_THAN_OR_EQUAL: {
double arg0 = ((DoubleAttribute) (argValues[0])).getValue();
double arg1 = ((DoubleAttribute) (argValues[1])).getValue();
boolResult = (doubleCompare(arg0, arg1) <= 0);
break;
}
case ID_STRING_GREATER_THAN: {
String arg0 = ((StringAttribute) (argValues[0])).getValue();
String arg1 = ((StringAttribute) (argValues[1])).getValue();
boolResult = (arg0.compareTo(arg1) > 0);
break;
}
case ID_STRING_GREATER_THAN_OR_EQUAL: {
String arg0 = ((StringAttribute) (argValues[0])).getValue();
String arg1 = ((StringAttribute) (argValues[1])).getValue();
boolResult = (arg0.compareTo(arg1) >= 0);
break;
}
case ID_STRING_LESS_THAN: {
String arg0 = ((StringAttribute) (argValues[0])).getValue();
String arg1 = ((StringAttribute) (argValues[1])).getValue();
boolResult = (arg0.compareTo(arg1) < 0);
break;
}
case ID_STRING_LESS_THAN_OR_EQUAL: {
String arg0 = ((StringAttribute) (argValues[0])).getValue();
String arg1 = ((StringAttribute) (argValues[1])).getValue();
boolResult = (arg0.compareTo(arg1) <= 0);
break;
}
case ID_TIME_GREATER_THAN: {
TimeAttribute arg0 = (TimeAttribute) (argValues[0]);
TimeAttribute arg1 = (TimeAttribute) (argValues[1]);
boolResult = (dateCompare(arg0.getValue(), arg0.getNanoseconds(), arg1.getValue(),
arg1.getNanoseconds()) > 0);
break;
}
case ID_TIME_GREATER_THAN_OR_EQUAL: {
TimeAttribute arg0 = (TimeAttribute) (argValues[0]);
TimeAttribute arg1 = (TimeAttribute) (argValues[1]);
boolResult = (dateCompare(arg0.getValue(), arg0.getNanoseconds(), arg1.getValue(),
arg1.getNanoseconds()) >= 0);
break;
}
case ID_TIME_LESS_THAN: {
TimeAttribute arg0 = (TimeAttribute) (argValues[0]);
TimeAttribute arg1 = (TimeAttribute) (argValues[1]);
boolResult = (dateCompare(arg0.getValue(), arg0.getNanoseconds(), arg1.getValue(),
arg1.getNanoseconds()) < 0);
break;
}
case ID_TIME_LESS_THAN_OR_EQUAL: {
TimeAttribute arg0 = (TimeAttribute) (argValues[0]);
TimeAttribute arg1 = (TimeAttribute) (argValues[1]);
boolResult = (dateCompare(arg0.getValue(), arg0.getNanoseconds(), arg1.getValue(),
arg1.getNanoseconds()) <= 0);
break;
}
case ID_DATETIME_GREATER_THAN: {
DateTimeAttribute arg0 = (DateTimeAttribute) (argValues[0]);
DateTimeAttribute arg1 = (DateTimeAttribute) (argValues[1]);
boolResult = (dateCompare(arg0.getValue(), arg0.getNanoseconds(), arg1.getValue(),
arg1.getNanoseconds()) > 0);
break;
}
case ID_DATETIME_GREATER_THAN_OR_EQUAL: {
DateTimeAttribute arg0 = (DateTimeAttribute) (argValues[0]);
DateTimeAttribute arg1 = (DateTimeAttribute) (argValues[1]);
boolResult = (dateCompare(arg0.getValue(), arg0.getNanoseconds(), arg1.getValue(),
arg1.getNanoseconds()) >= 0);
break;
}
case ID_DATETIME_LESS_THAN: {
DateTimeAttribute arg0 = (DateTimeAttribute) (argValues[0]);
DateTimeAttribute arg1 = (DateTimeAttribute) (argValues[1]);
boolResult = (dateCompare(arg0.getValue(), arg0.getNanoseconds(), arg1.getValue(),
arg1.getNanoseconds()) < 0);
break;
}
case ID_DATETIME_LESS_THAN_OR_EQUAL: {
DateTimeAttribute arg0 = (DateTimeAttribute) (argValues[0]);
DateTimeAttribute arg1 = (DateTimeAttribute) (argValues[1]);
boolResult = (dateCompare(arg0.getValue(), arg0.getNanoseconds(), arg1.getValue(),
arg1.getNanoseconds()) <= 0);
break;
}
case ID_DATE_GREATER_THAN: {
Date arg0 = ((DateAttribute) (argValues[0])).getValue();
Date arg1 = ((DateAttribute) (argValues[1])).getValue();
boolResult = (arg0.compareTo(arg1) > 0);
break;
}
case ID_DATE_GREATER_THAN_OR_EQUAL: {
Date arg0 = ((DateAttribute) (argValues[0])).getValue();
Date arg1 = ((DateAttribute) (argValues[1])).getValue();
boolResult = (arg0.compareTo(arg1) >= 0);
break;
}
case ID_DATE_LESS_THAN: {
Date arg0 = ((DateAttribute) (argValues[0])).getValue();
Date arg1 = ((DateAttribute) (argValues[1])).getValue();
boolResult = (arg0.compareTo(arg1) < 0);
break;
}
case ID_DATE_LESS_THAN_OR_EQUAL: {
Date arg0 = ((DateAttribute) (argValues[0])).getValue();
Date arg1 = ((DateAttribute) (argValues[1])).getValue();
boolResult = (arg0.compareTo(arg1) <= 0);
break;
}
}
// Return the result as a BooleanAttribute.
return EvaluationResult.getInstance(boolResult);
}
/**
* Helper function that does a comparison of the two doubles using the rules of XMLSchema. Like
* all compare methods, this returns 0 if they're equal, a positive value if d1 > d2, and a
* negative value if d1 < d2.
*/
private int doubleCompare(double d1, double d2) {
// see if the numbers equal each other
if (d1 == d2) {
// these are not NaNs, and therefore we just need to check that
// that they're not zeros, which may have different signs
if (d1 != 0)
return 0;
// they're both zeros, so we compare strings to figure out
// the significance of any signs
return Double.toString(d1).compareTo(Double.toString(d2));
}
// see if d1 is NaN
if (Double.isNaN(d1)) {
// d1 is NaN, so see if d2 is as well
if (Double.isNaN(d2)) {
// they're both NaNs, so they're equal
return 0;
} else {
// d1 is always bigger than d2 since it's a NaN
return 1;
}
}
// see if d2 is NaN
if (Double.isNaN(d2)) {
// d2 is a NaN, though d1 isn't, so d2 is always bigger
return -1;
}
// if we got here then neither is a NaN, and the numbers aren't
// equal...given those facts, basic comparison works the same in
// java as it's defined in XMLSchema, so now we can do the simple
// comparison and return whatever we find
return ((d1 > d2) ? 1 : -1);
}
/**
* Helper function to compare two Date objects and their associated nanosecond values. Like all
* compare methods, this returns 0 if they're equal, a positive value if d1 > d2, and a negative
* value if d1 < d2.
*/
private int dateCompare(Date d1, int n1, Date d2, int n2) {
int compareResult = d1.compareTo(d2);
// we only worry about the nanosecond values if the Dates are equal
if (compareResult != 0)
return compareResult;
// see if there's any difference
if (n1 == n2)
return 0;
// there is some difference in the nanoseconds, and that's how
// we'll determine the comparison
return ((n1 > n2) ? 1 : -1);
}
}
| 22,540 | 33.731895 | 97 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/Apply.java | /*
* @(#)Apply.java
*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.*;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.wso2.balana.ctx.EvaluationCtx;
/**
* Represents the XACML ApplyType and ConditionType XML types.
* <p>
* Note well: as of 2.0, there is no longer a notion of a separate higher- order bag function.
* Instead, if needed, it is supplied as one of the <code>Expression</code>s in the parameter list.
* As such, when this <code>Apply</code> is evaluated, it no longer pre-evaluates all the parameters
* if a bag function is used. It is now up to the implementor of a higher-order function to do this.
* <p>
* Also, as of 2.0, the <code>Apply</code> is no longer used to represent a Condition, since the
* XACML 2.0 specification changed how Condition works. Instead, there is now a
* <code>Condition</code> class that represents both 1.x and 2.0 style Conditions.
*
* @since 1.0
* @author Seth Proctor
*/
public class Apply implements Evaluatable {
// the function used to evaluate the contents of the apply
private Function function;
// the paramaters to the function...ie, the contents of the apply
private List xprs;
/**
* Constructs an <code>Apply</code> instance.
*
* @param function the <code>Function</code> to use in evaluating the elements in the apply
* @param xprs the contents of the apply which will be the parameters to the function, each of
* which is an <code>Expression</code>
*
* @throws IllegalArgumentException if the input expressions don't match the signature of the
* function
*/
public Apply(Function function, List xprs) throws IllegalArgumentException {
// check that the given inputs work for the function
function.checkInputs(xprs);
// if everything checks out, then store the inputs
this.function = function;
this.xprs = Collections.unmodifiableList(new ArrayList(xprs));
}
/**
* Constructs an <code>Apply</code> instance.
*
* @deprecated As of 2.0 <code>Apply</code> is no longer used for Conditions, so the
* <code>isCondition</code> parameter is no longer needed. You should now use the 2
* parameter constructor. This constructor will be removed in a future release.
*
* @param function the <code>Function</code> to use in evaluating the elements in the apply
* @param xprs the contents of the apply which will be the parameters to the function, each of
* which is an <code>Expression</code>
* @param isCondition as of 2.0, this must always be false
*
* @throws IllegalArgumentException if the input expressions don't match the signature of the
* function or if <code>isCondition</code> is true
*/
public Apply(Function function, List xprs, boolean isCondition) throws IllegalArgumentException {
// make sure that no is using this constructor to create a Condition
if (isCondition)
throw new IllegalArgumentException("As of version 2.0 an Apply"
+ " may not represent a" + " Condition");
// check that the given inputs work for the function
function.checkInputs(xprs);
// if everything checks out, then store the inputs
this.function = function;
this.xprs = Collections.unmodifiableList(new ArrayList(xprs));
}
/**
* Returns an instance of an <code>Apply</code> based on the given DOM root node. This will
* actually return a special kind of <code>Apply</code>, namely an XML ConditionType, which is
* the root of the condition logic in a RuleType. A ConditionType is the same as an ApplyType
* except that it must use a FunctionId that returns a boolean value.
* <p>
* Note that as of 2.0 there is a separate <code>Condition</code> class used to support the
* different kinds of Conditions in XACML 1.x and 2.0. As such, the system no longer treats a
* ConditionType as a special kind of ApplyType. You may still use this method to get a 1.x
* style ConditionType, but you will need to convert it into a <code>Condition</code> to use it
* in evaluation. The preferred way to create a Condition is now through the
* <code>getInstance</code> method on <code>Condition</code>.
*
* @param root the DOM root of a ConditionType XML type
* @param xpathVersion the XPath version to use in any selectors or XPath functions, or null if
* this is unspecified (ie, not supplied in the defaults section of the policy)
* @param manager <code>VariableManager</code> used to connect references and definitions while
* parsing
*
* @throws ParsingException if this is not a valid ConditionType
*/
public static Apply getConditionInstance(Node root, String xpathVersion, VariableManager manager)
throws ParsingException {
return getInstance(root, FunctionFactory.getConditionInstance(), new PolicyMetaData(
XACMLConstants.XACML_1_0_IDENTIFIER, xpathVersion), manager);
}
/**
* Returns an instance of an <code>Apply</code> based on the given DOM root node. This will
* actually return a special kind of <code>Apply</code>, namely an XML ConditionType, which is
* the root of the condition logic in a RuleType. A ConditionType is the same as an ApplyType
* except that it must use a FunctionId that returns a boolean value.
*
* @deprecated As of 2.0 you should avoid using this method, since it does not provide a
* <code>Condition</code> instance and does not handle XACML 2.0 policies correctly.
* If you need a similar method you can use the new version that accepts a
* <code>VariableManager</code>. This will return an <code>Apply</code> instance for
* XACML 1.x policies.
*
* @param root the DOM root of a ConditionType XML type
* @param xpathVersion the XPath version to use in any selectors or XPath functions, or null if
* this is unspecified (ie, not supplied in the defaults section of the policy)
*
* @throws ParsingException if this is not a valid ConditionType
*/
public static Apply getConditionInstance(Node root, String xpathVersion)
throws ParsingException {
return getInstance(root, FunctionFactory.getConditionInstance(), new PolicyMetaData(
XACMLConstants.XACML_1_0_IDENTIFIER, xpathVersion), null);
}
/**
* Returns an instance of <code>Apply</code> based on the given DOM root.
*
* @param root the DOM root of an ApplyType XML type
* @param metaData the meta-data associated with the containing policy
* @param manager <code>VariableManager</code> used to connect references and definitions while
* parsing
*
* @throws ParsingException if this is not a valid ApplyType
*/
public static Apply getInstance(Node root, PolicyMetaData metaData, VariableManager manager)
throws ParsingException {
return getInstance(root, FunctionFactory.getGeneralInstance(), metaData, manager);
}
/**
* Returns an instance of <code>Apply</code> based on the given DOM root.
*
* @deprecated As of 2.0 you should avoid using this method, since it does not handle XACML 2.0
* policies correctly. If you need a similar method you can use the new version that
* accepts a <code>VariableManager</code>. This will return an <code>Apply</code>
* instance for XACML 1.x policies.
*
* @param root the DOM root of an ApplyType XML type
* @param xpathVersion the XPath version to use in any selectors or XPath functions, or null if
* this is unspecified (ie, not supplied in the defaults section of the policy)
*
* @throws ParsingException if this is not a valid ApplyType
*/
public static Apply getInstance(Node root, String xpathVersion) throws ParsingException {
return getInstance(root, FunctionFactory.getGeneralInstance(), new PolicyMetaData(
XACMLConstants.XACML_1_0_IDENTIFIER, xpathVersion), null);
}
/**
* This is a helper method that is called by the two getInstance methods. It takes a factory so
* we know that we're getting the right kind of function.
*/
private static Apply getInstance(Node root, FunctionFactory factory, PolicyMetaData metaData,
VariableManager manager) throws ParsingException {
Function function = ExpressionHandler.getFunction(root, metaData, factory);
List xprs = new ArrayList();
NodeList nodes = root.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Expression xpr = ExpressionHandler.parseExpression(nodes.item(i), metaData, manager);
if (xpr != null)
xprs.add(xpr);
}
return new Apply(function, xprs);
}
/**
* Returns the <code>Function</code> used by this <code>Apply</code>.
*
* @return the <code>Function</code>
*/
public Function getFunction() {
return function;
}
/**
* Returns the <code>List</code> of children for this <code>Apply</code>. The <code>List</code>
* contains <code>Expression</code>s. The list is unmodifiable, and may be empty.
*
* @return a <code>List</code> of <code>Expression</code>s
*/
public List getChildren() {
return xprs;
}
/**
* Returns whether or not this ApplyType is actually a ConditionType. As of 2.0 this always
* returns false;
*
* @deprecated As of 2.0 this method should not be used, since an <code>Apply</code> is never a
* Condition.
*
* @return false
*/
public boolean isCondition() {
return false;
}
/**
* Evaluates the apply object using the given function. This will in turn call evaluate on all
* the given parameters, some of which may be other <code>Apply</code> objects.
*
* @param context the representation of the request
*
* @return the result of trying to evaluate this apply object
*/
public EvaluationResult evaluate(EvaluationCtx context) {
// Note that prior to the 2.0 codebase, this method was much more
// complex, pre-evaluating the higher-order functions. Because this
// was never really the right behavior (there's no reason that a
// function can only be at the start of an Apply), we no longer make
// assumptions at this point, so the higher order functions are
// left to evaluate their own parameters.
return function.evaluate(xprs, context);
}
/**
* Returns the type of attribute that this object will return on a call to <code>evaluate</code>
* . In practice, this will always be the same as the result of calling
* <code>getReturnType</code> on the function used by this object.
*
* @return the type returned by <code>evaluate</code>
*/
public URI getType() {
return function.getReturnType();
}
/**
* Returns whether or not the <code>Function</code> will return a bag of values on evaluation.
*
* @return true if evaluation will return a bag of values, false otherwise
*/
public boolean returnsBag() {
return function.returnsBag();
}
/**
* Returns whether or not the <code>Function</code> will return a bag of values on evaluation.
*
*
* @deprecated As of 2.0, you should use the <code>returnsBag</code> method from the
* super-interface <code>Expression</code>.
*
* @return true if evaluation will return a bag of values, false otherwise
*/
public boolean evaluatesToBag() {
return function.returnsBag();
}
/**
* Encodes this <code>Apply</code> into its XML form
*
* @return <code>String</code>
*/
public String encode() {
StringBuilder builder = new StringBuilder();
encode(builder);
return builder.toString();
}
/**
* Encodes this <code>Apply</code> into its XML form and writes this out to the provided
* <code>StringBuilder<code>
*
* @param builder string stream into which the XML-encoded data is written
*/
public void encode(StringBuilder builder) {
builder.append("<Apply FunctionId=\"").append(function.getIdentifier()).append("\">\n");
Iterator it = xprs.iterator();
while (it.hasNext()) {
Expression xpr = (Expression) (it.next());
xpr.encode(builder);
}
builder.append("</Apply>\n");
}
}
| 14,881 | 42.136232 | 101 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/GeneralSetFunction.java | /*
* @(#)GeneralSetFunction.java
*
* Copyright 2004-2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.BagAttribute;
import java.util.*;
/**
* Specific <code>SetFunction</code> class that supports all of the general-purpose set functions:
* type-intersection and type-union.
*
* @since 1.2
* @author Seth Proctor
*/
public class GeneralSetFunction extends SetFunction {
// private identifiers for the supported functions
private static final int ID_BASE_INTERSECTION = 0;
private static final int ID_BASE_UNION = 1;
// mapping of function name to its associated id and parameter type
private static HashMap<String, Integer> idMap;
private static HashMap<String, String> typeMap;
/**
* Static initializer that sets up the parameter info for all the supported functions.
*/
static {
idMap = new HashMap<String, Integer>();
typeMap = new HashMap<String, String>();
idMap.put(NAME_BASE_INTERSECTION, Integer.valueOf(ID_BASE_INTERSECTION));
idMap.put(NAME_BASE_UNION, Integer.valueOf(ID_BASE_UNION));
for (int i = 0; i < baseTypes.length; i++) {
String baseName = FUNCTION_NS + simpleTypes[i];
String baseType = baseTypes[i];
idMap.put(baseName + NAME_BASE_INTERSECTION, Integer.valueOf(ID_BASE_INTERSECTION));
idMap.put(baseName + NAME_BASE_UNION, Integer.valueOf(ID_BASE_UNION));
typeMap.put(baseName + NAME_BASE_INTERSECTION, baseType);
typeMap.put(baseName + NAME_BASE_UNION, baseType);
}
for (int i = 0; i < baseTypes2.length; i++) {
String baseName = FUNCTION_NS_2 + simpleTypes2[i];
String baseType = baseTypes2[i];
idMap.put(baseName + NAME_BASE_INTERSECTION, Integer.valueOf(ID_BASE_INTERSECTION));
idMap.put(baseName + NAME_BASE_UNION, Integer.valueOf(ID_BASE_UNION));
typeMap.put(baseName + NAME_BASE_INTERSECTION, baseType);
typeMap.put(baseName + NAME_BASE_UNION, baseType);
}
};
/**
* Constructor that is used to create one of the general-purpose standard set functions. The
* name supplied must be one of the standard XACML functions supported by this class, including
* the full namespace, otherwise an exception is thrown. Look in <code>SetFunction</code> for
* details about the supported names.
*
* @param functionName the name of the function to create
*
* @throws IllegalArgumentException if the function is unknown
*/
public GeneralSetFunction(String functionName) {
super(functionName, getId(functionName), getArgumentType(functionName),
getArgumentType(functionName), true);
}
/**
* Constructor that is used to create instances of general-purpose set functions for new
* (non-standard) datatypes. This is equivalent to using the <code>getInstance</code> methods in
* <code>SetFunction</code> and is generally only used by the run-time configuration code.
*
* @param functionName the name of the new function
* @param datatype the full identifier for the supported datatype
* @param functionType which kind of Set function, based on the <code>NAME_BASE_*</code> fields
*/
public GeneralSetFunction(String functionName, String datatype, String functionType) {
super(functionName, getId(functionType), datatype, datatype, true);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*/
private static int getId(String functionName) {
Integer id = (Integer) (idMap.get(functionName));
if (id == null)
throw new IllegalArgumentException("unknown set function " + functionName);
return id.intValue();
}
/**
* Private helper that returns the argument type for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String getArgumentType(String functionName) {
return (String) (typeMap.get(functionName));
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
return Collections.unmodifiableSet(idMap.keySet());
}
/**
* Evaluates the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult evalResult = evalArgs(inputs, context, argValues);
if (evalResult != null)
return evalResult;
// setup the two bags we'll be using
BagAttribute[] bags = new BagAttribute[2];
bags[0] = (BagAttribute) (argValues[0]);
bags[1] = (BagAttribute) (argValues[1]);
AttributeValue result = null;
Set<AttributeValue> set = new HashSet<AttributeValue>();
switch (getFunctionId()) {
// *-intersection takes two bags of the same type and returns
// a bag of that type
case ID_BASE_INTERSECTION:
// create a bag with the common elements of both inputs, removing
// all duplicate values
Iterator it = bags[0].iterator();
// find all the things in bags[0] that are also in bags[1]
while (it.hasNext()) {
AttributeValue value = (AttributeValue) (it.next());
if (bags[1].contains(value)) {
// sets won't allow duplicates, so this addition is ok
set.add(value);
}
}
result = new BagAttribute(bags[0].getType(), Arrays.asList(set.toArray(new AttributeValue[set.size()])));
break;
// *-union takes two bags of the same type and returns a bag of
// that type
case ID_BASE_UNION:
// create a bag with all the elements from both inputs, removing
// all duplicate values
Iterator it0 = bags[0].iterator();
while (it0.hasNext()) {
// first off, add all elements from the first bag...the set
// will ignore all duplicates
set.add((AttributeValue)it0.next());
}
Iterator it1 = bags[1].iterator();
while (it1.hasNext()) {
// now add all the elements from the second bag...again, all
// duplicates will be ignored by the set
set.add((AttributeValue)it1.next());
}
result = new BagAttribute(bags[0].getType(), Arrays.asList(set.toArray(new AttributeValue[set.size()])));
break;
}
return new EvaluationResult(result);
}
}
| 8,457 | 35.773913 | 109 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/LogicalFunction.java | /*
* @(#)LogicalFunction.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.BooleanAttribute;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* A class that implements the logical functions "or" and "and". These functions take any number of
* boolean arguments and evaluate them one at a time, starting with the first argument. As soon as
* the result of the function can be determined, evaluation stops and that result is returned.
* During this process, if any argument evaluates to indeterminate, an indeterminate result is
* returned.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class LogicalFunction extends FunctionBase {
/**
* Standard identifier for the or function.
*/
public static final String NAME_OR = FUNCTION_NS + "or";
/**
* Standard identifier for the and function.
*/
public static final String NAME_AND = FUNCTION_NS + "and";
// internal identifiers for each of the supported functions
private static final int ID_OR = 0;
private static final int ID_AND = 1;
/**
* Creates a new <code>LogicalFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the functionName is unknown
*/
public LogicalFunction(String functionName) {
super(functionName, getId(functionName), BooleanAttribute.identifier, false, -1,
BooleanAttribute.identifier, false);
}
/**
* Private helper that looks up the private id based on the function name.
*/
private static int getId(String functionName) {
if (functionName.equals(NAME_OR))
return ID_OR;
else if (functionName.equals(NAME_AND))
return ID_AND;
else
throw new IllegalArgumentException("unknown logical function: " + functionName);
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_OR);
set.add(NAME_AND);
return set;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments one by one. As soon as we can
// return a result, do so. Return Indeterminate if any argument
// evaluated is indeterminate.
Iterator it = inputs.iterator();
while (it.hasNext()) {
Evaluatable eval = (Evaluatable) (it.next());
// Evaluate the argument
EvaluationResult result = eval.evaluate(context);
if (result.indeterminate())
return result;
AttributeValue value = result.getAttributeValue();
boolean argBooleanValue = ((BooleanAttribute) value).getValue();
switch (getFunctionId()) {
case ID_OR:
if (argBooleanValue)
return EvaluationResult.getTrueInstance();
break;
case ID_AND:
if (!argBooleanValue)
return EvaluationResult.getFalseInstance();
break;
}
}
if (getFunctionId() == ID_OR)
return EvaluationResult.getFalseInstance();
else
return EvaluationResult.getTrueInstance();
}
}
| 5,940 | 36.601266 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/FunctionFactory.java | /*
* @(#)FunctionFactory.java
*
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ParsingException;
import org.wso2.balana.PolicyMetaData;
import org.wso2.balana.UnknownIdentifierException;
import java.net.URI;
import java.util.HashMap;
import java.util.Set;
import org.w3c.dom.Node;
import org.wso2.balana.XACMLConstants;
/**
* Factory used to create all functions. There are three kinds of factories: general, condition, and
* target. These provide functions that can be used anywhere, only in a condition's root and only in
* a target (respectively).
* <p>
* Note that all functions, except for abstract functions, are singletons, so any instance that is
* added to a factory will be the same one returned from the create methods. This is done because
* most functions don't have state, so there is no need to have more than one, or to spend the time
* creating multiple instances that all do the same thing.
*
* @since 1.0
* @author Marco Barreno
* @author Seth Proctor
*/
public abstract class FunctionFactory {
// the proxies used to get the default factorys
private static FunctionFactoryProxy defaultFactoryProxy;
// the map of registered factories
private static HashMap registeredFactories;
/**
* static intialiazer that sets up the default factory proxies and registers the standard
* namespaces
*/
static {
FunctionFactoryProxy proxy = new FunctionFactoryProxy() {
public FunctionFactory getTargetFactory() {
return StandardFunctionFactory.getTargetFactory();
}
public FunctionFactory getConditionFactory() {
return StandardFunctionFactory.getConditionFactory();
}
public FunctionFactory getGeneralFactory() {
return StandardFunctionFactory.getGeneralFactory();
}
};
registeredFactories = new HashMap();
registeredFactories.put(XACMLConstants.XACML_1_0_IDENTIFIER, proxy);
registeredFactories.put(XACMLConstants.XACML_2_0_IDENTIFIER, proxy);
registeredFactories.put(XACMLConstants.XACML_3_0_IDENTIFIER, proxy);
defaultFactoryProxy = proxy;
};
/**
* Default constructor. Used only by subclasses.
*/
protected FunctionFactory() {
}
/**
* Returns the default FunctionFactory that will only provide those functions that are usable in
* Target matching.
*
* @return a <code>FunctionFactory</code> for target functions
*/
public static final FunctionFactory getTargetInstance() {
return defaultFactoryProxy.getTargetFactory();
}
/**
* Returns a factory based on the given identifier. You may register as many factories as you
* like, and then retrieve them through this interface, but a factory may only be registered
* once using a given identifier. By default, the standard XACML 1.0 and 2.0 identifiers are
* regsietered to provide the standard factory.
*
* @param identifier the identifier for a factory
*
* @return a <code>FunctionFactory</code> that supports Target functions
*
* @throws UnknownIdentifierException if the given identifier isn't registered
*/
public static final FunctionFactory getTargetInstance(String identifier)
throws UnknownIdentifierException {
return getRegisteredProxy(identifier).getTargetFactory();
}
/**
* Returns the default FuntionFactory that will only provide those functions that are usable in
* the root of the Condition. These Functions are a superset of the Target functions.
*
* @return a <code>FunctionFactory</code> for condition functions
*/
public static final FunctionFactory getConditionInstance() {
return defaultFactoryProxy.getConditionFactory();
}
/**
* Returns a factory based on the given identifier. You may register as many factories as you
* like, and then retrieve them through this interface, but a factory may only be registered
* once using a given identifier. By default, the standard XACML 1.0 and 2.0 identifiers are
* regsietered to provide the standard factory.
*
* @param identifier the identifier for a factory
*
* @return a <code>FunctionFactory</code> that supports Condition functions
*
* @throws UnknownIdentifierException if the given identifier isn't registered
*/
public static final FunctionFactory getConditionInstance(String identifier)
throws UnknownIdentifierException {
return getRegisteredProxy(identifier).getConditionFactory();
}
/**
* Returns the default FunctionFactory that provides access to all the functions. These
* Functions are a superset of the Condition functions.
*
* @return a <code>FunctionFactory</code> for all functions
*/
public static final FunctionFactory getGeneralInstance() {
return defaultFactoryProxy.getGeneralFactory();
}
/**
* Returns a factory based on the given identifier. You may register as many factories as you
* like, and then retrieve them through this interface, but a factory may only be registered
* once using a given identifier. By default, the standard XACML 1.0 and 2.0 identifiers are
* regsietered to provide the standard factory.
*
* @param identifier the identifier for a factory
*
* @return a <code>FunctionFactory</code> that supports General functions
*
* @throws UnknownIdentifierException if the given identifier isn't registered
*/
public static final FunctionFactory getGeneralInstance(String identifier)
throws UnknownIdentifierException {
return getRegisteredProxy(identifier).getGeneralFactory();
}
/**
* Returns the default FunctionFactoryProxy that provides access to all the functions.
*
* @return a <code>FunctionFactoryProxy</code> for all functions
*/
public static final FunctionFactoryProxy getInstance() {
return defaultFactoryProxy;
}
/**
* Returns a factory based on the given identifier. You may register as many factories as you
* like, and then retrieve them through this interface, but a factory may only be registered
* once using a given identifier. By default, the standard XACML 1.0 and 2.0 identifiers are
* regsietered to provide the standard factory.
*
* @param identifier the identifier for a factory
*
* @return a <code>FunctionFactoryProxy</code>
*
* @throws UnknownIdentifierException if the given identifier isn't registered
*/
public static final FunctionFactoryProxy getInstance(String identifier)
throws UnknownIdentifierException {
return getRegisteredProxy(identifier);
}
/**
* Private helper that resolves the proxy for the given identifier, or throws an exception if no
* proxy is registered for that identifier.
*/
private static FunctionFactoryProxy getRegisteredProxy(String identifier)
throws UnknownIdentifierException {
FunctionFactoryProxy proxy = (FunctionFactoryProxy) (registeredFactories.get(identifier));
if (proxy == null)
throw new UnknownIdentifierException("Uknown FunctionFactory " + "identifier: "
+ identifier);
return proxy;
}
/**
* Sets the default factory. This does not register the factory proxy as an identifiable
* factory.
*
* @param proxy the <code>FunctionFactoryProxy</code> to set as the new default factory proxy
*/
public static final void setDefaultFactory(FunctionFactoryProxy proxy) {
defaultFactoryProxy = proxy;
}
/**
* Registers the given factory proxy with the given identifier. If the identifier is already
* used, then this throws an exception. If the identifier is not already used, then it will
* always be bound to the given proxy.
*
* @param identifier the identifier for the proxy
* @param proxy the <code>FunctionFactoryProxy</code> to register with the given identifier
*
* @throws IllegalArgumentException if the identifier is already used
*/
public static final void registerFactory(String identifier, FunctionFactoryProxy proxy)
throws IllegalArgumentException {
synchronized (registeredFactories) {
if (registeredFactories.containsKey(identifier))
throw new IllegalArgumentException("Identifier is already " + "registered as "
+ "FunctionFactory: " + identifier);
registeredFactories.put(identifier, proxy);
}
}
/**
* Adds the function to the factory. Most functions have no state, so the singleton model used
* here is typically desireable. The factory will not enforce the requirement that a Target or
* Condition matching function must be boolean.
*
* @param function the <code>Function</code> to add to the factory
*
* @throws IllegalArgumentException if the function's identifier is already used
*/
public abstract void addFunction(Function function);
/**
* Adds the abstract function proxy to the factory. This is used for those functions which have
* state, or change behavior (for instance the standard map function, which changes its return
* type based on how it is used).
*
* @param proxy the <code>FunctionProxy</code> to add to the factory
* @param identity the function's identifier
*
* @throws IllegalArgumentException if the function's identifier is already used
*/
public abstract void addAbstractFunction(FunctionProxy proxy, URI identity);
/**
* Adds a target function.
*
* @deprecated As of version 1.2, replaced by {@link #addFunction(Function)}. The new factory
* system requires you to get a factory instance and then call the non-static
* methods on that factory. The static versions of these methods have been left in
* for now, but are slower and will be removed in a future version.
*
* @param function the function to add
*
* @throws IllegalArgumentException if the name is already in use
*/
public static void addTargetFunction(Function function) {
getTargetInstance().addFunction(function);
}
/**
* Adds an abstract target function.
*
* @deprecated As of version 1.2, replaced by {@link #addAbstractFunction(FunctionProxy,URI)}.
* The new factory system requires you to get a factory instance and then call the
* non-static methods on that factory. The static versions of these methods have
* been left in for now, but are slower and will be removed in a future version.
*
* @param proxy the function proxy to add
* @param identity the name of the function
*
* @throws IllegalArgumentException if the name is already in use
*/
public static void addAbstractTargetFunction(FunctionProxy proxy, URI identity) {
getTargetInstance().addAbstractFunction(proxy, identity);
}
/**
* Adds a condition function.
*
* @deprecated As of version 1.2, replaced by {@link #addFunction(Function)}. The new factory
* system requires you to get a factory instance and then call the non-static
* methods on that factory. The static versions of these methods have been left in
* for now, but are slower and will be removed in a future version.
*
* @param function the function to add
*
* @throws IllegalArgumentException if the name is already in use
*/
public static void addConditionFunction(Function function) {
getConditionInstance().addFunction(function);
}
/**
* Adds an abstract condition function.
*
* @deprecated As of version 1.2, replaced by {@link #addAbstractFunction(FunctionProxy,URI)}.
* The new factory system requires you to get a factory instance and then call the
* non-static methods on that factory. The static versions of these methods have
* been left in for now, but are slower and will be removed in a future version.
*
* @param proxy the function proxy to add
* @param identity the name of the function
*
* @throws IllegalArgumentException if the name is already in use
*/
public static void addAbstractConditionFunction(FunctionProxy proxy, URI identity) {
getConditionInstance().addAbstractFunction(proxy, identity);
}
/**
* Adds a general function.
*
* @deprecated As of version 1.2, replaced by {@link #addFunction(Function)}. The new factory
* system requires you to get a factory instance and then call the non-static
* methods on that factory. The static versions of these methods have been left in
* for now, but are slower and will be removed in a future version.
*
* @param function the function to add
*
* @throws IllegalArgumentException if the name is already in use
*/
public static void addGeneralFunction(Function function) {
getGeneralInstance().addFunction(function);
}
/**
* Adds an abstract general function.
*
* @deprecated As of version 1.2, replaced by {@link #addAbstractFunction(FunctionProxy,URI)}.
* The new factory system requires you to get a factory instance and then call the
* non-static methods on that factory. The static versions of these methods have
* been left in for now, but are slower and will be removed in a future version.
*
* @param proxy the function proxy to add
* @param identity the name of the function
*
* @throws IllegalArgumentException if the name is already in use
*/
public static void addAbstractGeneralFunction(FunctionProxy proxy, URI identity) {
getGeneralInstance().addAbstractFunction(proxy, identity);
}
/**
* Returns the function identifiers supported by this factory.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public abstract Set getSupportedFunctions();
/**
* Tries to get an instance of the specified function.
*
* @param identity the name of the function
*
* @throws UnknownIdentifierException if the name isn't known
* @throws FunctionTypeException if the name is known to map to an abstract function, and should
* therefore be created through createAbstractFunction
*/
public abstract Function createFunction(URI identity) throws UnknownIdentifierException,
FunctionTypeException;
/**
* Tries to get an instance of the specified function.
*
* @param identity the name of the function
*
* @throws UnknownIdentifierException if the name isn't known
* @throws FunctionTypeException if the name is known to map to an abstract function, and should
* therefore be created through createAbstractFunction
*/
public abstract Function createFunction(String identity) throws UnknownIdentifierException,
FunctionTypeException;
/**
* Tries to get an instance of the specified abstract function.
*
* @param identity the name of the function
* @param root the DOM root containing info used to create the function
*
* @throws UnknownIdentifierException if the name isn't known
* @throws FunctionTypeException if the name is known to map to a concrete function, and should
* therefore be created through createFunction
* @throws ParsingException if the function can't be created with the given inputs
*/
public abstract Function createAbstractFunction(URI identity, Node root)
throws UnknownIdentifierException, ParsingException, FunctionTypeException;
/**
* Tries to get an instance of the specified abstract function.
*
* @param identity the name of the function
* @param root the DOM root containing info used to create the function
* @param xpathVersion the version specified in the contianing policy, or null if no version was
* specified
*
* @throws UnknownIdentifierException if the name isn't known
* @throws FunctionTypeException if the name is known to map to a concrete function, and should
* therefore be created through createFunction
* @throws ParsingException if the function can't be created with the given inputs
*/
public abstract Function createAbstractFunction(URI identity, Node root, String xpathVersion)
throws UnknownIdentifierException, ParsingException, FunctionTypeException;
/**
* Tries to get an instance of the specified abstract function.
*
* @param identity the name of the function
* @param root the DOM root containing info used to create the function
*
* @throws UnknownIdentifierException if the name isn't known
* @throws FunctionTypeException if the name is known to map to a concrete function, and should
* therefore be created through createFunction
* @throws ParsingException if the function can't be created with the given inputs
*/
public abstract Function createAbstractFunction(String identity, Node root)
throws UnknownIdentifierException, ParsingException, FunctionTypeException;
/**
* Tries to get an instance of the specified abstract function.
*
* @param identity the name of the function
* @param root the DOM root containing info used to create the function
* @param xpathVersion the version specified in the contianing policy, or null if no version was
* specified
*
* @throws UnknownIdentifierException if the name isn't known
* @throws FunctionTypeException if the name is known to map to a concrete function, and should
* therefore be created through createFunction
* @throws ParsingException if the function can't be created with the given inputs
*/
public abstract Function createAbstractFunction(String identity, Node root, String xpathVersion)
throws UnknownIdentifierException, ParsingException, FunctionTypeException;
}
| 20,406 | 42.143763 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/NotFunction.java | /*
* @(#)NotFunction.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.BooleanAttribute;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A class that implements the not function. This function takes one boolean argument and returns
* the logical negation of that value. If the argument evaluates to indeterminate, an indeterminate
* result is returned.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class NotFunction extends FunctionBase {
/**
* Standard identifier for the not function.
*/
public static final String NAME_NOT = FUNCTION_NS + "not";
/**
* Creates a new <code>NotFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public NotFunction(String functionName) {
super(NAME_NOT, 0, BooleanAttribute.identifier, false, 1, BooleanAttribute.identifier,
false);
if (!functionName.equals(NAME_NOT))
throw new IllegalArgumentException("unknown not function: " + functionName);
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_NOT);
return set;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have a real value, perform the not operation.
boolean arg = ((BooleanAttribute) argValues[0]).getValue();
return EvaluationResult.getInstance(!arg);
}
}
| 4,403 | 37.631579 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/AbsFunction.java | /*
* @(#)AbsFunction.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.DoubleAttribute;
import org.wso2.balana.attr.IntegerAttribute;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A class that implements all the *-abs functions. It takes one operand of the appropriate type and
* returns the absolute value of the operand. If the operand is indeterminate, an indeterminate
* result is returned.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class AbsFunction extends FunctionBase {
/**
* Standard identifier for the integer-abs function.
*/
public static final String NAME_INTEGER_ABS = FUNCTION_NS + "integer-abs";
/**
* Standard identifier for the double-abs function.
*/
public static final String NAME_DOUBLE_ABS = FUNCTION_NS + "double-abs";
// inernal identifiers for each of the supported functions
private static final int ID_INTEGER_ABS = 0;
private static final int ID_DOUBLE_ABS = 1;
/**
* Creates a new <code>AbsFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is known
*/
public AbsFunction(String functionName) {
super(functionName, getId(functionName), getArgumentType(functionName), false, 1,
getArgumentType(functionName), false);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*/
private static int getId(String functionName) {
if (functionName.equals(NAME_INTEGER_ABS))
return ID_INTEGER_ABS;
else if (functionName.equals(NAME_DOUBLE_ABS))
return ID_DOUBLE_ABS;
else
throw new IllegalArgumentException("unknown abs function " + functionName);
}
/**
* Private helper that returns the type used for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String getArgumentType(String functionName) {
if (functionName.equals(NAME_INTEGER_ABS))
return IntegerAttribute.identifier;
else
return DoubleAttribute.identifier;
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_INTEGER_ABS);
set.add(NAME_DOUBLE_ABS);
return set;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// evaluate the inputs, returning any error that may occur
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have real values, perform the abs operation
// in the manner appropriate for the type of the arguments.
switch (getFunctionId()) {
case ID_INTEGER_ABS: {
long arg = ((IntegerAttribute) argValues[0]).getValue();
long absValue = Math.abs(arg);
result = new EvaluationResult(new IntegerAttribute(absValue));
break;
}
case ID_DOUBLE_ABS: {
double arg = ((DoubleAttribute) argValues[0]).getValue();
double absValue = Math.abs(arg);
result = new EvaluationResult(new DoubleAttribute(absValue));
break;
}
}
return result;
}
}
| 6,190 | 36.981595 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/Function.java | /*
* @(#)Function.java
*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.Indenter;
import java.net.URI;
import java.io.OutputStream;
import java.util.List;
/**
* Interface that all functions in the system must implement.
*
* @since 1.0
* @author Seth Proctor
*/
public interface Function extends Expression {
/**
* Evaluates the <code>Function</code> using the given inputs. The <code>List</code> contains
* <code>Evaluatable<code>s which are all
* of the correct type if the <code>Function</code> has been created as part of an
* <code>Apply</code> or <code>TargetMatch</code>, but which may otherwise be invalid. Each
* parameter should be evaluated by the <code>Function</code>, unless the <code>Function</code>
* doesn't need to evaluate all inputs to determine a result (as in the case of the or
* function). The order of the <code>List</code> is significant, so a <code>Function</code>
* should have a very good reason if it wants to evaluate the inputs in a different order.
* <p>
* Note that if this is a higher-order function, like any-of, then some argument (typically the
* first) in the <code>List</code> will actually be a Function object representing the function
* to apply to some bag. A function needs to know if it's a higher-order function, and therefore
* whether or not to look for this case. Also, a higher-order function is responsible for
* checking that the inputs that it will pass to the <code>Function</code> provided as the first
* parameter are valid, ie. it must do a <code>checkInputs</code> on its sub-function when
* <code>checkInputs</code> is called on the higher-order function.
*
* @param inputs the <code>List</code> of inputs for the function
* @param context the representation of the request
*
* @return a result containing the <code>AttributeValue</code> computed when evaluating the
* function, or <code>Status</code> specifying some error condition
*/
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context);
/**
* Returns the identifier of this function as known by the factories. In the case of the
* standard XACML functions, this will be one of the URIs defined in the standard namespace.
* This function must always return the complete namespace and identifier of this function.
*
* @return the function's identifier
*/
public URI getIdentifier();
/**
* Provides the type of <code>AttributeValue</code> that this function returns from
* <code>evaluate</code> in a successful evaluation.
*
* @return the type returned by this function
*/
public URI getReturnType();
/**
* Tells whether this function will return a bag of values or just a single value.
*
* @return true if evaluation will return a bag, false otherwise
*/
public boolean returnsBag();
/**
* Checks that the given inputs are of the right types, in the right order, and are the right
* number for this function to evaluate. If the function cannot accept the inputs for
* evaluation, an <code>IllegalArgumentException</code> is thrown.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code>s, with the first argument being
* a <code>Function</code> if this is a higher-order function
*
* @throws IllegalArgumentException if the inputs do match what the function accepts for
* evaluation
*/
public void checkInputs(List inputs) throws IllegalArgumentException;
/**
* Checks that the given inputs are of the right types, in the right order, and are the right
* number for this function to evaluate. If the function cannot accept the inputs for
* evaluation, an <code>IllegalArgumentException</code> is thrown. Unlike the other
* <code>checkInput</code> method in this interface, this assumes that the parameters will never
* provide bags of values. This is useful if you're considering a target function which has a
* designator or selector in its input list, but which passes the values from the derived bags
* one at a time to the function, so the function doesn't have to deal with the bags that the
* selector or designator generates.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code>s, with the first argument being
* a <code>Function</code> if this is a higher-order function
*
* @throws IllegalArgumentException if the inputs do match what the function accepts for
* evaluation
*/
public void checkInputsNoBag(List inputs) throws IllegalArgumentException;
/**
* Encodes this <code>Function</code> into its XML form
*
* @return <code>String</code>
*/
public String encode();
/**
* Encodes this <code>Function</code> into its XML form and writes this out to the provided
* <code>StringBuilder<code>
*
* @param builder string stream into which the XML-encoded data is written
*/
public void encode(StringBuilder builder);
}
| 7,035 | 45.289474 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/SubtractFunction.java | /*
* @(#)SubtractFunction.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.DoubleAttribute;
import org.wso2.balana.attr.IntegerAttribute;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A class that implements all the *-subtract functions. It takes two operands of the appropriate
* type and returns the difference of the operands. If either of the operands is indeterminate, an
* indeterminate result is returned.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class SubtractFunction extends FunctionBase {
/**
* Standard identifier for the integer-subtract function.
*/
public static final String NAME_INTEGER_SUBTRACT = FUNCTION_NS + "integer-subtract";
/**
* Standard identifier for the integer-subtract function.
*/
public static final String NAME_DOUBLE_SUBTRACT = FUNCTION_NS + "double-subtract";
// inernal identifiers for each of the supported functions
private static final int ID_INTEGER_SUBTRACT = 0;
private static final int ID_DOUBLE_SUBTRACT = 1;
/**
* Creates a new <code>SubtractFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public SubtractFunction(String functionName) {
super(functionName, getId(functionName), getArgumentType(functionName), false, 2,
getArgumentType(functionName), false);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*/
private static int getId(String functionName) {
if (functionName.equals(NAME_INTEGER_SUBTRACT))
return ID_INTEGER_SUBTRACT;
else if (functionName.equals(NAME_DOUBLE_SUBTRACT))
return ID_DOUBLE_SUBTRACT;
else
throw new IllegalArgumentException("unknown subtract function " + functionName);
}
/**
* Private helper that returns the type used for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String getArgumentType(String functionName) {
if (functionName.equals(NAME_INTEGER_SUBTRACT))
return IntegerAttribute.identifier;
else
return DoubleAttribute.identifier;
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_INTEGER_SUBTRACT);
set.add(NAME_DOUBLE_SUBTRACT);
return set;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have real values, perform the subtract operation
// in the manner appropriate for the type of the arguments.
switch (getFunctionId()) {
case ID_INTEGER_SUBTRACT: {
long arg0 = ((IntegerAttribute) argValues[0]).getValue();
long arg1 = ((IntegerAttribute) argValues[1]).getValue();
long difference = arg0 - arg1;
result = new EvaluationResult(new IntegerAttribute(difference));
break;
}
case ID_DOUBLE_SUBTRACT: {
double arg0 = ((DoubleAttribute) argValues[0]).getValue();
double arg1 = ((DoubleAttribute) argValues[1]).getValue();
double difference = arg0 - arg1;
result = new EvaluationResult(new DoubleAttribute(difference));
break;
}
}
return result;
}
}
| 6,436 | 38.012121 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/IPInRangeFunction.java | /*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.cond;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.BooleanAttribute;
import org.wso2.balana.attr.IPAddressAttribute;
import org.wso2.balana.ctx.EvaluationCtx;
import java.net.InetAddress;
import java.util.List;
/**
* IP range function developed for Balana.
*/
public class IPInRangeFunction extends FunctionBase {
/**
* The identifier for this function
*/
public static final String NAME = "urn:org.wso2.balana:function:ip-in-range";
/**
* Default constructor.
*/
public IPInRangeFunction() {
super(NAME, 0, IPAddressAttribute.identifier, false, 3, BooleanAttribute.identifier, false);
}
/**
* Evaluates the ip-in-range function, which takes three <code>IPAddressAttribute</code> values.
* This function return true if the first value falls between the second and third values
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context the respresentation of the request
*
* @return an <code>EvaluationResult</code> containing true or false
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
// check if any errors occured while resolving the inputs
if (result != null)
return result;
// get the three ip values
long ipAddressToTest = ipToLong(((IPAddressAttribute)argValues[0]).getAddress());
long ipAddressMin = ipToLong(((IPAddressAttribute)argValues[1]).getAddress());
long ipAddressMax = ipToLong(((IPAddressAttribute)argValues[2]).getAddress());
if(ipAddressMin > ipAddressMax){
long temp = ipAddressMax;
ipAddressMax = ipAddressMin;
ipAddressMin = temp;
}
// we're in the range if the middle is now between min and max ip address
return EvaluationResult.getInstance(ipAddressToTest >= ipAddressMin && ipAddressToTest <= ipAddressMax);
}
/**
* Helper method
* @param ip
* @return
*/
public static long ipToLong(InetAddress ip) {
byte[] octets = ip.getAddress();
long result = 0;
for (byte octet : octets) {
result <<= 8;
result |= octet & 0xff;
}
return result;
}
}
| 3,207 | 31.08 | 112 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/SetFunction.java | /*
* @(#)SetFunction.java
*
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.attr.AnyURIAttribute;
import org.wso2.balana.attr.Base64BinaryAttribute;
import org.wso2.balana.attr.BooleanAttribute;
import org.wso2.balana.attr.DateAttribute;
import org.wso2.balana.attr.DateTimeAttribute;
import org.wso2.balana.attr.DayTimeDurationAttribute;
import org.wso2.balana.attr.DNSNameAttribute;
import org.wso2.balana.attr.DoubleAttribute;
import org.wso2.balana.attr.HexBinaryAttribute;
import org.wso2.balana.attr.IntegerAttribute;
import org.wso2.balana.attr.IPAddressAttribute;
import org.wso2.balana.attr.RFC822NameAttribute;
import org.wso2.balana.attr.StringAttribute;
import org.wso2.balana.attr.TimeAttribute;
import org.wso2.balana.attr.X500NameAttribute;
import org.wso2.balana.attr.YearMonthDurationAttribute;
import java.util.HashSet;
import java.util.Set;
/**
* Represents all of the Set functions, though the actual implementations are in two sub-classes
* specific to the condition and general set functions.
*
* @since 1.0
* @author Seth Proctor
*/
public abstract class SetFunction extends FunctionBase {
/**
* Base name for the type-intersection funtions. To get the standard identifier for a given
* type, use <code>FunctionBase.FUNCTION_NS</code> + the datatype's base name (e.g.,
* <code>string</code>) + </code>NAME_BASE_INTERSECTION</code>.
*/
public static final String NAME_BASE_INTERSECTION = "-intersection";
/**
* Base name for the type-at-least-one-member-of funtions. To get the standard identifier for a
* given type, use <code>FunctionBase.FUNCTION_NS</code> + the datatype's base name (e.g.,
* <code>string</code>) + </code>NAME_BASE_AT_LEAST_ONE_MEMBER_OF</code>.
*/
public static final String NAME_BASE_AT_LEAST_ONE_MEMBER_OF = "-at-least-one-member-of";
/**
* Base name for the type-union funtions. To get the standard identifier for a given type, use
* <code>FunctionBase.FUNCTION_NS</code> + the datatype's base name (e.g., <code>string</code>)
* + </code>NAME_BASE_UNION</code>.
*/
public static final String NAME_BASE_UNION = "-union";
/**
* Base name for the type-subset funtions. To get the standard identifier for a given type, use
* <code>FunctionBase.FUNCTION_NS</code> + the datatype's base name (e.g., <code>string</code>)
* + </code>NAME_BASE_SUBSET</code>.
*/
public static final String NAME_BASE_SUBSET = "-subset";
/**
* Base name for the type-set-equals funtions. To get the standard identifier for a given type,
* use <code>FunctionBase.FUNCTION_NS</code> + the datatype's base name (e.g.,
* <code>string</code>) + </code>NAME_BASE_SET_EQUALS</code>.
*/
public static final String NAME_BASE_SET_EQUALS = "-set-equals";
/**
* A complete list of all the XACML datatypes supported by the Set functions in XACML 1.x
*/
protected static String baseTypes[] = { StringAttribute.identifier,
BooleanAttribute.identifier, IntegerAttribute.identifier, DoubleAttribute.identifier,
DateAttribute.identifier, DateTimeAttribute.identifier, TimeAttribute.identifier,
AnyURIAttribute.identifier, HexBinaryAttribute.identifier,
Base64BinaryAttribute.identifier, DayTimeDurationAttribute.identifier,
YearMonthDurationAttribute.identifier, X500NameAttribute.identifier,
RFC822NameAttribute.identifier };
/**
* A complete list of all the XACML datatypes newly supported by the Set functions in XACML 2.0
*/
protected static String baseTypes2[] = { IPAddressAttribute.identifier,
DNSNameAttribute.identifier };
/**
* A complete list of all the XACML datatypes supported by the Set functions in XACML 1.x, using
* the "simple" form of the names (eg, string instead of
* http://www.w3.org/2001/XMLSchema#string)
*/
protected static String simpleTypes[] = { "string", "boolean", "integer", "double", "date",
"dateTime", "time", "anyURI", "hexBinary", "base64Binary", "dayTimeDuration",
"yearMonthDuration", "x500Name", "rfc822Name" };
/**
* A complete list of all the XACML datatypes newly supported by the Set functions in XACML 2.0,
* using the "simple" form of the names (eg, string instead of
* http://www.w3.org/2001/XMLSchema#string)
*/
protected static String simpleTypes2[] = { "ipAddress", "dnsName" };
/**
* Creates a new instance of the intersection set function. This should be used to create
* support for any new attribute types and then the new <code>SetFunction</code> object should
* be added to the factory (all set functions for the base types are already installed in the
* factory).
*
* @param functionName the name of the function
* @param argumentType the attribute type this function will work with
*
* @return a new <code>SetFunction</code> for the given type
*/
public static SetFunction getIntersectionInstance(String functionName, String argumentType) {
return new GeneralSetFunction(functionName, argumentType, NAME_BASE_INTERSECTION);
}
/**
* Creates a new instance of the at-least-one-member-of set function. This should be used to
* create support for any new attribute types and then the new <code>SetFunction</code> object
* should be added to the factory (all set functions for the base types are already installed in
* the factory).
*
* @param functionName the name of the function
* @param argumentType the attribute type this function will work with
*
* @return a new <code>SetFunction</code> for the given type
*/
public static SetFunction getAtLeastOneInstance(String functionName, String argumentType) {
return new ConditionSetFunction(functionName, argumentType,
NAME_BASE_AT_LEAST_ONE_MEMBER_OF);
}
/**
* Creates a new instance of the union set function. This should be used to create support for
* any new attribute types and then the new <code>SetFunction</code> object should be added to
* the factory (all set functions for the base types are already installed in the factory).
*
* @param functionName the name of the function
* @param argumentType the attribute type this function will work with
*
* @return a new <code>SetFunction</code> for the given type
*/
public static SetFunction getUnionInstance(String functionName, String argumentType) {
return new GeneralSetFunction(functionName, argumentType, NAME_BASE_UNION);
}
/**
* Creates a new instance of the subset set function. This should be used to create support for
* any new attribute types and then the new <code>SetFunction</code> object should be added to
* the factory (all set functions for the base types are already installed in the factory).
*
* @param functionName the name of the function
* @param argumentType the attribute type this function will work with
*
* @return a new <code>SetFunction</code> for the given type
*/
public static SetFunction getSubsetInstance(String functionName, String argumentType) {
return new ConditionSetFunction(functionName, argumentType, NAME_BASE_SUBSET);
}
/**
* Creates a new instance of the equals set function. This should be used to create support for
* any new attribute types and then the new <code>SetFunction</code> object should be added to
* the factory (all set functions for the base types are already installed in the factory).
*
* @param functionName the name of the function
* @param argumentType the attribute type this function will work with
*
* @return a new <code>SetFunction</code> for the given type
*/
public static SetFunction getSetEqualsInstance(String functionName, String argumentType) {
return new ConditionSetFunction(functionName, argumentType, NAME_BASE_SET_EQUALS);
}
/**
* Protected constuctor used by the general and condition subclasses. If you need to create a
* new <code>SetFunction</code> instance you should either use one of the
* <code>getInstance</code> methods or construct one of the sub-classes directly.
*
* @param functionName the identitifer for the function
* @param functionId an optional, internal numeric identifier
* @param argumentType the datatype this function accepts
* @param returnType the datatype this function returns
* @param returnsBag whether this function returns bags
*/
protected SetFunction(String functionName, int functionId, String argumentType,
String returnType, boolean returnsBag) {
super(functionName, functionId, argumentType, true, 2, returnType, returnsBag);
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.addAll(ConditionSetFunction.getSupportedIdentifiers());
set.addAll(GeneralSetFunction.getSupportedIdentifiers());
return set;
}
}
| 11,151 | 45.661088 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/VariableManager.java | /*
* @(#)VariableManager.java
*
* Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.DOMHelper;
import org.wso2.balana.ParsingException;
import org.wso2.balana.PolicyMetaData;
import org.wso2.balana.ProcessingException;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* This class is used by the parsing routines to handle the relationships between variable
* references and definitions. Specifically, it takes care of the fact that definitions can be
* placed after their first reference, and can use references to create circular or recursive
* relationships. It keeps track of what's in the process of being parsed and will pre-parse
* elements as needed.
* <p>
* Note that you should never have to use this class directly. It is really meant only as a utility
* for the internal parsing routines. Also, note that the operations on this class are not
* thread-safe. Typically this doesn't matter, since the code doesn't support using more than one
* thread to parse a single Policy.
*
* @since 2.0
* @author Seth Proctor
*/
public class VariableManager {
// the map from identifiers to internal data
private Map idMap;
// the meta-data for the containing policy
private PolicyMetaData metaData;
/**
* Creates a manager with a fixed set of supported identifiers. For each of these identifiers,
* the map supplies a cooresponding DOM node used to parse the definition. This is used if, in
* the course of parsing one definition, a reference requires that you have information about
* another definition available. All parsed definitions are cached so that each is only parsed
* once. If a node is not provided, then the parsing code may throw an exception if out-of-order
* or circular refereces are used.
* <p>
* Note that the use of a DOM node may change to an arbitrary interface, so that you could use
* your own mechanism, but this is still being hashed out. This interface will be forzed before
* a 2.0 release.
*
* @param variableIds a <code>Map</code> from an identifier to the <code>Node</code> that is the
* root of the cooresponding variable definition, or null
* @param metaData the meta-data associated with the containing policy
*/
public VariableManager(Map variableIds, PolicyMetaData metaData) {
idMap = new HashMap();
Iterator it = variableIds.entrySet().iterator();
while (it.hasNext()) {
Object key = ((Entry)it.next()).getKey();
Node node = (Node) (variableIds.get(key));
idMap.put(key, new VariableState(null, node, null, false, false));
}
this.metaData = metaData;
}
/**
* Returns the definition with the given identifier. If the definition is not available, then
* this method will try to get the definition based on the DOM node given for this identifier.
* If parsing the definition requires loading another definition (because of a reference) then
* this method will be recursively invoked. This may make it slow to call this method once, but
* all retrieved definitions are cached, and once this manager has started parsing a definition
* it will never try parsing that definition again. If the definition cannot be retrieved, then
* an exception is thrown.
*
* @param variableId the definition's identifier
*
* @return the identified definition
*
* @throws ProcessingException if the definition cannot be resolved
*/
public VariableDefinition getDefinition(String variableId) {
VariableState state = (VariableState) (idMap.get(variableId));
// make sure this is an identifier we handle
if (state == null)
throw new ProcessingException("variable is unsupported: " + variableId);
// if we've resolved the definition before, then we're done
if (state.definition != null)
return state.definition;
// we don't have the definition, so get the DOM node
Node node = state.rootNode;
// we can't keep going unless we have a node to work with
if (node != null) {
// if we've already started parsing this node before, then
// don't start again
if (state.handled)
throw new ProcessingException("processing in progress");
// keep track of the fact that we're parsing this node, and
// also get the type (if it's an Apply node)
state.handled = true;
discoverApplyType(node, state);
try {
// now actually try parsing the definition...remember that
// if its expression has a reference, we could end up
// calling this manager method again
state.definition = VariableDefinition.getInstance(state.rootNode, metaData, this);
return state.definition;
} catch (ParsingException pe) {
// we failed to parse the definition for some reason
throw new ProcessingException("failed to parse the definition", pe);
}
}
// we couldn't figure out how to resolve the definition
throw new ProcessingException("couldn't retrieve definition: " + variableId);
}
/**
* Private helper method to get the type of an expression, but only if that expression is an
* Apply. Basically, if there is a circular reference, then we'll need to know the types before
* we're done parsing one of the definitions. But, a circular reference that requires
* type-checking can only happen if the definition's expression is an Apply. So, we look here,
* and if it's an Apply, we get the type information and store that for later use, just in case.
* <p>
* Note that we could wait until later to try this, or we could check first to see if there will
* be a circular reference. Comparatively, however, this isn't too expensive, and it makes the
* system much simpler. Still, it's worth re-examining this to see if there's a way that makes
* more sense.
*/
private void discoverApplyType(Node root, VariableState state) {
// get the first element, which is the expression node
NodeList nodes = root.getChildNodes();
Node xprNode = nodes.item(0);
int i = 1;
while (xprNode.getNodeType() != Node.ELEMENT_NODE)
xprNode = nodes.item(i++);
// now see if the node is an Apply
if (DOMHelper.getLocalName(xprNode).equals("Apply")) {
try {
// get the function in the Apply...
Function function = ExpressionHandler.getFunction(xprNode, metaData,
FunctionFactory.getGeneralInstance());
// ...and store the type information in the variable state
state.type = function.getReturnType();
state.returnsBag = function.returnsBag();
} catch (ParsingException pe) {
// we can just ignore this...if there really is an error,
// then it will come up during parsing in a code path that
// can handle the error cleanly
}
}
}
/**
* Returns the datatype that the identified definition's expression resolves to on evaluation.
* Note that this method makes every attempt to discover this value, including parsing dependent
* definitions if needed and possible.
*
* @param variableId the identifier for the definition
*
* @return the datatype that the identified definition's expression evaluates to
*
* @throws ProcessingException if the identifier is not supported or if the result cannot be
* resolved
*/
public URI getVariableType(String variableId) {
VariableState state = (VariableState) (idMap.get(variableId));
// make sure the variable is supported
if (state == null)
throw new ProcessingException("variable not supported: " + variableId);
// if we've previously figured out the type, then return that
if (state.type != null)
return state.type;
// we haven't figured out the type already, so see if we have or
// can resolve the definition
VariableDefinition definition = state.definition;
if (definition == null)
definition = getDefinition(variableId);
// if we could get the definition, then ask it for the type
if (definition != null)
return definition.getExpression().getType();
// we exhausted all our ways to get the right answer
throw new ProcessingException("we couldn't establish the type: " + variableId);
}
/**
* Returns true if the identified definition's expression resolves to a bag on evaluation. Note
* that this method makes every attempt to discover this value, including parsing dependent
* definitions if needed and possible.
*
* @param variableId the identifier for the definition
*
* @return true if the identified definition's expression evaluates to a bag
*
* @throws ProcessingException if the identifier is not supported or if the result cannot be
* resolved
*/
public boolean returnsBag(String variableId) {
VariableState state = (VariableState) (idMap.get(variableId));
// make sure the variable is supported
if (state == null)
throw new ProcessingException("variable not supported: " + variableId);
// the flag is only valid if a type has also been determined
if (state.type != null)
return state.returnsBag;
// we haven't figured out the type already, so see if we have or
// can resolve the definition
VariableDefinition definition = state.definition;
if (definition == null)
definition = getDefinition(variableId);
// if we could get the definition, then ask it for the bag return
if (definition != null)
return definition.getExpression().returnsBag();
// we exhausted all our ways to get the right answer
throw new ProcessingException("couldn't establish bag return for " + variableId);
}
/**
* Inner class that is used simply to manage fields associated with a given identifier.
*/
static class VariableState {
// the resolved definition for the identifier
public VariableDefinition definition;
// the DOM node used to parse the definition
public Node rootNode;
// the datatype returned when evaluating the definition
public URI type;
// whether the definition's root evaluates to a Bag
public boolean returnsBag;
// whether the definition is being parsed and constructed
public boolean handled;
public VariableState() {
this.definition = null;
this.rootNode = null;
this.type = null;
this.returnsBag = false;
this.handled = false;
}
public VariableState(VariableDefinition definition, Node rootNode, URI type,
boolean returnsBag, boolean handled) {
this.definition = definition;
this.rootNode = rootNode;
this.type = type;
this.returnsBag = returnsBag;
this.handled = handled;
}
}
}
| 13,461 | 41.872611 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/VariableDefinition.java | /*
* @(#)VariableDefinition.java
*
* Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.Indenter;
import org.wso2.balana.ParsingException;
import org.wso2.balana.PolicyMetaData;
import java.io.OutputStream;
import java.io.PrintStream;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* This class supports the VariableDefinitionType type introuced in XACML 2.0. It allows a Policy to
* pre-define any number of expression blocks for general use. Note that it's legal (though not
* usually useful) to define expressions that don't get referenced within the Policy. It is illegal
* to have more than one definition with the same identifier within a Policy.
*
* @since 2.0
* @author Seth Proctor
*/
public class VariableDefinition {
// the identitifer for this definition
private String variableId;
// the actual expression defined here
private Expression expression;
/**
* Creates a new <code>VariableDefinition</code> with the given identifier and expression.
*
* @param variableId the identifier for this definition
* @param expression the expression defined here
*/
public VariableDefinition(String variableId, Expression expression) {
this.variableId = variableId;
this.expression = expression;
}
/**
* Returns a new instance of the <code>VariableDefinition</code> class based on a DOM node. The
* node must be the root of an XML VariableDefinitionType.
*
* @param root the DOM root of a VariableDefinitionType XML type
* @param metaData the meta-data associated with the containing policy
* @param manager <code>VariableManager</code> used to connect references to this definition
*
* @throws ParsingException if the VariableDefinitionType is invalid
*/
public static VariableDefinition getInstance(Node root, PolicyMetaData metaData,
VariableManager manager) throws ParsingException {
String variableId = root.getAttributes().getNamedItem("VariableId").getNodeValue();
// get the first element, which is the expression node
NodeList nodes = root.getChildNodes();
Node xprNode = nodes.item(0);
int i = 1;
while (xprNode.getNodeType() != Node.ELEMENT_NODE)
xprNode = nodes.item(i++);
// use that node to get the expression
Expression xpr = ExpressionHandler.parseExpression(xprNode, metaData, manager);
return new VariableDefinition(variableId, xpr);
}
/**
* Returns the identifier for this definition.
*
* @return the definition's identifier
*/
public String getVariableId() {
return variableId;
}
/**
* Returns the expression provided by this definition.
*
* @return the definition's expression
*/
public Expression getExpression() {
return expression;
}
/**
* Encodes this <code>VariableDefinition</code> into its XML form
*
* @return <code>String</code>
*/
public String encode() {
StringBuilder builder = new StringBuilder();
encode(builder);
return builder.toString();
}
/**
* Encodes this <code>VariableDefinition</code> into its XML form and writes this out to the provided
* <code>StringBuilder<code>
*
* @param builder string stream into which the XML-encoded data is written
*/
public void encode(StringBuilder builder) {
builder.append("<VariableDefinition VariableId=\"").append(variableId).append("\">\n");
expression.encode(builder);
builder.append("</VariableDefinition>\n");
}
}
| 5,445 | 35.797297 | 105 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/MapFunction.java | /*
* @(#)MapFunction.java 1.4 01/30/03
*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.DOMHelper;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.Indenter;
import org.wso2.balana.ParsingException;
import org.wso2.balana.attr.BagAttribute;
import org.wso2.balana.ctx.Status;
import java.net.URI;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Represents the higher order bag function map.
*
* @since 1.0
* @author Seth Proctor
*/
class MapFunction implements Function {
/**
* The name of this function
*/
public static final String NAME_MAP = FunctionBase.FUNCTION_NS + "map";
// the return type for this instance
private URI returnType;
// the stuff used to make sure that we have a valid identifier or a
// known error, just like in the attribute classes
private static URI identifier;
private static RuntimeException earlyException;
// try to initialize the identifier
static {
try {
identifier = new URI(NAME_MAP);
} catch (Exception e) {
earlyException = new IllegalArgumentException();
earlyException.initCause(e);
}
};
/**
* Creates a new instance of a <code>MapFunction</code>.
*
* @param returnType the type returned by this function
*/
public MapFunction(URI returnType) {
this.returnType = returnType;
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_MAP);
return set;
}
/**
* Creates a new instance of the map function using the data found in the DOM node provided.
* This is called by a proxy when the factory is asked to create one of these functions.
*
* @param root the DOM node of the apply tag containing this function
*
* @return a <code>MapFunction</code> instance
*
* @throws ParsingException if the DOM data was incorrect
*/
public static MapFunction getInstance(Node root) throws ParsingException {
URI returnType = null;
NodeList nodes = root.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (DOMHelper.getLocalName(node).equals("Function")) {
String funcName = node.getAttributes().getNamedItem("FunctionId").getNodeValue();
FunctionFactory factory = FunctionFactory.getGeneralInstance();
try {
Function function = factory.createFunction(funcName);
returnType = function.getReturnType();
break;
} catch (FunctionTypeException fte) {
// try to get this as an abstract function
try {
Function function = factory.createAbstractFunction(funcName, root);
returnType = function.getReturnType();
break;
} catch (Exception e) {
// any exception here is an error
throw new ParsingException("invalid abstract map", e);
}
} catch (Exception e) {
// any exception that's not function type is an error
throw new ParsingException("couldn't parse map body", e);
}
}
}
// see if we found the return type
if (returnType == null)
throw new ParsingException("couldn't find the return type");
return new MapFunction(returnType);
}
/**
* Returns the full identifier of this function, as known by the factories.
*
* @return the function's identifier
*/
public URI getIdentifier() {
// strictly speaking, this should never happen
if (earlyException != null)
throw earlyException;
return identifier;
}
/**
* Returns the same value as <code>getReturnType</code>. This is here to support the
* <code>Expression</code> interface.
*
* @return the return type
*/
public URI getType() {
return getReturnType();
}
/**
* Returns the attribute type returned by this function.
*
* @return the return type
*/
public URI getReturnType() {
return returnType;
}
/**
* Returns <code>true</code>, since the map function always returns a bag
*
* @return true
*/
public boolean returnsBag() {
return true;
}
/**
* Helper function to create a processing error message.
*/
private static EvaluationResult makeProcessingError(String message) {
ArrayList code = new ArrayList();
code.add(Status.STATUS_PROCESSING_ERROR);
return new EvaluationResult(new Status(code, message));
}
/**
* Evaluates the function given the input data. Map expects a <code>Function</code> followed by
* a <code>BagAttribute</code>.
*
* @param inputs the input agrument list
* @param context the representation of the request
*
* @return the result of evaluation
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// get the inputs, which we expect to be correct
Iterator iterator = inputs.iterator();
Function function = null;
Expression xpr = (Expression) (iterator.next());
if (xpr instanceof Function) {
function = (Function) xpr;
} else {
function = (Function) (((VariableReference) xpr).getReferencedDefinition()
.getExpression());
}
Evaluatable eval = (Evaluatable) (iterator.next());
EvaluationResult result = eval.evaluate(context);
// in a higher-order case, if anything is INDETERMINATE, then
// we stop right away
if (result.indeterminate())
return result;
BagAttribute bag = (BagAttribute) (result.getAttributeValue());
// param: function, bag
// return: bag
// for each value in the bag evaluate the given function with
// the value and put the function result in a new bag that
// is ultimately returned
Iterator it = bag.iterator();
List<AttributeValue> outputs = new ArrayList<AttributeValue>();
while (it.hasNext()) {
List params = new ArrayList();
params.add(it.next());
result = function.evaluate(params, context);
if (result.indeterminate())
return result;
outputs.add(result.getAttributeValue());
}
return new EvaluationResult(new BagAttribute(returnType, outputs));
}
/**
* Checks that the input list is valid for evaluation.
*
* @param inputs a <code>List</code> of inputs
*
* @throws IllegalArgumentException if the inputs cannot be evaluated
*/
public void checkInputs(List inputs) throws IllegalArgumentException {
Object[] list = inputs.toArray();
// check that we've got the right number of arguments
if (list.length != 2)
throw new IllegalArgumentException("map requires two inputs");
// now check that we've got the right types for map
Function function = null;
if (list[0] instanceof Function) {
function = (Function) (list[0]);
} else if (list[0] instanceof VariableReference) {
Expression xpr = ((VariableReference) (list[0])).getReferencedDefinition()
.getExpression();
if (xpr instanceof Function)
function = (Function) xpr;
}
if (function == null)
throw new IllegalArgumentException("first argument to map must " + "be a Function");
Evaluatable eval = (Evaluatable) (list[1]);
if (!eval.returnsBag())
throw new IllegalArgumentException("second argument to map must " + "be a bag");
// finally, check that the type in the bag is right for the function
List input = new ArrayList();
input.add(list[1]);
function.checkInputsNoBag(input);
}
/**
* Always throws <code>IllegalArgumentException</code> since map needs to work on a bag
*
* @param inputs a <code>List</code> of inputs
*
* @throws IllegalArgumentException always
*/
public void checkInputsNoBag(List inputs) throws IllegalArgumentException {
throw new IllegalArgumentException("map requires a bag");
}
/**
* Encodes this <code>MapFunction</code> into its XML form
*
* @return <code>String</code>
*/
public String encode() {
StringBuilder builder = new StringBuilder();
encode(builder);
return builder.toString();
}
/**
* Encodes this <code>MapFunction</code> into its XML form and writes this out to the provided
* <code>StringBuilder<code>
*
* @param builder string stream into which the XML-encoded data is written
*/
public void encode(StringBuilder builder) {
builder.append("<Function FunctionId=\"" + NAME_MAP + "\"/>\n");
}
}
| 11,461 | 32.711765 | 99 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/BaseFunctionFactory.java | /*
* @(#)BaseCombiningAlgFactory.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ParsingException;
import org.wso2.balana.UnknownIdentifierException;
import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.w3c.dom.Node;
/**
* This is a basic implementation of <code>FunctionFactory</code>. It implements the insertion and
* retrieval methods, but it doesn't actually setup the factory with any functions. It also assumes
* a certain model with regard to the different kinds of functions (Target, Condition, and General).
* For this reason, you may want to re-use this class, or you may want to extend FunctionFactory
* directly, if you're writing a new factory implementation.
* <p>
* Note that while this class is thread-safe on all creation methods, it is not safe to add support
* for a new function while creating an instance of a function. This follows from the assumption
* that most people will initialize these factories up-front, and then start processing without ever
* modifying the factories. If you need these mutual operations to be thread-safe, then you should
* write a wrapper class that implements the right synchronization.
*
* @since 1.2
* @author Seth Proctor
*/
public class BaseFunctionFactory extends FunctionFactory {
// the backing maps for the Function objects
private HashMap functionMap = null;
// the superset factory chained to this factory
private FunctionFactory superset = null;
/**
* Default constructor. No superset factory is used.
*/
public BaseFunctionFactory() {
this(null);
}
/**
* Constructor that sets a "superset factory". This is useful since the different function
* factories (Target, Condition, and General) have a superset relationship (Condition functions
* are a superset of Target functions, etc.). Adding a function to this factory will
* automatically add the same function to the superset factory.
*
* @param superset the superset factory or null
*/
public BaseFunctionFactory(FunctionFactory superset) {
functionMap = new HashMap();
this.superset = superset;
}
/**
* Constructor that defines the initial functions supported by this factory but doesn't use a
* superset factory.
*
* @param supportedFunctions a <code>Set</code> of <code>Function</code>s
* @param supportedAbstractFunctions a mapping from <code>URI</code> to
* <code>FunctionProxy</code>
*/
public BaseFunctionFactory(Set supportedFunctions, Map supportedAbstractFunctions) {
this(null, supportedFunctions, supportedAbstractFunctions);
}
/**
* Constructor that defines the initial functions supported by this factory and uses a superset
* factory. Note that the functions supplied here are not propagated up to the superset factory,
* so you must either make sure the superst factory is correctly initialized or use
* <code>BaseFunctionFactory(FunctionFactory)</code> and then manually add each function.
*
* @param superset the superset factory or null
* @param supportedFunctions a <code>Set</code> of <code>Function</code>s
* @param supportedAbstractFunctions a mapping from <code>URI</code> to
* <code>FunctionProxy</code>
*/
public BaseFunctionFactory(FunctionFactory superset, Set supportedFunctions,
Map supportedAbstractFunctions) {
this(superset);
Iterator it = supportedFunctions.iterator();
while (it.hasNext()) {
Function function = (Function) (it.next());
functionMap.put(function.getIdentifier().toString(), function);
}
it = supportedAbstractFunctions.entrySet().iterator();
while (it.hasNext()) {
URI id = (URI) (((Entry)it.next()).getKey());
FunctionProxy proxy = (FunctionProxy) (supportedAbstractFunctions.get(id));
functionMap.put(id.toString(), proxy);
}
}
/**
* Adds the function to the factory. Most functions have no state, so the singleton model used
* here is typically desireable. The factory will not enforce the requirement that a Target or
* Condition matching function must be boolean.
*
* @param function the <code>Function</code> to add to the factory
*
* @throws IllegalArgumentException if the function's identifier is already used or if the
* function is non-boolean (when this is a Target or Condition factory)
*/
public void addFunction(Function function) throws IllegalArgumentException {
String id = function.getIdentifier().toString();
// make sure this doesn't already exist
if (functionMap.containsKey(id))
throw new IllegalArgumentException("function already exists");
// add to the superset factory
if (superset != null)
superset.addFunction(function);
// finally, add to this factory
functionMap.put(id, function);
}
/**
* Adds the abstract function proxy to the factory. This is used for those functions which have
* state, or change behavior (for instance the standard map function, which changes its return
* type based on how it is used).
*
* @param proxy the <code>FunctionProxy</code> to add to the factory
* @param identity the function's identifier
*
* @throws IllegalArgumentException if the function's identifier is already used
*/
public void addAbstractFunction(FunctionProxy proxy, URI identity)
throws IllegalArgumentException {
String id = identity.toString();
// make sure this doesn't already exist
if (functionMap.containsKey(id))
throw new IllegalArgumentException("function already exists");
// add to the superset factory
if (superset != null)
superset.addAbstractFunction(proxy, identity);
// finally, add to this factory
functionMap.put(id, proxy);
}
/**
* Returns the function identifiers supported by this factory.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public Set getSupportedFunctions() {
Set set = new HashSet(functionMap.keySet());
if (superset != null)
set.addAll(superset.getSupportedFunctions());
return set;
}
/**
* Tries to get an instance of the specified function.
*
* @param identity the name of the function
*
* @throws UnknownIdentifierException if the name isn't known
* @throws FunctionTypeException if the name is known to map to an abstract function, and should
* therefore be created through createAbstractFunction
*/
public Function createFunction(URI identity) throws UnknownIdentifierException,
FunctionTypeException {
return createFunction(identity.toString());
}
/**
* Tries to get an instance of the specified function.
*
* @param identity the name of the function
*
* @throws UnknownIdentifierException if the name isn't known
* @throws FunctionTypeException if the name is known to map to an abstract function, and should
* therefore be created through createAbstractFunction
*/
public Function createFunction(String identity) throws UnknownIdentifierException,
FunctionTypeException {
Object entry = functionMap.get(identity);
if (entry != null) {
if (entry instanceof Function) {
return (Function) entry;
} else {
// this is actually a proxy, which means the other create
// method should have been called
throw new FunctionTypeException("function is abstract");
}
} else {
// we couldn't find a match
throw new UnknownIdentifierException("functions of type " + identity + " are not "
+ "supported by this factory");
}
}
/**
* Tries to get an instance of the specified abstract function.
*
* @param identity the name of the function
* @param root the DOM root containing info used to create the function
*
* @throws UnknownIdentifierException if the name isn't known
* @throws FunctionTypeException if the name is known to map to a concrete function, and should
* therefore be created through createFunction
* @throws ParsingException if the function can't be created with the given inputs
*/
public Function createAbstractFunction(URI identity, Node root)
throws UnknownIdentifierException, ParsingException, FunctionTypeException {
return createAbstractFunction(identity.toString(), root, null);
}
/**
* Tries to get an instance of the specified abstract function.
*
* @param identity the name of the function
* @param root the DOM root containing info used to create the function
* @param xpathVersion the version specified in the contianing policy, or null if no version was
* specified
*
* @throws UnknownIdentifierException if the name isn't known
* @throws FunctionTypeException if the name is known to map to a concrete function, and should
* therefore be created through createFunction
* @throws ParsingException if the function can't be created with the given inputs
*/
public Function createAbstractFunction(URI identity, Node root, String xpathVersion)
throws UnknownIdentifierException, ParsingException, FunctionTypeException {
return createAbstractFunction(identity.toString(), root, xpathVersion);
}
/**
* Tries to get an instance of the specified abstract function.
*
* @param identity the name of the function
* @param root the DOM root containing info used to create the function
*
* @throws UnknownIdentifierException if the name isn't known
* @throws FunctionTypeException if the name is known to map to a concrete function, and should
* therefore be created through createFunction
* @throws ParsingException if the function can't be created with the given inputs
*/
public Function createAbstractFunction(String identity, Node root)
throws UnknownIdentifierException, ParsingException, FunctionTypeException {
return createAbstractFunction(identity, root, null);
}
/**
* Tries to get an instance of the specified abstract function.
*
* @param identity the name of the function
* @param root the DOM root containing info used to create the function
* @param xpathVersion the version specified in the contianing policy, or null if no version was
* specified
*
* @throws UnknownIdentifierException if the name isn't known
* @throws FunctionTypeException if the name is known to map to a concrete function, and should
* therefore be created through createFunction
* @throws ParsingException if the function can't be created with the given inputs
*/
public Function createAbstractFunction(String identity, Node root, String xpathVersion)
throws UnknownIdentifierException, ParsingException, FunctionTypeException {
Object entry = functionMap.get(identity);
if (entry != null) {
if (entry instanceof FunctionProxy) {
try {
return ((FunctionProxy) entry).getInstance(root, xpathVersion);
} catch (Exception e) {
throw new ParsingException(
"couldn't create abstract" + " function " + identity, e);
}
} else {
// this is actually a concrete function, which means that
// the other create method should have been called
throw new FunctionTypeException("function is concrete");
}
} else {
// we couldn't find a match
throw new UnknownIdentifierException("abstract functions of " + "type " + identity
+ " are not supported by " + "this factory");
}
}
}
| 14,263 | 41.834835 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/TimeInRangeFunction.java | /*
* @(#)TimeInRangeFunction.java
*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.BooleanAttribute;
import org.wso2.balana.attr.TimeAttribute;
import java.util.List;
/**
* This class implements the time-in-range function, which takes three time values and returns true
* if the first value falls between the second and the third value. This function was introduced in
* XACML 2.0.
* <p>
* Note that this function allows any time ranges less than 24 hours. In other words, it is not
* bound by normal day boundries (midnight GMT), but by the minimum time in the range. This means
* that ranges like 9am-5pm are supported, as are ranges like 5pm-9am.
*
* @since 2.0
* @author seth proctor
*/
public class TimeInRangeFunction extends FunctionBase {
/**
* The identifier for this function
*/
public static final String NAME = FUNCTION_NS_2 + "time-in-range";
/**
* The number of milliseconds in a minute
*/
public static final long MILLIS_PER_MINUTE = 1000 * 60;
/**
* The number of milliseconds in a day
*/
public static final long MILLIS_PER_DAY = MILLIS_PER_MINUTE * 60 * 24;
/**
* Default constructor.
*/
public TimeInRangeFunction() {
super(NAME, 0, TimeAttribute.identifier, false, 3, BooleanAttribute.identifier, false);
}
/**
* Evaluates the time-in-range function, which takes three <code>TimeAttribute</code> values.
* This function return true if the first value falls between the second and third values (ie.,
* on or after the second time and on or before the third time). If no time zone is specified
* for the second and/or third time value, then the timezone from the first time value is used.
* This lets you say time-in-range(current-time, 9am, 5pm) and always have the evaluation happen
* in your current-time timezone.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context the respresentation of the request
*
* @return an <code>EvaluationResult</code> containing true or false
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
// check if any errors occured while resolving the inputs
if (result != null)
return result;
// get the three time values
TimeAttribute attr = (TimeAttribute) (argValues[0]);
long middleTime = attr.getMilliseconds();
long minTime = resolveTime(attr, (TimeAttribute) (argValues[1]));
long maxTime = resolveTime(attr, (TimeAttribute) (argValues[2]));
// first off, if the min and max are the same, then this can only
// be true is the middle is also the same value
if (minTime == maxTime)
return EvaluationResult.getInstance(middleTime == minTime);
// shift the minTime to 00:00:00 so we can do a normal comparison,
// taking care to shift in the correct direction (left if the
// maxTime is bigger, otherwise right), and making sure that we
// handle any wrapping values for the middle time (the maxTime will
// never wrap around 00:00:00 GMT as long as we're dealing with
// windows of less than 24 hours) ur
// the amount we're shifting
long shiftSpan;
// figure out the right direction and get the shift amount
if (minTime < maxTime)
shiftSpan = -minTime;
else
shiftSpan = MILLIS_PER_DAY - minTime;
// shift the maxTime and the middleTime
maxTime = maxTime + shiftSpan;
middleTime = handleWrap(middleTime + shiftSpan);
// we're in the range if the middle is now between 0 and maxTime
return EvaluationResult.getInstance((middleTime >= 0) && (middleTime <= maxTime));
}
/**
* Private helper method that is used to resolve the correct values for min and max. If an
* explicit timezone is provided for either, then that value gets used. Otherwise we need to
* pick the timezone the middle time is using, and move the other time into that timezone.
*/
private long resolveTime(TimeAttribute middleTime, TimeAttribute otherTime) {
long time = otherTime.getMilliseconds();
int tz = otherTime.getTimeZone();
// if there's no explicit timezone, then the otherTime needs to
// be shifted to the middleTime's timezone
if (tz == TimeAttribute.TZ_UNSPECIFIED) {
// the other time didn't specify a timezone, so we use the
// timezone specified in the middle time...
int middleTz = middleTime.getTimeZone();
// ...and we get the default timezone from the otherTime
tz = otherTime.getDefaultedTimeZone();
// if there was no specified timezone for the middleTime, use
// the default timezone for that too
if (middleTz == TimeAttribute.TZ_UNSPECIFIED)
middleTz = middleTime.getDefaultedTimeZone();
// use the timezone to offset the time value, if the two aren't
// already in the same timezone
if (middleTz != tz) {
time -= ((middleTz - tz) * MILLIS_PER_MINUTE);
time = handleWrap(time);
}
}
return time;
}
/**
* Private helper method that handles when a time value wraps no more than 24 hours either above
* 23:59:59 or below 00:00:00.
*/
private long handleWrap(long time) {
if (time < 0) {
// if it's negative, add one day
return time + MILLIS_PER_DAY;
}
if (time > MILLIS_PER_DAY) {
// if it's more than 24 hours, subtract one day
return time - MILLIS_PER_DAY;
}
return time;
}
}
| 7,968 | 40.290155 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/NOfFunction.java | /*
* @(#)NOfFunction.java
*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.BooleanAttribute;
import org.wso2.balana.attr.IntegerAttribute;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* A class that implements the n-of function. It requires at least one argument. The first argument
* must be an integer and the rest of the arguments must be booleans. If the number of boolean
* arguments that evaluate to true is at least the value of the first argument, the function returns
* true. Otherwise, it returns false (or indeterminate, as described in the next paragraph.
* <p>
* This function evaluates the arguments one at a time, starting with the first one. As soon as the
* result of the function can be determined, evaluation stops and that result is returned. During
* this process, if any argument evaluates to indeterminate, an indeterminate result is returned.
*
* @since 1.0
* @author Steve Hanne
* @author Seth Proctor
*/
public class NOfFunction extends FunctionBase {
/**
* Standard identifier for the n-of function.
*/
public static final String NAME_N_OF = FUNCTION_NS + "n-of";
/**
* Creates a new <code>NOfFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public NOfFunction(String functionName) {
super(NAME_N_OF, 0, BooleanAttribute.identifier, false);
if (!functionName.equals(NAME_N_OF))
throw new IllegalArgumentException("unknown nOf function: " + functionName);
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_N_OF);
return set;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments one by one. As soon as we can return
// a result, do so. Return Indeterminate if any argument
// evaluated is indeterminate.
Iterator it = inputs.iterator();
Evaluatable eval = (Evaluatable) (it.next());
// Evaluate the first argument
EvaluationResult result = eval.evaluate(context);
if (result.indeterminate())
return result;
// if there were no problems, we know 'n'
long n = ((IntegerAttribute) (result.getAttributeValue())).getValue();
// If the number of trues needed is less than zero, report an error.
if (n < 0)
return makeProcessingError("First argument to " + getFunctionName()
+ " cannot be negative.");
// If the number of trues needed is zero, return true.
if (n == 0)
return EvaluationResult.getTrueInstance();
// make sure it's possible to find n true values
long remainingArgs = inputs.size() - 1;
if (n > remainingArgs)
return makeProcessingError("not enough arguments to n-of to " + "find " + n
+ " true values");
// loop through the inputs, trying to find at least n trues
while (remainingArgs >= n) {
eval = (Evaluatable) (it.next());
// evaluate the next argument
result = eval.evaluate(context);
if (result.indeterminate())
return result;
// get the next value, and see if it's true
if (((BooleanAttribute) (result.getAttributeValue())).getValue()) {
// we're one closer to our goal...see if we met it
if (--n == 0)
return EvaluationResult.getTrueInstance();
}
// we're still looking, but we've got one fewer arguments
remainingArgs--;
}
// if we got here then we didn't meet our quota
return EvaluationResult.getFalseInstance();
}
/**
*
*/
public void checkInputs(List inputs) throws IllegalArgumentException {
// check that none of the inputs is a bag
Object[] list = inputs.toArray();
for (int i = 0; i < list.length; i++)
if (((Evaluatable) (list[i])).returnsBag())
throw new IllegalArgumentException("n-of can't use bags");
// if we got here then there were no bags, so ask the other check
// method to finish the checking
checkInputsNoBag(inputs);
}
/**
*
*/
public void checkInputsNoBag(List inputs) throws IllegalArgumentException {
Object[] list = inputs.toArray();
// check that there is at least one arg
if (list.length == 0)
throw new IllegalArgumentException("n-of requires an argument");
// check that the first element is an Integer
Evaluatable eval = (Evaluatable) (list[0]);
if (!eval.getType().toString().equals(IntegerAttribute.identifier))
throw new IllegalArgumentException("first argument to n-of must" + " be an integer");
// now check that the rest of the args are booleans
for (int i = 1; i < list.length; i++) {
if (!((Evaluatable) (list[i])).getType().toString().equals(BooleanAttribute.identifier))
throw new IllegalArgumentException("invalid parameter in n-of"
+ ": expected boolean");
}
}
}
| 7,922 | 38.615 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/ConditionSetFunction.java | /*
* @(#)ConditionSetFunction.java
*
* Copyright 2004-2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.BagAttribute;
import org.wso2.balana.attr.BooleanAttribute;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Specific <code>SetFunction</code> class that supports all of the condition set functions:
* type-at-least-one-member-of, type-subset, and type-set-equals.
*
* @since 1.2
* @author Seth Proctor
*/
public class ConditionSetFunction extends SetFunction {
// private identifiers for the supported functions
private static final int ID_BASE_AT_LEAST_ONE_MEMBER_OF = 0;
private static final int ID_BASE_SUBSET = 1;
private static final int ID_BASE_SET_EQUALS = 2;
// mapping of function name to its associated id and parameter type
private static HashMap<String, Integer> idMap;
private static HashMap<String, String> typeMap;
// the actual supported ids
private static Set<String> supportedIds;
/**
* Static initializer that sets up the paramater info for all the supported functions.
*/
static {
idMap = new HashMap<String, Integer>();
typeMap = new HashMap<String, String>();
for (int i = 0; i < baseTypes.length; i++) {
String baseName = FUNCTION_NS + simpleTypes[i];
String baseType = baseTypes[i];
idMap.put(baseName + NAME_BASE_AT_LEAST_ONE_MEMBER_OF,
Integer.valueOf(ID_BASE_AT_LEAST_ONE_MEMBER_OF));
idMap.put(baseName + NAME_BASE_SUBSET, Integer.valueOf(ID_BASE_SUBSET));
idMap.put(baseName + NAME_BASE_SET_EQUALS, Integer.valueOf(ID_BASE_SET_EQUALS));
typeMap.put(baseName + NAME_BASE_AT_LEAST_ONE_MEMBER_OF, baseType);
typeMap.put(baseName + NAME_BASE_SUBSET, baseType);
typeMap.put(baseName + NAME_BASE_SET_EQUALS, baseType);
}
for (int i = 0; i < baseTypes2.length; i++) {
String baseName = FUNCTION_NS_2 + simpleTypes2[i];
String baseType = baseTypes2[i];
idMap.put(baseName + NAME_BASE_AT_LEAST_ONE_MEMBER_OF,
Integer.valueOf(ID_BASE_AT_LEAST_ONE_MEMBER_OF));
idMap.put(baseName + NAME_BASE_SUBSET, Integer.valueOf(ID_BASE_SUBSET));
idMap.put(baseName + NAME_BASE_SET_EQUALS, Integer.valueOf(ID_BASE_SET_EQUALS));
typeMap.put(baseName + NAME_BASE_AT_LEAST_ONE_MEMBER_OF, baseType);
typeMap.put(baseName + NAME_BASE_SUBSET, baseType);
typeMap.put(baseName + NAME_BASE_SET_EQUALS, baseType);
}
supportedIds = Collections.unmodifiableSet(new HashSet<String>(idMap.keySet()));
idMap.put(NAME_BASE_AT_LEAST_ONE_MEMBER_OF, Integer.valueOf(ID_BASE_AT_LEAST_ONE_MEMBER_OF));
idMap.put(NAME_BASE_SUBSET, Integer.valueOf(ID_BASE_SUBSET));
idMap.put(NAME_BASE_SET_EQUALS, Integer.valueOf(ID_BASE_SET_EQUALS));
};
/**
* Constructor that is used to create one of the condition standard set functions. The name
* supplied must be one of the standard XACML functions supported by this class, including the
* full namespace, otherwise an exception is thrown. Look in <code>SetFunction</code> for
* details about the supported names.
*
* @param functionName the name of the function to create
*
* @throws IllegalArgumentException if the function is unknown
*/
public ConditionSetFunction(String functionName) {
super(functionName, getId(functionName), getArgumentType(functionName),
BooleanAttribute.identifier, false);
}
/**
* Constructor that is used to create instances of condition set functions for new
* (non-standard) datatypes. This is equivalent to using the <code>getInstance</code> methods in
* <code>SetFunction</code> and is generally only used by the run-time configuration code.
*
* @param functionName the name of the new function
* @param datatype the full identifier for the supported datatype
* @param functionType which kind of Set function, based on the <code>NAME_BASE_*</code> fields
*/
public ConditionSetFunction(String functionName, String datatype, String functionType) {
super(functionName, getId(functionName), datatype, BooleanAttribute.identifier, false);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*/
private static int getId(String functionName) {
Integer id = (Integer) (idMap.get(functionName));
if (id == null)
throw new IllegalArgumentException("unknown set function " + functionName);
return id.intValue();
}
/**
* Private helper that returns the argument type for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*/
private static String getArgumentType(String functionName) {
return (String) (typeMap.get(functionName));
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
return supportedIds;
}
/**
* Evaluates the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult evalResult = evalArgs(inputs, context, argValues);
if (evalResult != null)
return evalResult;
// setup the two bags we'll be using
BagAttribute[] bags = new BagAttribute[2];
bags[0] = (BagAttribute) (argValues[0]);
bags[1] = (BagAttribute) (argValues[1]);
AttributeValue result = null;
switch (getFunctionId()) {
// *-at-least-one-member-of takes two bags of the same type and
// returns a boolean
case ID_BASE_AT_LEAST_ONE_MEMBER_OF:
// true if at least one element in the first argument is in the
// second argument (using the *-is-in semantics)
result = BooleanAttribute.getFalseInstance();
Iterator it = bags[0].iterator();
while (it.hasNext()) {
if (bags[1].contains((AttributeValue) (it.next()))) {
result = BooleanAttribute.getTrueInstance();
break;
}
}
break;
// *-set-equals takes two bags of the same type and returns
// a boolean
case ID_BASE_SUBSET:
// returns true if the first argument is a subset of the second
// argument (ie, all the elements in the first bag appear in
// the second bag) ... ignore all duplicate values in both
// input bags
boolean subset = bags[1].containsAll(bags[0]);
result = BooleanAttribute.getInstance(subset);
break;
// *-set-equals takes two bags of the same type and returns
// a boolean
case ID_BASE_SET_EQUALS:
// returns true if the two inputs contain the same elements
// discounting any duplicates in either input ... this is the same
// as applying the and function on the subset function with
// the two inputs, and then the two inputs reversed (ie, are the
// two inputs subsets of each other)
boolean equals = (bags[1].containsAll(bags[0]) && bags[0].containsAll(bags[1]));
result = BooleanAttribute.getInstance(equals);
break;
}
return new EvaluationResult(result);
}
}
| 9,341 | 36.669355 | 97 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/FloorFunction.java | /*
* @(#)FloorFunction.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.DoubleAttribute;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A class that implements the floor function. It takes one double operand, chooses the largest
* integer less than or equal to that value, and returns that integer (as a double). If the operand
* is indeterminate, an indeterminate result is returned.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class FloorFunction extends FunctionBase {
/**
* Standard identifier for the floor function.
*/
public static final String NAME_FLOOR = FUNCTION_NS + "floor";
/**
* Creates a new <code>FloorFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public FloorFunction(String functionName) {
super(NAME_FLOOR, 0, DoubleAttribute.identifier, false, 1, DoubleAttribute.identifier,
false);
if (!functionName.equals(NAME_FLOOR))
throw new IllegalArgumentException("unknown floor function: " + functionName);
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
Set set = new HashSet();
set.add(NAME_FLOOR);
return set;
}
/**
* Evaluate the function, using the specified parameters.
*
* @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
* arguments passed to the function
* @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
* be evaluated
* @return an <code>EvaluationResult</code> representing the function's result
*/
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have real values, perform the floor operation
double arg = ((DoubleAttribute) argValues[0]).getValue();
return new EvaluationResult(new DoubleAttribute(Math.floor(arg)));
}
}
| 4,478 | 37.947826 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/BasicFunctionFactoryProxy.java | /*
* @(#)BasicFunctionFactoryProxy.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
/**
* A simple utility class that manages triples of function factories.
*
* @since 1.2
* @author Seth Proctor
*/
public class BasicFunctionFactoryProxy implements FunctionFactoryProxy {
// the triple of factories
private FunctionFactory targetFactory;
private FunctionFactory conditionFactory;
private FunctionFactory generalFactory;
/**
* Creates a new proxy.
*
* @param targetFactory the target factory provided by this proxy
* @param conditionFactory the target condition provided by this proxy
* @param generalFactory the general factory provided by this proxy
*/
public BasicFunctionFactoryProxy(FunctionFactory targetFactory,
FunctionFactory conditionFactory, FunctionFactory generalFactory) {
this.targetFactory = targetFactory;
this.conditionFactory = conditionFactory;
this.generalFactory = generalFactory;
}
public FunctionFactory getTargetFactory() {
return targetFactory;
}
public FunctionFactory getConditionFactory() {
return conditionFactory;
}
public FunctionFactory getGeneralFactory() {
return generalFactory;
}
}
| 3,047 | 38.076923 | 79 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/StandardFunctionFactory.java | /*
* @(#)StandardFunctionFactory.java
*
* Copyright 2004-2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.balana.UnknownIdentifierException;
import org.wso2.balana.cond.cluster.AbsFunctionCluster;
import org.wso2.balana.cond.cluster.AddFunctionCluster;
import org.wso2.balana.cond.cluster.ComparisonFunctionCluster;
import org.wso2.balana.cond.cluster.ConditionBagFunctionCluster;
import org.wso2.balana.cond.cluster.ConditionSetFunctionCluster;
import org.wso2.balana.cond.cluster.DateMathFunctionCluster;
import org.wso2.balana.cond.cluster.DivideFunctionCluster;
import org.wso2.balana.cond.cluster.EqualFunctionCluster;
import org.wso2.balana.cond.cluster.FloorFunctionCluster;
import org.wso2.balana.cond.cluster.GeneralBagFunctionCluster;
import org.wso2.balana.cond.cluster.GeneralSetFunctionCluster;
import org.wso2.balana.cond.cluster.HigherOrderFunctionCluster;
import org.wso2.balana.cond.cluster.LogicalFunctionCluster;
import org.wso2.balana.cond.cluster.MatchFunctionCluster;
import org.wso2.balana.cond.cluster.ModFunctionCluster;
import org.wso2.balana.cond.cluster.MultiplyFunctionCluster;
import org.wso2.balana.cond.cluster.NOfFunctionCluster;
import org.wso2.balana.cond.cluster.NotFunctionCluster;
import org.wso2.balana.cond.cluster.NumericConvertFunctionCluster;
import org.wso2.balana.cond.cluster.RoundFunctionCluster;
import org.wso2.balana.cond.cluster.StringFunctionCluster;
import org.wso2.balana.cond.cluster.StringNormalizeFunctionCluster;
import org.wso2.balana.cond.cluster.SubtractFunctionCluster;
import org.wso2.balana.cond.cluster.xacml3.StringComparingFunctionCluster;
import org.wso2.balana.cond.cluster.xacml3.StringConversionFunctionCluster;
import org.wso2.balana.cond.cluster.xacml3.StringCreationFunctionCluster;
import org.wso2.balana.cond.cluster.xacml3.SubStringFunctionCluster;
import org.wso2.balana.cond.cluster.xacml3.XACML3HigherOrderFunctionCluster;
import org.wso2.balana.cond.cluster.xacml3.XPathFunctionCluster;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* This factory supports the standard set of functions specified in XACML 1.x and 2.0. It is the
* default factory used by the system, and imposes a singleton pattern insuring that there is only
* ever one instance of this class.
* <p>
* Note that because this supports only the standard functions, this factory does not allow the
* addition of any other functions. If you call <code>addFunction</code> on an instance of this
* class, an exception will be thrown. If you need a standard factory that is modifiable, you can
* either create a new <code>BaseFunctionFactory</code> (or some other implementation of
* <code>FunctionFactory</code>) populated with the standard functions from
* <code>getStandardFunctions</code> or you can use <code>getNewFactoryProxy</code> to get a proxy
* containing a new, modifiable set of factories.
*
* @since 1.2
* @author Seth Proctor
*/
public class StandardFunctionFactory extends BaseFunctionFactory {
// the three singleton instances
private static volatile StandardFunctionFactory targetFactory = null;
private static volatile StandardFunctionFactory conditionFactory = null;
private static volatile StandardFunctionFactory generalFactory = null;
// the three function sets/maps that we use internally
private static Set<Function> targetFunctions = null;
private static Set<Function> conditionFunctions = null;
private static Set<Function> generalFunctions = null;
private static Map<URI, FunctionProxy> targetAbstractFunctions = null;
private static Map<URI, FunctionProxy> conditionAbstractFunctions = null;
private static Map<URI, FunctionProxy> generalAbstractFunctions = null;
// the static sets of supported identifiers for each XACML version
private static Set supportedV1Functions;
private static Set supportedV2Functions;
// the set/map used by each singleton factory instance
private Set supportedFunctions = null;
private Map supportedAbstractFunctions = null;
// the logger we'll use for all messages
private static final Log logger = LogFactory.getLog(StandardFunctionFactory.class);
/**
* Creates a new StandardFunctionFactory, making sure that the default maps are initialized
* correctly. Standard factories can't be modified, so there is no notion of supersetting since
* that's only used for correctly propagating new functions.
*/
private StandardFunctionFactory(Set supportedFunctions, Map supportedAbstractFunctions) {
super(supportedFunctions, supportedAbstractFunctions);
this.supportedFunctions = supportedFunctions;
this.supportedAbstractFunctions = supportedAbstractFunctions;
}
/**
* Private initializer for the target functions. This is only ever called once.
*/
private static void initTargetFunctions() {
if (logger.isDebugEnabled()) {
logger.debug("Initializing standard Target functions");
}
targetFunctions = new HashSet<Function>();
// add EqualFunction
targetFunctions.addAll((new EqualFunctionCluster()).getSupportedFunctions());
// add LogicalFunction
targetFunctions.addAll((new LogicalFunctionCluster()).getSupportedFunctions());
// add NOfFunction
targetFunctions.addAll((new NOfFunctionCluster()).getSupportedFunctions());
// add NotFunction
targetFunctions.addAll((new NotFunctionCluster()).getSupportedFunctions());
// add ComparisonFunction
targetFunctions.addAll((new ComparisonFunctionCluster()).getSupportedFunctions());
// add MatchFunction
targetFunctions.addAll((new MatchFunctionCluster()).getSupportedFunctions());
// add 3.0 Comparison Functions
targetFunctions.addAll((new StringComparingFunctionCluster().getSupportedFunctions()));
targetAbstractFunctions = new HashMap(); // TODO ??
}
/**
* Private initializer for the condition functions. This is only ever called once.
*/
private static void initConditionFunctions() {
if (logger.isDebugEnabled()) {
logger.debug("Initializing standard Condition functions");
}
if (targetFunctions == null)
initTargetFunctions();
conditionFunctions = new HashSet<Function>(targetFunctions);
// add condition function TimeInRange
conditionFunctions.add(new TimeInRangeFunction());
// add condition function IPInRange
conditionFunctions.add(new IPInRangeFunction());
// add condition functions from BagFunction
conditionFunctions.addAll((new ConditionBagFunctionCluster()).getSupportedFunctions());
// add condition functions from SetFunction
conditionFunctions.addAll((new ConditionSetFunctionCluster()).getSupportedFunctions());
// add condition functions from HigherOrderFunction
conditionFunctions.addAll((new HigherOrderFunctionCluster()).getSupportedFunctions());
conditionFunctions.addAll((new XACML3HigherOrderFunctionCluster()).getSupportedFunctions());
conditionAbstractFunctions = new HashMap<URI, FunctionProxy>(targetAbstractFunctions);// TODO ??
}
/**
* Private initializer for the general functions. This is only ever called once.
*/
private static void initGeneralFunctions() {
if (logger.isDebugEnabled()) {
logger.debug("Initializing standard General functions");
}
if (conditionFunctions == null)
initConditionFunctions();
generalFunctions = new HashSet<Function>(conditionFunctions);
// add AddFunction
generalFunctions.addAll((new AddFunctionCluster()).getSupportedFunctions());
// add SubtractFunction
generalFunctions.addAll((new SubtractFunctionCluster()).getSupportedFunctions());
// add MultiplyFunction
generalFunctions.addAll((new MultiplyFunctionCluster()).getSupportedFunctions());
// add DivideFunction
generalFunctions.addAll((new DivideFunctionCluster()).getSupportedFunctions());
// add ModFunction
generalFunctions.addAll((new ModFunctionCluster()).getSupportedFunctions());
// add AbsFunction
generalFunctions.addAll((new AbsFunctionCluster()).getSupportedFunctions());
// add RoundFunction
generalFunctions.addAll((new RoundFunctionCluster()).getSupportedFunctions());
// add FloorFunction
generalFunctions.addAll((new FloorFunctionCluster()).getSupportedFunctions());
// add DateMathFunction
generalFunctions.addAll((new DateMathFunctionCluster()).getSupportedFunctions());
// add general functions from BagFunction
generalFunctions.addAll((new GeneralBagFunctionCluster()).getSupportedFunctions());
// add NumericConvertFunction
generalFunctions.addAll((new NumericConvertFunctionCluster()).getSupportedFunctions());
// add StringNormalizeFunction
generalFunctions.addAll((new StringNormalizeFunctionCluster()).getSupportedFunctions());
// add general functions from SetFunction
generalFunctions.addAll((new GeneralSetFunctionCluster()).getSupportedFunctions());
// add the XACML 2.0 string functions
generalFunctions.addAll((new StringFunctionCluster()).getSupportedFunctions());
// add the XACML 3.0 start with functions
generalFunctions.addAll((new StringComparingFunctionCluster()).getSupportedFunctions());
// add the XACML 3.0 start with functions
generalFunctions.addAll((new StringConversionFunctionCluster()).getSupportedFunctions());
// add the XACML 3.0 start with functions
generalFunctions.addAll((new SubStringFunctionCluster()).getSupportedFunctions());
// add the XACML 3.0 start with functions
generalFunctions.addAll((new StringCreationFunctionCluster()).getSupportedFunctions());
// add the XACML 3.0 start with functions
generalFunctions.addAll((new XPathFunctionCluster()).getSupportedFunctions());
generalAbstractFunctions = new HashMap<URI, FunctionProxy>(conditionAbstractFunctions); // TODO
// add the map function's proxy
try {
generalAbstractFunctions.put(new URI(MapFunction.NAME_MAP), new MapFunctionProxy());
} catch (URISyntaxException e) {
// this shouldn't ever happen, but just in case...
throw new IllegalArgumentException("invalid function name");
}
}
/**
* Returns a FunctionFactory that will only provide those functions that are usable in Target
* matching. This method enforces a singleton model, meaning that this always returns the same
* instance, creating the factory if it hasn't been requested before. This is the default model
* used by the <code>FunctionFactory</code>, ensuring quick access to this factory.
*
* @return a <code>FunctionFactory</code> for target functions
*/
public static StandardFunctionFactory getTargetFactory() {
if (targetFactory == null) {
synchronized (StandardFunctionFactory.class) {
if (targetFunctions == null)
initTargetFunctions();
if (targetFactory == null)
targetFactory = new StandardFunctionFactory(targetFunctions,
targetAbstractFunctions);
}
}
return targetFactory;
}
/**
* Returns a FuntionFactory that will only provide those functions that are usable in the root
* of the Condition. These Functions are a superset of the Target functions. This method
* enforces a singleton model, meaning that this always returns the same instance, creating the
* factory if it hasn't been requested before. This is the default model used by the
* <code>FunctionFactory</code>, ensuring quick access to this factory.
*
* @return a <code>FunctionFactory</code> for condition functions
*/
public static StandardFunctionFactory getConditionFactory() {
if (conditionFactory == null) {
synchronized (StandardFunctionFactory.class) {
if (conditionFunctions == null)
initConditionFunctions();
if (conditionFactory == null)
conditionFactory = new StandardFunctionFactory(conditionFunctions,
conditionAbstractFunctions);
}
}
return conditionFactory;
}
/**
* Returns a FunctionFactory that provides access to all the functions. These Functions are a
* superset of the Condition functions. This method enforces a singleton model, meaning that
* this always returns the same instance, creating the factory if it hasn't been requested
* before. This is the default model used by the <code>FunctionFactory</code>, ensuring quick
* access to this factory.
*
* @return a <code>FunctionFactory</code> for all functions
*/
public static StandardFunctionFactory getGeneralFactory() {
if (generalFactory == null) {
synchronized (StandardFunctionFactory.class) {
if (generalFunctions == null) {
initGeneralFunctions();
generalFactory = new StandardFunctionFactory(generalFunctions,
generalAbstractFunctions);
}
}
}
return generalFactory;
}
/**
* Returns the identifiers supported for the given version of XACML. Because this factory
* supports identifiers from all versions of the XACML specifications, this method is useful for
* getting a list of which specific identifiers are supported by a given version of XACML.
*
* @param xacmlVersion a standard XACML identifier string, as provided in
* <code>PolicyMetaData</code>
*
* @return a <code>Set</code> of identifiers
*
* @throws UnknownIdentifierException if the version string is unknown
*/
public static Set getStandardFunctions(String xacmlVersion) {
// FIXME: collecting the identifiers needs to be implemented..
throw new RuntimeException("This method isn't implemented yet.");
}
/**
* Returns the set of abstract functions that this standard factory supports as a mapping of
* identifier to proxy.
*
* @return a <code>Map</code> mapping <code>URI</code>s to <code>FunctionProxy</code>s
*/
public static Map getStandardAbstractFunctions(String xacmlVersion) {
// FIXME: collecting the identifiers needs to be implemented..
throw new RuntimeException("This method isn't implemented yet.");
}
/**
* A convenience method that returns a proxy containing newly created instances of
* <code>BaseFunctionFactory</code>s that are correctly supersetted and contain the standard
* functions and abstract functions. These factories allow adding support for new functions.
*
* @return a new proxy containing new factories supporting the standard functions
*/
public static FunctionFactoryProxy getNewFactoryProxy() {
// first off, make sure everything's been initialized
getGeneralFactory();
// now create the new instances
FunctionFactory newGeneral = new BaseFunctionFactory(generalFunctions,
generalAbstractFunctions);
FunctionFactory newCondition = new BaseFunctionFactory(newGeneral, conditionFunctions,
conditionAbstractFunctions);
FunctionFactory newTarget = new BaseFunctionFactory(newCondition, targetFunctions,
targetAbstractFunctions);
return new BasicFunctionFactoryProxy(newTarget, newCondition, newGeneral);
}
/**
* Always throws an exception, since support for new functions may not be added to a standard
* factory.
*
* @param function the <code>Function</code> to add to the factory
*
* @throws UnsupportedOperationException always
*/
public void addFunction(Function function) throws IllegalArgumentException {
throw new UnsupportedOperationException("a standard factory cannot "
+ "support new functions");
}
/**
* Always throws an exception, since support for new functions may not be added to a standard
* factory.
*
* @param proxy the <code>FunctionProxy</code> to add to the factory
* @param identity the function's identifier
*
* @throws UnsupportedOperationException always
*/
public void addAbstractFunction(FunctionProxy proxy, URI identity)
throws IllegalArgumentException {
throw new UnsupportedOperationException("a standard factory cannot "
+ "support new functions");
}
}
| 18,907 | 45.918114 | 104 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/xacml3/XPathFunction.java | /*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.cond.xacml3;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.wso2.balana.DOMHelper;
import org.wso2.balana.DefaultNamespaceContext;
import org.wso2.balana.XACMLConstants;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.BooleanAttribute;
import org.wso2.balana.attr.IntegerAttribute;
import org.wso2.balana.attr.xacml3.XPathAttribute;
import org.wso2.balana.cond.Evaluatable;
import org.wso2.balana.cond.EvaluationResult;
import org.wso2.balana.cond.FunctionBase;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.ctx.Status;
import org.wso2.balana.ctx.xacml3.XACML3EvaluationCtx;
import org.wso2.balana.xacml3.Attributes;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.*;
import java.util.*;
/**
* The class that implement all XPath based functions. An XPath expression evaluates to a node-set,
* which is a set of XML nodes that match the expression. All comparison or other operations on
* node-sets are performed in isolation of the particular function specified.
*/
public class XPathFunction extends FunctionBase {
/**
* Standard identifier for the xpath-node-count function.
*/
public static final String NAME_XPATH_NODE_COUNT = FUNCTION_NS_3 + "xpath-node-count";
/**
* Standard identifier for the xpath-node-match function.
*/
public static final String NAME_XPATH_NODE_MATCH = FUNCTION_NS_3 + "xpath-node-match";
/**
* Standard identifier for the xpath-node-equal function.
*/
public static final String NAME_XPATH_NODE_EQUAL = FUNCTION_NS_3 + "xpath-node-equal";
/**
* private identifiers for xpath-node-count function
*/
private static final int ID_XPATH_NODE_COUNT = 0;
/**
* private identifiers for xpath-node-match function.
*/
private static final int ID_XPATH_NODE_MATCH = 1;
/**
* private identifiers for xpath-node-equal function.
*/
private static final int ID_XPATH_NODE_EQUAL = 2;
/**
* Creates a new <code>StringFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public XPathFunction(String functionName) {
super(functionName, getId(functionName), XPathAttribute.identifier, false,
getNumArgs(functionName), getReturnType(functionName), false);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*
* @param functionName function name
* @return function id
*/
private static int getId(String functionName) {
if (functionName.equals(NAME_XPATH_NODE_COUNT)){
return ID_XPATH_NODE_COUNT;
} else if (functionName.equals(NAME_XPATH_NODE_EQUAL)){
return ID_XPATH_NODE_EQUAL;
} else if (functionName.equals(NAME_XPATH_NODE_MATCH)){
return ID_XPATH_NODE_MATCH;
} else {
throw new IllegalArgumentException("unknown divide function " + functionName);
}
}
/**
* Private helper that returns the return type for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*
* @param functionName function name
* @return identifier of the Data type
*/
private static String getReturnType(String functionName) {
if (functionName.equals(NAME_XPATH_NODE_COUNT)){
return IntegerAttribute.identifier;
} else {
return BooleanAttribute.identifier;
}
}
/**
* Private helper that returns the argument count for the given standard function. Note that
* this doesn't check on the return value since the method always is called after getId, so we
* assume that the function is present.
*
* @param functionName function name
* @return identifier of the Data type
*/
private static int getNumArgs(String functionName) {
if (functionName.equals(NAME_XPATH_NODE_COUNT)){
return 1;
} else {
return 2;
}
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set<String> getSupportedIdentifiers() {
Set<String> set = new HashSet<String>();
set.add(NAME_XPATH_NODE_COUNT);
set.add(NAME_XPATH_NODE_EQUAL);
set.add(NAME_XPATH_NODE_MATCH);
return set;
}
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null) {
return result;
}
switch (getFunctionId()) {
case ID_XPATH_NODE_COUNT: {
XPathAttribute xpathAttribute = ((XPathAttribute) argValues[0]);
String xpathValue = xpathAttribute.getValue();
String category = xpathAttribute.getXPathCategory();
Node contextNode = null;
// this must be XACML 3
List<Attributes> attributesSet = ((XACML3EvaluationCtx) context).getAttributes(category);
if(attributesSet != null && attributesSet.size() > 0){
// only one attributes can be there
Attributes attributes = attributesSet.get(0);
contextNode = attributes.getContent();
}
if(contextNode != null){
// now apply XPath
try {
NodeList nodeList = getXPathResults(contextNode, xpathValue);
return new EvaluationResult(new IntegerAttribute(nodeList.getLength()));
} catch (XPathExpressionException e) {
List<String> codes = new ArrayList<String>();
codes.add(Status.STATUS_SYNTAX_ERROR);
Status status = new Status(codes, e.getMessage());
return new EvaluationResult(status);
}
}
}
case ID_XPATH_NODE_EQUAL :{
//TODO
}
}
List<String> codes = new ArrayList<String>();
codes.add(Status.STATUS_SYNTAX_ERROR);
Status status = new Status(codes, "Not supported function");
return new EvaluationResult(status);
}
/**
* Gets Xpath results
*
* @param contextNode
* @param xpathValue
* @return
* @throws XPathExpressionException
*/
private NodeList getXPathResults(Node contextNode, String xpathValue)
throws XPathExpressionException {
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
//see if the request root is in a namespace
String namespace = contextNode.getNamespaceURI();
// name spaces are used, so we need to lookup the correct
// prefix to use in the search string
NamedNodeMap namedNodeMap = contextNode.getAttributes();
Map<String, String> nsMap = new HashMap<String, String>();
for (int i = 0; i < namedNodeMap.getLength(); i++) {
Node n = namedNodeMap.item(i);
// we found the matching namespace, so get the prefix
// and then break out
String prefix = DOMHelper.getLocalName(n);
String nodeValue= n.getNodeValue();
nsMap.put(prefix, nodeValue);
}
// if there is not any namespace is defined for content element, default XACML request
// name space would be there.
if(XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(namespace) ||
XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(namespace) ||
XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(namespace)){
nsMap.put("xacml", namespace);
}
NamespaceContext namespaceContext = new DefaultNamespaceContext(nsMap);
xpath.setNamespaceContext(namespaceContext);
XPathExpression expression = xpath.compile(xpathValue);
return (NodeList) expression.evaluate(contextNode, XPathConstants.NODESET);
}
}
| 9,459 | 35.10687 | 105 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/xacml3/StringCreationFunction.java | /*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.cond.xacml3;
import org.wso2.balana.attr.*;
import org.wso2.balana.cond.Evaluatable;
import org.wso2.balana.cond.EvaluationResult;
import org.wso2.balana.cond.FunctionBase;
import org.wso2.balana.ctx.EvaluationCtx;
import java.util.*;
/**
* String creation function that creates String from other data types
*/
public class StringCreationFunction extends FunctionBase {
/**
* Standard identifier for the string-from-boolean function.
*/
public static final String NAME_STRING_FROM_BOOLEAN = FUNCTION_NS_3 + "string-from-boolean";
/**
* Standard identifier for the string-from-double function.
*/
public static final String NAME_STRING_FROM_DOUBLE= FUNCTION_NS_3 + "string-from-double";
/**
* Standard identifier for the string-from-time function.
*/
public static final String NAME_STRING_FROM_TIME = FUNCTION_NS_3 + "string-from-time";
/**
* Standard identifier for the string-from-dateTime function.
*/
public static final String NAME_STRING_FROM_DATE_TIME = FUNCTION_NS_3 + "string-from-dateTime";
/**
* Standard identifier for the string-from-date function.
*/
public static final String NAME_STRING_FROM_DATE= FUNCTION_NS_3 + "string-from-date";
/**
* Standard identifier for the string-from-integer function.
*/
public static final String NAME_STRING_FROM_INTEGER = FUNCTION_NS_3 + "string-from-integer";
/**
* Standard identifier for the string-from-anyURI function.
*/
public static final String NAME_STRING_FROM_URI = FUNCTION_NS_3 + "string-from-anyURI";
/**
* Standard identifier for the string-from-dayTimeDuration function.
*/
public static final String NAME_STRING_FROM_DAYTIME_DURATION = FUNCTION_NS_3 + "string-from-dayTimeDuration";
/**
* Standard identifier for the string-from-yearMonthDuration function.
*/
public static final String NAME_STRING_FROM_YEAR_MONTH_DURATION = FUNCTION_NS_3 + "string-from-yearMonthDuration";
/**
* Standard identifier for the string-from-x500Name function.
*/
public static final String NAME_STRING_FROM_X500NAME = FUNCTION_NS_3 + "string-from-x500Name";
/**
* Standard identifier for the string-from-rfc822Name function.
*/
public static final String NAME_STRING_FROM_RFC822NAME = FUNCTION_NS_3 + "string-from-rfc822Name";
/**
* Standard identifier for the string-from-dnsName function.
*/
public static final String NAME_STRING_FROM_DNS = FUNCTION_NS_3 + "string-from-dnsName";
/**
* Standard identifier for the string-from-ipAddress function.
*/
public static final String NAME_STRING_FROM_IP_ADDRESS = FUNCTION_NS_3 + "string-from-ipAddress";
private static Map<String, String> dataTypeMap;
/**
* Static initializer sets up a map of standard function names to their associated argument
* data types
*/
static {
dataTypeMap = new HashMap<String, String>();
dataTypeMap.put(NAME_STRING_FROM_BOOLEAN, BooleanAttribute.identifier);
dataTypeMap.put(NAME_STRING_FROM_INTEGER, IntegerAttribute.identifier);
dataTypeMap.put(NAME_STRING_FROM_DOUBLE, DoubleAttribute.identifier);
dataTypeMap.put(NAME_STRING_FROM_DATE, DateAttribute.identifier);
dataTypeMap.put(NAME_STRING_FROM_TIME, TimeAttribute.identifier);
dataTypeMap.put(NAME_STRING_FROM_DATE_TIME, DateTimeAttribute.identifier);
dataTypeMap.put(NAME_STRING_FROM_DAYTIME_DURATION, DayTimeDurationAttribute.identifier);
dataTypeMap.put(NAME_STRING_FROM_YEAR_MONTH_DURATION, YearMonthDurationAttribute.identifier);
dataTypeMap.put(NAME_STRING_FROM_URI, AnyURIAttribute.identifier);
dataTypeMap.put(NAME_STRING_FROM_X500NAME, X500NameAttribute.identifier);
dataTypeMap.put(NAME_STRING_FROM_RFC822NAME, RFC822NameAttribute.identifier);
dataTypeMap.put(NAME_STRING_FROM_IP_ADDRESS, IPAddressAttribute.identifier);
dataTypeMap.put(NAME_STRING_FROM_DNS, DNSNameAttribute.identifier);
}
/**
* Creates a new <code>EqualFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*/
public StringCreationFunction(String functionName) {
super(functionName, 0, getArgumentType(functionName), false, 1, StringAttribute.identifier, false);
}
/**
* Private helper that returns the parameter type used for the given standard function.
*
* @param functionName function name
* @return identifier of the Data type
*/
private static String getArgumentType(String functionName) {
return dataTypeMap.get(functionName);
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set<String> getSupportedIdentifiers() {
return Collections.unmodifiableSet(dataTypeMap.keySet());
}
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null){
return result;
}
return new EvaluationResult(new StringAttribute(argValues[0].encode()));
}
}
| 6,246 | 36.63253 | 118 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/xacml3/StringConversionFunction.java | /*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.cond.xacml3;
import org.wso2.balana.Balana;
import org.wso2.balana.ParsingException;
import org.wso2.balana.UnknownIdentifierException;
import org.wso2.balana.attr.*;
import org.wso2.balana.cond.Evaluatable;
import org.wso2.balana.cond.EvaluationResult;
import org.wso2.balana.cond.FunctionBase;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.ctx.Status;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
/**
* String conversion functions that creates different data-types from String type
*/
public class StringConversionFunction extends FunctionBase{
/**
* Standard identifier for the boolean-from-string function.
*/
public static final String NAME_BOOLEAN_FROM_STRING = FUNCTION_NS_3 + "boolean-from-string";
/**
* Standard identifier for the integer-from-boolean function.
*/
public static final String NAME_INTEGER_FROM_STRING = FUNCTION_NS_3 + "integer-from-string";
/**
* Standard identifier for the integer-from-boolean function.
*/
public static final String NAME_DOUBLE_FROM_STRING = FUNCTION_NS_3 + "double-from-string";
/**
* Standard identifier for the integer-from-boolean function.
*/
public static final String NAME_TIME_FROM_STRING = FUNCTION_NS_3 + "time-from-string";
/**
* Standard identifier for the integer-from-boolean function.
*/
public static final String NAME_DATE_FROM_STRING = FUNCTION_NS_3 + "date-from-string";
/**
* Standard identifier for the integer-from-boolean function.
*/
public static final String NAME_DATE_TIME_FROM_STRING = FUNCTION_NS_3 + "dateTime-from-string";
/**
* Standard identifier for the integer-from-boolean function.
*/
public static final String NAME_URI_FROM_STRING = FUNCTION_NS_3 + "anyURI-from-string";
/**
* Standard identifier for the integer-from-boolean function.
*/
public static final String NAME_DAYTIME_DURATION_FROM_STRING = FUNCTION_NS_3 + "dayTimeDuration-from-string";
/**
* Standard identifier for the integer-from-boolean function.
*/
public static final String NAME_YEAR_MONTH_DURATION_FROM_STRING = FUNCTION_NS_3 + "yearMonthDuration-from-string";
/**
* Standard identifier for the integer-from-boolean function.
*/
public static final String NAME_X500NAME_FROM_STRING = FUNCTION_NS_3 + "x500Name-from-string";
/**
* Standard identifier for the integer-from-boolean function.
*/
public static final String NAME_RFC822_FROM_STRING = FUNCTION_NS_3 + "rfc822Name-from-string";
/**
* Standard identifier for the integer-from-boolean function.
*/
public static final String NAME_IP_ADDRESS_FROM_STRING = FUNCTION_NS_3 + "ipAddress-from-string";
/**
* Standard identifier for the integer-from-boolean function.
*/
public static final String NAME_DNS_FROM_STRING = FUNCTION_NS_3 + "dnsName-from-string";
private static Map<String, String> dataTypeMap;
/**
* Static initializer sets up a map of standard function names to their associated return
* data types
*/
static {
dataTypeMap = new HashMap<String, String>();
dataTypeMap.put(NAME_BOOLEAN_FROM_STRING, BooleanAttribute.identifier);
dataTypeMap.put(NAME_INTEGER_FROM_STRING, IntegerAttribute.identifier);
dataTypeMap.put(NAME_DOUBLE_FROM_STRING, DoubleAttribute.identifier);
dataTypeMap.put(NAME_DATE_FROM_STRING, DateAttribute.identifier);
dataTypeMap.put(NAME_TIME_FROM_STRING, TimeAttribute.identifier);
dataTypeMap.put(NAME_DATE_TIME_FROM_STRING, DateTimeAttribute.identifier);
dataTypeMap.put(NAME_DAYTIME_DURATION_FROM_STRING, DayTimeDurationAttribute.identifier);
dataTypeMap.put(NAME_YEAR_MONTH_DURATION_FROM_STRING, YearMonthDurationAttribute.identifier);
dataTypeMap.put(NAME_URI_FROM_STRING, AnyURIAttribute.identifier);
dataTypeMap.put(NAME_X500NAME_FROM_STRING, X500NameAttribute.identifier);
dataTypeMap.put(NAME_RFC822_FROM_STRING, RFC822NameAttribute.identifier);
dataTypeMap.put(NAME_IP_ADDRESS_FROM_STRING, IPAddressAttribute.identifier);
dataTypeMap.put(NAME_DNS_FROM_STRING, DNSNameAttribute.identifier);
}
/**
* Creates a new <code>EqualFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*/
public StringConversionFunction(String functionName) {
super(functionName, 0, StringAttribute.identifier, false, 1, getReturnType(functionName), false);
}
/**
* Private helper that returns the return type used for the given standard function.
*
* @param functionName function name
* @return identifier of the Data type
*/
private static String getReturnType(String functionName) {
return dataTypeMap.get(functionName);
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set<String> getSupportedIdentifiers() {
return Collections.unmodifiableSet(dataTypeMap.keySet());
}
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null){
return result;
}
try {
URI dataType = new URI (dataTypeMap.get(getFunctionName()));
AttributeValue value = Balana.getInstance().getAttributeFactory().createValue(dataType,
argValues[0].encode());
return new EvaluationResult(value);
} catch (URISyntaxException e) {
List<String> code = new ArrayList<String>();
code.add(Status.STATUS_PROCESSING_ERROR);
return new EvaluationResult(new Status(code, e.getMessage()));
} catch (ParsingException e) {
List<String> code = new ArrayList<String>();
code.add(Status.STATUS_PROCESSING_ERROR);
return new EvaluationResult(new Status(code, e.getMessage()));
} catch (UnknownIdentifierException e) {
List<String> code = new ArrayList<String>();
code.add(Status.STATUS_PROCESSING_ERROR);
return new EvaluationResult(new Status(code, e.getMessage()));
}
}
}
| 7,319 | 37.93617 | 118 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/xacml3/StringComparingFunction.java | /*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.cond.xacml3;
import org.wso2.balana.attr.*;
import org.wso2.balana.cond.Evaluatable;
import org.wso2.balana.cond.EvaluationResult;
import org.wso2.balana.cond.FunctionBase;
import org.wso2.balana.ctx.EvaluationCtx;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A class that implements all the *-start-with functions. It takes two arguments of given
* data-type and returns a <code>BooleanAttribute</code> data type.
* The result shall be true if the second string begins with the first string, and false otherwise.
*/
public class StringComparingFunction extends FunctionBase {
/**
* Standard identifier for the string-starts-with function.
*/
public static final String NAME_STRING_START_WITH = FUNCTION_NS_3 + "string-starts-with";
/**
* Standard identifier for the anyURI-starts-with function.
*/
public static final String NAME_ANY_URI_START_WITH = FUNCTION_NS_3 + "anyURI-starts-with";
/**
* Standard identifier for the string-starts-with function.
*/
public static final String NAME_STRING_ENDS_WITH = FUNCTION_NS_3 + "string-ends-with";
/**
* Standard identifier for the anyURI-starts-with function.
*/
public static final String NAME_ANY_URI_ENDS_WITH = FUNCTION_NS_3 + "anyURI-ends-with";
/**
* Standard identifier for the string-starts-with function.
*/
public static final String NAME_STRING_CONTAIN = FUNCTION_NS_3 + "string-contains";
/**
* Standard identifier for the anyURI-starts-with function.
*/
public static final String NAME_ANY_URI_CONTAIN = FUNCTION_NS_3 + "anyURI-contains";
// internal identifiers for each of the supported functions
private static final int ID_STRING_START_WITH = 0;
private static final int ID_ANY_URI_START_WITH = 1;
private static final int ID_STRING_ENDS_WITH = 2;
private static final int ID_ANY_URI_ENDS_WITH = 3;
private static final int ID_STRING_CONTAIN = 4;
private static final int ID_ANY_URI_CONTAIN = 5;
/**
* Creates a new <code>AddFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public StringComparingFunction(String functionName) {
super(functionName, getId(functionName), getArgumentType(functionName), false, 2,
BooleanAttribute.identifier, false);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*
* @param functionName function name
* @return function id
*/
private static int getId(String functionName) {
if (functionName.equals(NAME_STRING_START_WITH)){
return ID_STRING_START_WITH;
} else if (functionName.equals(NAME_ANY_URI_START_WITH)){
return ID_ANY_URI_START_WITH;
} else if (functionName.equals(NAME_STRING_ENDS_WITH)){
return ID_STRING_ENDS_WITH;
} else if (functionName.equals(NAME_ANY_URI_ENDS_WITH)){
return ID_ANY_URI_ENDS_WITH;
} else if (functionName.equals(NAME_STRING_CONTAIN)){
return ID_STRING_CONTAIN;
} else if (functionName.equals(NAME_ANY_URI_CONTAIN)){
return ID_ANY_URI_CONTAIN;
} else {
throw new IllegalArgumentException("unknown start-with function " + functionName);
}
}
/**
* Private helper that returns the type used for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*
* @param functionName function name
* @return identifier of the Data type
*/
private static String getArgumentType(String functionName) {
if (functionName.equals(NAME_STRING_START_WITH) || functionName.equals(NAME_STRING_ENDS_WITH)
|| functionName.equals(NAME_STRING_CONTAIN)){
return StringAttribute.identifier;
} else {
return AnyURIAttribute.identifier;
}
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set<String> getSupportedIdentifiers() {
Set<String> set = new HashSet<String>();
set.add(NAME_STRING_START_WITH);
set.add(NAME_ANY_URI_START_WITH);
set.add(NAME_STRING_ENDS_WITH);
set.add(NAME_ANY_URI_ENDS_WITH);
set.add(NAME_STRING_CONTAIN);
set.add(NAME_ANY_URI_CONTAIN);
return set;
}
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null) {
return result;
}
int id = getFunctionId();
if(id == ID_STRING_START_WITH || id == ID_ANY_URI_START_WITH){
// do not want to check for anyURI and String data types. As both attribute values would
// returns String data type after encode() is done,
return EvaluationResult.getInstance(argValues[1].encode().
startsWith(argValues[0].encode()));
} else if(id == ID_STRING_ENDS_WITH || id == ID_ANY_URI_ENDS_WITH){
// do not want to check for anyURI and String data types. As both attribute values would
// returns String data type after encode() is done,
return EvaluationResult.getInstance(argValues[1].encode().
endsWith(argValues[0].encode()));
} else {
// do not want to check for anyURI and String data types. As both attribute values would
// returns String data type after encode() is done,
return EvaluationResult.getInstance(argValues[1].encode().
contains(argValues[0].encode()));
}
}
}
| 7,051 | 37.326087 | 101 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/xacml3/XACML3HigherOrderFunction.java | /*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.cond.xacml3;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.BagAttribute;
import org.wso2.balana.attr.BooleanAttribute;
import org.wso2.balana.cond.Evaluatable;
import org.wso2.balana.cond.EvaluationResult;
import org.wso2.balana.cond.Expression;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.FunctionBase;
import org.wso2.balana.ctx.EvaluationCtx;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Represents all of the XACML3 higher order functions. (any-of, all-of and any-of-any)
*/
public class XACML3HigherOrderFunction implements Function {
// Standard identifier for the any-of function.
public static final String NAME_ANY_OF = FunctionBase.FUNCTION_NS_3 + "any-of";
// Standard identifier for the all-of function.
public static final String NAME_ALL_OF = FunctionBase.FUNCTION_NS_3 + "all-of";
// Standard identifier for the any-of-any function.
public static final String NAME_ANY_OF_ANY = FunctionBase.FUNCTION_NS_3 + "any-of-any";
// Internal identifiers for each of the supported functions.
private static final int ID_ANY_OF = 0;
private static final int ID_ALL_OF = 1;
private static final int ID_ANY_OF_ANY = 2;
// Internal mapping of names to ids.
private final static Map<String, Integer> ID_MAP;
private int functionId;
private URI identifier;
private static URI returnTypeURI;
private static RuntimeException earlyException;
// Try to create the return type URI, and also setup the id map.
static {
try {
returnTypeURI = new URI(BooleanAttribute.identifier);
} catch (URISyntaxException e) {
earlyException = new IllegalArgumentException(e);
}
Map<String, Integer> nameIdMap = new HashMap<>();
nameIdMap.put(NAME_ANY_OF, ID_ANY_OF);
nameIdMap.put(NAME_ALL_OF, ID_ALL_OF);
nameIdMap.put(NAME_ANY_OF_ANY, ID_ANY_OF_ANY);
ID_MAP = Collections.unmodifiableMap(nameIdMap);
}
/**
* Creates a new instance of the given function.
*
* @param functionName the function to create
* @throws IllegalArgumentException if the function is unknown
*/
public XACML3HigherOrderFunction(String functionName) {
// Try to get the function's identifier.
Integer i = ID_MAP.get(functionName);
if (i == null) {
throw new IllegalArgumentException("Unknown function: " + functionName);
}
functionId = i;
// Setup the URI form of this function's identity.
try {
identifier = new URI(functionName);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Invalid URI", e);
}
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set getSupportedIdentifiers() {
return Collections.unmodifiableSet(ID_MAP.keySet());
}
@Override
public void checkInputs(List inputs) throws IllegalArgumentException {
Object[] list = inputs.toArray();
// First, check that we got the right number of parameters.
if (list.length < 2) {
throw new IllegalArgumentException("requires more than two inputs");
}
// Try to cast the first element into a function.
Function function;
if (list[0] instanceof Function) {
function = (Function) (list[0]);
} else {
throw new IllegalArgumentException("first arg to higher-order "
+ " function must be a function");
}
// Check that the function returns a boolean
if (!function.getReturnType().toString().equals(BooleanAttribute.identifier))
throw new IllegalArgumentException("higher-order function must "
+ "use a boolean function");
// Separate the remaining inputs into primitive data types or bags of primitive types.
List<Evaluatable> bagArgs = new ArrayList();
List<Evaluatable> args = new ArrayList();
for (int i = 1; i < list.length; i++) {
Evaluatable eval = (Evaluatable) (list[i]);
if (eval.returnsBag()) {
bagArgs.add(eval);
} else {
args.add(eval);
}
}
if (functionId == ID_ALL_OF || functionId == ID_ANY_OF) {
// The n-1 parameters SHALL be values of primitive data-types and one SHALL be a bag of a primitive
// data-type for any-of and all-of.
if (bagArgs.size() != 1) {
throw new IllegalArgumentException("Only one argument SHALL be a bag of a primitive data-type for " +
getIdentifier());
}
// The expression SHALL be evaluated as if the function named in the <Function> argument were applied
// to the n-1 non-bag arguments and each element of the bag argument for any-of and all-of.
for (Evaluatable arg : args) {
List<Evaluatable> inputForCheck = new ArrayList();
inputForCheck.add(arg);
inputForCheck.addAll(bagArgs);
function.checkInputsNoBag(inputForCheck);
}
} else {
// The remaining arguments are either primitive data types or bags of primitive types.
if (!args.isEmpty() && !bagArgs.isEmpty()) {
throw new IllegalArgumentException("The arguments can be are either primitive data types or " +
"bags of primitive types. " + getIdentifier());
}
// The expression SHALL be evaluated as if the function named in the <Function> argument was applied
// between every tuple of the cross product on all bags and the primitive values.
if (!args.isEmpty()) {
validateAnyOfAnyInput(args, function);
} else {
validateAnyOfAnyInput(bagArgs, function);
}
}
}
private void validateAnyOfAnyInput(List<Evaluatable> inputs, Function function) {
for (int i = 0; i < inputs.size(); i++) {
for (int j = i + 1; j < inputs.size(); j++) {
List<Evaluatable> inputForCheck = new ArrayList();
inputForCheck.add(inputs.get(i));
inputForCheck.add(inputs.get(j));
function.checkInputsNoBag(inputForCheck);
}
}
}
@Override
public void checkInputsNoBag(List inputs) throws IllegalArgumentException {
// This always throws an exception, since this function by definition must work on bags.
throw new IllegalArgumentException("higher-order functions require use of bags");
}
@Override
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
Iterator iterator = inputs.iterator();
// Get the first arg, which is the function.
Expression xpr = (Expression) (iterator.next());
Function function = null;
if (xpr instanceof Function) {
function = (Function) xpr;
}
// Separate the remaining inputs into primitive data types or bags of primitive types.
List<AttributeValue> args = new ArrayList<>();
List<BagAttribute> bagArgs = new ArrayList<>();
while (iterator.hasNext()) {
Evaluatable eval = (Evaluatable) (iterator.next());
EvaluationResult result = eval.evaluate(context);
if (result.indeterminate()) {
return result;
}
if (result.getAttributeValue().returnsBag()) {
bagArgs.add((BagAttribute) (result.getAttributeValue()));
} else {
args.add(result.getAttributeValue());
}
}
switch (functionId) {
case ID_ANY_OF:
return anyAndAllHelper(context, function, args, bagArgs.get(0), false);
case ID_ALL_OF:
return anyAndAllHelper(context, function, args, bagArgs.get(0), true);
case ID_ANY_OF_ANY:
return anyOfAny(context, function, args, bagArgs);
}
return null;
}
private EvaluationResult anyAndAllHelper(EvaluationCtx context, Function function, List<AttributeValue> values,
BagAttribute bag, boolean isAllFunction) {
Iterator it = bag.iterator();
while (it.hasNext()) {
AttributeValue bagValue = (AttributeValue) (it.next());
for (AttributeValue value : values) {
EvaluationResult result = getEvaluationResult(context, function, value, bagValue, isAllFunction);
if (result != null) {
return result;
}
}
}
return new EvaluationResult(BooleanAttribute.getInstance(isAllFunction));
}
private EvaluationResult anyOfAny(EvaluationCtx context, Function function, List<AttributeValue> args,
List<BagAttribute> bagArgs) {
// The expression SHALL be evaluated as if the function named in the <Function> argument was applied
// between every tuple of the cross product on all bags and the primitive values, and the results were
// combined using "urn:oasis:names:tc:xacml:1.0:function:or"
EvaluationResult result = new EvaluationResult(BooleanAttribute.getInstance(false));
if (!args.isEmpty()) {
for (int i = 0; i < args.size() - 1; i++) {
AttributeValue value = args.get(i);
List<AttributeValue> bagValue = new ArrayList<>();
bagValue.add(value);
BagAttribute bagArg = new BagAttribute(value.getType(), bagValue);
result = anyAndAllHelper(context, function, args.subList(i + 1, args.size()), bagArg, false);
if (result.indeterminate() || ((BooleanAttribute) (result.getAttributeValue())).getValue()) {
return result;
}
}
return new EvaluationResult(BooleanAttribute.getInstance(false));
}
if (!bagArgs.isEmpty()) {
for (int i = 0; i < bagArgs.size(); i++) {
for (int j = i + 1; j < bagArgs.size(); j++) {
Iterator iIterator = bagArgs.get(i).iterator();
while (iIterator.hasNext()) {
AttributeValue iValue = (AttributeValue) (iIterator.next());
Iterator jIterator = bagArgs.get(j).iterator();
while (jIterator.hasNext()) {
AttributeValue jValue = (AttributeValue) (jIterator.next());
result = getEvaluationResult(context, function, jValue, iValue, false);
if (result != null && (result.indeterminate() ||
((BooleanAttribute) (result.getAttributeValue())).getValue())) {
return result;
}
}
}
}
}
return new EvaluationResult(BooleanAttribute.getInstance(false));
}
return null;
}
private EvaluationResult getEvaluationResult(EvaluationCtx context, Function function, AttributeValue val1,
AttributeValue val2, boolean isAllFunction) {
List<Evaluatable> params = new ArrayList<>();
params.add(val1);
params.add(val2);
EvaluationResult result = function.evaluate(params, context);
if (result.indeterminate()) {
return result;
}
BooleanAttribute bool = (BooleanAttribute) (result.getAttributeValue());
if (bool.getValue() != isAllFunction) {
return result;
}
return null;
}
@Override
public URI getIdentifier() {
return identifier;
}
@Override
public URI getType() {
return getReturnType();
}
@Override
public URI getReturnType() {
if (earlyException != null) {
throw earlyException;
}
return returnTypeURI;
}
@Override
public boolean returnsBag() {
return false;
}
@Override
public String encode() {
StringBuilder builder = new StringBuilder();
encode(builder);
return builder.toString();
}
@Override
public void encode(StringBuilder builder) {
builder.append("<Function FunctionId=\"").append(getIdentifier().toString()).append("\"/>\n");
}
}
| 13,728 | 36.613699 | 117 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/xacml3/SubStringFunction.java | /*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.cond.xacml3;
import org.wso2.balana.attr.AnyURIAttribute;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.StringAttribute;
import org.wso2.balana.cond.Evaluatable;
import org.wso2.balana.cond.EvaluationResult;
import org.wso2.balana.cond.FunctionBase;
import org.wso2.balana.ctx.EvaluationCtx;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Sub string functions .
*/
public class SubStringFunction extends FunctionBase {
/**
* Standard identifier for the string-sub string function.
*/
public static final String NAME_STRING_SUB_STRING = FUNCTION_NS_3 + "string-substring";
/**
* Standard identifier for the any uri sub string function.
*/
public static final String NAME_ANY_URI_SUB_STRING = FUNCTION_NS_3 + "anyURI-substring";
/**
* private identifiers for the supported functions
*/
private static final int ID_STRING_SUB_STRING = 0;
/**
* private identifiers for the supported functions
*/
private static final int ID_ANY_URI_SUB_STRING = 1;
/**
* Creates a new <code>StringFunction</code> object.
*
* @param functionName the standard XACML name of the function to be handled by this object,
* including the full namespace
*
* @throws IllegalArgumentException if the function is unknown
*/
public SubStringFunction(String functionName) {
super(functionName, getId(functionName), getArgumentType(functionName), false, 3,
StringAttribute.identifier, false);
}
/**
* Private helper that returns the internal identifier used for the given standard function.
*
* @param functionName function name
* @return function id
*/
private static int getId(String functionName) {
if (functionName.equals(NAME_STRING_SUB_STRING)){
return ID_STRING_SUB_STRING;
} else if (functionName.equals(NAME_ANY_URI_SUB_STRING)){
return ID_ANY_URI_SUB_STRING;
} else {
throw new IllegalArgumentException("unknown divide function " + functionName);
}
}
/**
* Private helper that returns the type used for the given standard function. Note that this
* doesn't check on the return value since the method always is called after getId, so we assume
* that the function is present.
*
* @param functionName function name
* @return identifier of the Data type
*/
private static String getArgumentType(String functionName) {
if (functionName.equals(NAME_STRING_SUB_STRING)){
return StringAttribute.identifier;
} else {
return AnyURIAttribute.identifier;
}
}
/**
* Returns a <code>Set</code> containing all the function identifiers supported by this class.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public static Set<String> getSupportedIdentifiers() {
Set<String> set = new HashSet<String>();
set.add(NAME_STRING_SUB_STRING);
set.add(NAME_ANY_URI_SUB_STRING);
return set;
}
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null) {
return result;
}
String processedString = argValues[0].encode().substring(Integer.parseInt(argValues[1].encode()),
Integer.parseInt(argValues[2].encode()));
return new EvaluationResult(new StringAttribute(processedString));
}
}
| 4,450 | 32.719697 | 105 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/MatchFunctionCluster.java | /*
* @(#)MatchFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.MatchFunction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>MatchFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class MatchFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = MatchFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new MatchFunction((String) (it.next())));
return set;
}
}
| 2,505 | 38.15625 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/NumericConvertFunctionCluster.java | /*
* @(#)NumericConvertFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.NumericConvertFunction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>NumericConvertFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class NumericConvertFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = NumericConvertFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new NumericConvertFunction((String) (it.next())));
return set;
}
}
| 2,559 | 39 | 82 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/FunctionCluster.java | /*
* @(#)FunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import java.util.Set;
/**
* Interface used by classes that support more than one function. It's a common design model to have
* a single class support more than one XACML function. In those cases, you should provide a proxy
* that implements <code>FunctionCluster</code> in addition to the <code>Function</code>. This is
* particularly important for the run-time configuration system, which uses this interface to create
* "clusters" of functions and therefore can use a smaller configuration file.
*
* @since 1.2
* @author Seth Proctor
*/
public interface FunctionCluster {
/**
* Returns a single instance of each of the functions supported by some class. The
* <code>Set</code> must contain instances of <code>Function</code>, and it must be both
* non-null and non-empty. It may contain only a single <code>Function</code>.
* <p>
* Note that this is only used to return concrete <code>Function</code>s. It may not be used to
* report abstract functions.
*
* @return the functions supported by this class
*/
public Set<Function> getSupportedFunctions();
}
| 3,021 | 44.104478 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/StringNormalizeFunctionCluster.java | /*
* @(#)StringNormalizeFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.StringNormalizeFunction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>StringNormalizeFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class StringNormalizeFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = StringNormalizeFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new StringNormalizeFunction((String) (it.next())));
return set;
}
}
| 2,565 | 39.09375 | 83 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/MultiplyFunctionCluster.java | /*
* @(#)MultiplyFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.MultiplyFunction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>MultiplyFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class MultiplyFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = MultiplyFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new MultiplyFunction((String) (it.next())));
return set;
}
}
| 2,523 | 38.4375 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/ConditionBagFunctionCluster.java | /*
* @(#)ConditionBagFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.ConditionBagFunction;
import org.wso2.balana.cond.Function;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>ConditionBagFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class ConditionBagFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = ConditionBagFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new ConditionBagFunction((String) (it.next())));
return set;
}
}
| 2,547 | 38.8125 | 80 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/DateMathFunctionCluster.java | /*
* @(#)DateMathFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.DateMathFunction;
import org.wso2.balana.cond.Function;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>DateMathFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class DateMathFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function> ();
Iterator it = DateMathFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new DateMathFunction((String) (it.next())));
return set;
}
}
| 2,526 | 38.484375 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/EqualFunctionCluster.java | /*
* @(#)EqualFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.EqualFunction;
import org.wso2.balana.cond.Function;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>EqualFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class EqualFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = EqualFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new EqualFunction((String) (it.next())));
return set;
}
}
| 2,505 | 38.15625 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/FloorFunctionCluster.java | /*
* @(#)FloorFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.FloorFunction;
import org.wso2.balana.cond.Function;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>FloorFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class FloorFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = FloorFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new FloorFunction((String) (it.next())));
return set;
}
}
| 2,505 | 38.15625 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/SubtractFunctionCluster.java | /*
* @(#)SubtractFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.SubtractFunction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>SubtractFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class SubtractFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = SubtractFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new SubtractFunction((String) (it.next())));
return set;
}
}
| 2,523 | 38.4375 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/NOfFunctionCluster.java | /*
* @(#)NOfFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.NOfFunction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>NOfFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class NOfFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = NOfFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new NOfFunction((String) (it.next())));
return set;
}
}
| 2,493 | 37.96875 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/ModFunctionCluster.java | /*
* @(#)ModFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.ModFunction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>ModFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class ModFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = ModFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new ModFunction((String) (it.next())));
return set;
}
}
| 2,493 | 37.96875 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/AddFunctionCluster.java | /*
* @(#)AddFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.AddFunction;
import org.wso2.balana.cond.Function;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>AddFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class AddFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = AddFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new AddFunction((String) (it.next())));
return set;
}
}
| 2,493 | 37.96875 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/ConditionSetFunctionCluster.java | /*
* @(#)ConditionSetFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.ConditionSetFunction;
import org.wso2.balana.cond.Function;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>ConditionSetFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class ConditionSetFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = ConditionSetFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new ConditionSetFunction((String) (it.next())));
return set;
}
}
| 2,547 | 38.8125 | 80 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/GeneralBagFunctionCluster.java | /*
* @(#)GeneralBagFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.GeneralBagFunction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>GeneralBagFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class GeneralBagFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = GeneralBagFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new GeneralBagFunction((String) (it.next())));
return set;
}
}
| 2,537 | 38.65625 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/StringFunctionCluster.java |
/*
* @(#)StringFunctionCluster.java
*
* Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.StringFunction;
import org.wso2.balana.cond.URLStringCatFunction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>StringFunction</code>
* and <code>URLStringCatFunction</code>.
*
* @since 2.0
* @author Seth Proctor
*/
public class StringFunctionCluster implements FunctionCluster
{
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = StringFunction.getSupportedIdentifiers().
iterator();
while (it.hasNext())
set.add(new StringFunction((String)(it.next())));
set.add(new URLStringCatFunction());
return set;
}
}
| 2,661 | 35.972222 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/DivideFunctionCluster.java | /*
* @(#)DivideFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.DivideFunction;
import org.wso2.balana.cond.Function;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>DivideFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class DivideFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = DivideFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new DivideFunction((String) (it.next())));
return set;
}
}
| 2,511 | 38.25 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/LogicalFunctionCluster.java | /*
* @(#)LogicalFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.LogicalFunction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>LogicalFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class LogicalFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = LogicalFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new LogicalFunction((String) (it.next())));
return set;
}
}
| 2,517 | 38.34375 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/RoundFunctionCluster.java | /*
* @(#)RoundFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.RoundFunction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>RoundFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class RoundFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = RoundFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new RoundFunction((String) (it.next())));
return set;
}
}
| 2,505 | 38.15625 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/AbsFunctionCluster.java | /*
* @(#)AbsFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.AbsFunction;
import org.wso2.balana.cond.Function;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>AbsFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class AbsFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = AbsFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new AbsFunction((String) (it.next())));
return set;
}
}
| 2,493 | 37.96875 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/HigherOrderFunctionCluster.java | /*
* @(#)HigherOrderFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.HigherOrderFunction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>HigherOrderFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class HigherOrderFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = HigherOrderFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new HigherOrderFunction((String) (it.next())));
return set;
}
}
| 2,541 | 38.71875 | 79 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/ComparisonFunctionCluster.java | /*
* @(#)ComparisonFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.ComparisonFunction;
import org.wso2.balana.cond.Function;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>ComparisonFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class ComparisonFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = ComparisonFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new ComparisonFunction((String) (it.next())));
return set;
}
}
| 2,535 | 38.625 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/NotFunctionCluster.java | /*
* @(#)NotFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.NotFunction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>NotFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class NotFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = NotFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new NotFunction((String) (it.next())));
return set;
}
}
| 2,493 | 37.96875 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/GeneralSetFunctionCluster.java | /*
* @(#)GeneralSetFunctionCluster.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.cond.cluster;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.GeneralSetFunction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>GeneralSetFunction</code>.
*
* @since 1.2
* @author Seth Proctor
*/
public class GeneralSetFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
Iterator it = GeneralSetFunction.getSupportedIdentifiers().iterator();
while (it.hasNext())
set.add(new GeneralSetFunction((String) (it.next())));
return set;
}
}
| 2,535 | 38.625 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/xacml3/SubStringFunctionCluster.java | /*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.cond.cluster.xacml3;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.cluster.FunctionCluster;
import org.wso2.balana.cond.xacml3.SubStringFunction;
import java.util.HashSet;
import java.util.Set;
/**
* Clusters all the functions supported by <code>SubStringFunction</code>
*/
public class SubStringFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
for (String identifier : SubStringFunction.getSupportedIdentifiers()){
set.add(new SubStringFunction(identifier));
}
return set;
}
} | 1,342 | 31.756098 | 78 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/xacml3/StringCreationFunctionCluster.java | /*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.cond.cluster.xacml3;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.cluster.FunctionCluster;
import org.wso2.balana.cond.xacml3.StringCreationFunction;
import java.util.HashSet;
import java.util.Set;
/**
* Clusters all the functions supported by <code>StringCreationFunction</code>
*/
public class StringCreationFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
for (String identifier : StringCreationFunction.getSupportedIdentifiers()){
set.add(new StringCreationFunction(identifier));
}
return set;
}
} | 1,367 | 32.365854 | 83 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/xacml3/XPathFunctionCluster.java | /*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.cond.cluster.xacml3;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.cluster.FunctionCluster;
import org.wso2.balana.cond.xacml3.XPathFunction;
import java.util.HashSet;
import java.util.Set;
/**
* Clusters all the functions supported by <code>XPathFunction</code>
*/
public class XPathFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
for (String identifier : XPathFunction.getSupportedIdentifiers()){
set.add(new XPathFunction(identifier));
}
return set;
}
} | 1,321 | 32.05 | 74 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/xacml3/StringComparingFunctionCluster.java | /*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.cond.cluster.xacml3;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.cluster.FunctionCluster;
import org.wso2.balana.cond.xacml3.StringComparingFunction;
import java.util.HashSet;
import java.util.Set;
/**
* Clusters all the functions supported by <code>StringComparingFunction</code>
*/
public class StringComparingFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
for (String identifier : StringComparingFunction.getSupportedIdentifiers()){
set.add(new StringComparingFunction(identifier));
}
return set;
}
}
| 1,382 | 31.162791 | 84 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/xacml3/StringConversionFunctionCluster.java | /*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.cond.cluster.xacml3;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.cluster.FunctionCluster;
import org.wso2.balana.cond.xacml3.StringConversionFunction;
import java.util.HashSet;
import java.util.Set;
/**
* Clusters all the functions supported by <code>StringConversionFunction</code>
*/
public class StringConversionFunctionCluster implements FunctionCluster {
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<Function>();
for (String identifier : StringConversionFunction.getSupportedIdentifiers()){
set.add(new StringConversionFunction(identifier));
}
return set;
}
}
| 1,376 | 33.425 | 85 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/cluster/xacml3/XACML3HigherOrderFunctionCluster.java | /*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.cond.cluster.xacml3;
import org.wso2.balana.cond.Function;
import org.wso2.balana.cond.xacml3.XACML3HigherOrderFunction;
import org.wso2.balana.cond.cluster.FunctionCluster;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Clusters all the functions supported by <code>XACML3HigherOrderFunction</code>.
*/
public class XACML3HigherOrderFunctionCluster implements FunctionCluster {
@Override
public Set<Function> getSupportedFunctions() {
Set<Function> set = new HashSet<>();
Iterator it = XACML3HigherOrderFunction.getSupportedIdentifiers().iterator();
while (it.hasNext()) {
set.add(new XACML3HigherOrderFunction((String) (it.next())));
}
return set;
}
}
| 1,470 | 31.688889 | 85 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/AttributeProxy.java | /*
* @(#)AttributeProxy.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import org.w3c.dom.Node;
/**
* Used by the <code>AttributeFactory</code> to create new attributes. Typically a new proxy class
* is created which in turn knows how to create a specific kind of attribute, and then this proxy
* class is installed in the <code>AttributeFactory</code>.
*
* @since 1.0
* @author Seth Proctor
*/
public interface AttributeProxy {
/**
* Tries to create a new <code>AttributeValue</code> based on the given DOM root node.
*
* @param root the DOM root of some attribute data
*
* @return an <code>AttributeValue</code> representing the given data
*
* @throws Exception if the data couldn't be used (the exception is typically wrapping some
* other exception)
*/
public AttributeValue getInstance(Node root) throws Exception;
/**
* Tries to create a new <code>AttributeValue</code> based on the given String data.
*
* @param value the text form of some attribute data
*
* @param params additional parameters that need to creates a value
*
* @return an <code>AttributeValue</code> representing the given data
*
* @throws Exception if the data couldn't be used (the exception is typically wrapping some
* other exception)
*/
public AttributeValue getInstance(String value, String[] params) throws Exception;
}
| 3,243 | 41.684211 | 98 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/RFC822NameAttribute.java | /*
* @(#)RFC822NameAttribute.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import java.net.URI;
import org.w3c.dom.Node;
/**
* Representation of an rfc822Name (ie, an email address).
*
* @since 1.0
* @author Seth Proctor
*/
public class RFC822NameAttribute extends AttributeValue {
/**
* Official name of this type
*/
public static final String identifier = "urn:oasis:names:tc:xacml:1.0:data-type:rfc822Name";
/**
* URI version of name for this type
* <p>
* This field is initialized by a static initializer so that we can catch any exceptions thrown
* by URI(String) and transform them into a RuntimeException, since this should never happen but
* should be reported properly if it ever does.
*/
private static URI identifierURI;
/**
* RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if
* none.
*/
private static RuntimeException earlyException;
/**
* Static initializer that initializes the identifierURI class field so that we can catch any
* exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions
* should never happen but should be reported properly if they ever do.
*/
static {
try {
identifierURI = new URI(identifier);
} catch (Exception e) {
earlyException = new IllegalArgumentException();
earlyException.initCause(e);
}
};
// the actual value being stored
private String value;
/**
* Creates a new <code>RFC822NameAttribute</code> that represents the value supplied.
*
* @param value the email address to be represented
*/
public RFC822NameAttribute(String value) {
super(identifierURI);
// Shouldn't happen, but just in case...
if (earlyException != null)
throw earlyException;
// check that the string is an address, ie, that it has one and only
// one '@' character in it
String[] parts = value.split("@");
if (parts.length != 2) {
// this is malformed input
throw new IllegalArgumentException("invalid RFC822Name: " + value);
}
// cannonicalize the name
this.value = parts[0] + "@" + parts[1].toLowerCase();
}
/**
* Returns a new <code>RFC822NameAttribute</code> that represents the email address at a
* particular DOM node.
*
* @param root the <code>Node</code> that contains the desired value
* @return a new <code>RFC822NameAttribute</code> representing the appropriate value
*/
public static RFC822NameAttribute getInstance(Node root) {
return getInstance(root.getFirstChild().getNodeValue());
}
/**
* Returns a new <code>RFC822NameAttribute</code> that represents the email address value
* indicated by the string provided.
*
* @param value a string representing the desired value
* @return a new <code>RFC822NameAttribute</code> representing the appropriate value
*/
public static RFC822NameAttribute getInstance(String value) {
return new RFC822NameAttribute(value);
}
/**
* Returns the name value represented by this object
*
* @return the name
*/
public String getValue() {
return value;
}
/**
* Returns true if the input is an instance of this class and if its value equals the value
* contained in this class.
*
* @param o the object to compare
*
* @return true if this object and the input represent the same value
*/
public boolean equals(Object o) {
if (!(o instanceof RFC822NameAttribute))
return false;
RFC822NameAttribute other = (RFC822NameAttribute) o;
return value.equals(other.value);
}
/**
* Returns the hashcode value used to index and compare this object with others of the same
* type. Typically this is the hashcode of the backing data object.
*
* @return the object's hashcode value
*/
public int hashCode() {
return value.hashCode();
}
/**
*
*/
public String encode() {
return value;
}
}
| 6,054 | 33.20904 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/IPAddressAttribute.java | /*
* @(#)IPAddressAttribute.java
*
* Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import org.wso2.balana.ParsingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.URI;
import org.w3c.dom.Node;
/**
* Represents the IPAddress datatype introduced in XACML 2.0. All objects of this class are
* immutable and all methods of the class are thread-safe.
* <p>
* To create an instance of an ipAddress from an encoded String or a DOM Node you should use the
* <code>getInstance</code> methods provided by this class. To construct an ipAddress instance
* directly, you must use the constructors provided by <code>IPv4AddressAttribute</code> and
* <code>IPv6AddressAttribute</code>. These will both create an attribute of XACML type ipAddress,
* but will handle the differences in these two representations correctly.
*
* @since 2.0
* @author Seth Proctor
*/
public abstract class IPAddressAttribute extends AttributeValue {
/**
* Official name of this type
*/
public static final String identifier = "urn:oasis:names:tc:xacml:2.0:data-type:ipAddress";
/**
* URI version of name for this type
* <p>
* This field is initialized by a static initializer so that we can catch any exceptions thrown
* by URI(String) and transform them into a RuntimeException, since this should never happen but
* should be reported properly if it ever does.
*/
private static URI identifierURI;
/**
* RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if
* none.
*/
private static RuntimeException earlyException;
/**
* Static initializer that initializes the identifierURI class field so that we can catch any
* exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions
* should never happen but should be reported properly if they ever do.
*/
static {
try {
identifierURI = new URI(identifier);
} catch (Exception e) {
earlyException = new IllegalArgumentException();
earlyException.initCause(e);
}
};
// the required address
private InetAddress address;
// the optional mask
private InetAddress mask;
// this is the optional port-range
private PortRange range;
/**
* Creates the new <code>IPAddressAttribute</code> with all the optional components.
*
* @param address a non-null <code>InetAddress</code>
* @param mask an <code>InetAddress</code> or null if there is no mask
* @param portRange a non-null <code>PortRange</code>
*/
protected IPAddressAttribute(InetAddress address, InetAddress mask, PortRange range) {
super(identifierURI);
// shouldn't happen, but just in case...
if (earlyException != null)
throw earlyException;
this.address = address;
this.mask = mask;
this.range = range;
}
/**
* Returns a new <code>IPAddressAttribute</code> that represents the name at a particular DOM
* node.
*
* @param root the <code>Node</code> that contains the desired value
*
* @return a new <code>IPAddressAttribute</code> representing the appropriate value (null if
* there is a parsing error)
*
* @throws ParsingException if any of the address components is invalid
*/
public static IPAddressAttribute getInstance(Node root) throws ParsingException {
return getInstance(root.getFirstChild().getNodeValue());
}
/**
* Returns a new <code>IPAddressAttribute</code> that represents the name indicated by the
* <code>String</code> provided.
*
* @param value a string representing the address
*
* @return a new <code>IPAddressAttribute</code>
*
* @throws ParsingException if any of the address components is invalid
*/
public static IPAddressAttribute getInstance(String value) throws ParsingException {
try {
// an IPv6 address starts with a '['
if (value.indexOf('[') == 0)
return IPv6AddressAttribute.getV6Instance(value);
else
return IPv4AddressAttribute.getV4Instance(value);
} catch (UnknownHostException uhe) {
throw new ParsingException("Failed to parse an IPAddress", uhe);
}
}
/**
* Returns the address represented by this object.
*
* @return the address
*/
public InetAddress getAddress() {
return address;
}
/**
* Returns the mask represented by this object, or null if there is no mask.
*
* @return the mask or null
*/
public InetAddress getMask() {
return mask;
}
/**
* Returns the port range represented by this object which will be unbound if no range was
* specified.
*
* @return the range
*/
public PortRange getRange() {
return range;
}
/**
* Returns true if the input is an instance of this class and if its value equals the value
* contained in this class.
*
* @param o the object to compare
*
* @return true if this object and the input represent the same value
*/
public boolean equals(Object o) {
if (!(o instanceof IPAddressAttribute))
return false;
IPAddressAttribute other = (IPAddressAttribute) o;
if (!address.equals(other.address))
return false;
if (mask != null) {
if (other.mask == null)
return false;
if (!mask.equals(other.mask))
return false;
} else {
if (other.mask != null)
return false;
}
if (!range.equals(other.range))
return false;
return true;
}
/**
* Returns the hashcode value used to index and compare this object with others of the same
* type.
*
* @return the object's hashcode value
*/
public int hashCode() {
// FIXME: what should the hashcode be?
return 0;
}
/**
* Converts to a String representation.
*
* @return the String representation
*/
public String toString() {
return "IPAddressAttribute: \"" + encode() + "\"";
}
}
| 8,167 | 32.338776 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/Base64.java | /*
* @(#)Base64.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
/**
* Class that knows how to encode and decode Base64 values. Base64 Content-Transfer-Encoding rules
* are defined in Section 6.8 of IETF RFC 2045 <i>Multipurpose Internet Mail Extensions (MIME) Part
* One: Format of Internet Message Bodies</i>, available at <a
* href="ftp://ftp.isi.edu/in-notes/rfc2045.txt">
* <code>ftp://ftp.isi.edu/in-notes/rfc2045.txt</code></a>.
* <p>
* All methods of this class are static and thread-safe.
*
* @since 1.0
* @author Anne Anderson
*/
class Base64 {
/*
* ASCII white-space characters. These are the ones recognized by the C and Java language
* [pre-processors].
*/
private static final char SPACE = 0x20; /* space, or blank, character */
private static final char ETX = 0x04; /* end-of-text character */
private static final char VTAB = 0x0b; /* vertical tab character */
private static final char FF = 0x0c; /* form-feed character */
private static final char HTAB = 0x09; /* horizontal tab character */
private static final char LF = 0x0a; /* line feed character */
private static final char ALTLF = 0x13; /* line feed on some systems */
private static final char CR = 0x0d; /* carriage-return character */
/*
* The character used to pad out a 4-character Base64-encoded block, or "quantum".
*/
private static char PAD = '=';
/*
* String used for BASE64 encoding and decoding.
*
* For index values 0-63, the character at each index is the Base-64 encoded value of the index
* value. Index values beyond 63 are never referenced during encoding, but are used in this
* implementation to help in decoding. The character at index 64 is the Base64 pad character
* '='.
*
* Charaters in index positions 0-64 MUST NOT be moved or altered, as this will break the
* implementation.
*
* The characters after index 64 are white space characters that should be ignored in
* Base64-encoded input strings while doing decoding. Note that the white-space character set
* should include values used on various platforms, since a Base64-encoded value may have been
* generated on a non-Java platform. The values included here are those used in Java and in C.
*
* The white-space character set may be modified without affecting the implementation of the
* encoding algorithm.
*/
private static final String BASE64EncodingString = "ABCDEFGHIJ" + "KLMNOPQRST" + "UVWXYZabcd"
+ "efghijklmn" + "opqrstuvwx" + "yz01234567" + "89+/" + "=" + SPACE + ETX + VTAB + FF
+ HTAB + LF + ALTLF + CR;
// Index of pad character in Base64EncodingString
private static final int PAD_INDEX = 64;
/*
* The character in Base64EncodingString with the maximum character value in Unicode.
*/
private static final int MAX_BASE64_CHAR = 'z';
/*
* Array for mapping encoded characters to decoded values. This array is initialized when needed
* by calling initDecodeArray(). Only includes entries up to MAX_BASE64_CHAR.
*/
private static int[] Base64DecodeArray = null;
/*
* State values used for decoding a quantum of four encoded input characters as follows.
*
* Initial state: NO_CHARS_DECODED NO_CHARS_DECODED: no characters have been decoded on encoded
* char: decode char into output quantum; new state: ONE_CHAR_DECODED otherwise: Exception
* ONE_CHAR_DECODED: one character has been decoded on encoded char: decode char into output
* quantum; new state: TWO_CHARS_DECODED otherwise: Exception TWO_CHARS_DECODED: two characters
* have been decoded on encoded char: decode char into output quantum; new state:
* THREE_CHARS_DECODED on pad: write quantum byte 0 to output; new state: PAD_THREE_READ
* THREE_CHARS_DECODED: three characters have been decoded on encoded char: decode char into
* output quantum; write quantum bytes 0-2 to output; new state: NO_CHARS_DECODED on pad: write
* quantum bytes 0-1 to output; new state: PAD_FOUR_READ PAD_THREE_READ: pad character has been
* read as 3rd of 4 chars on pad: new state: PAD_FOUR_READ otherwise: Exception PAD_FOUR_READ:
* pad character has been read as 4th of 4 char on any char: Exception
*
* The valid terminal states are NO_CHARS_DECODED and PAD_FOUR_READ.
*/
private static final int NO_CHARS_DECODED = 0;
private static final int ONE_CHAR_DECODED = 1;
private static final int TWO_CHARS_DECODED = 2;
private static final int THREE_CHARS_DECODED = 3;
private static final int PAD_THREE_READ = 5;
private static final int PAD_FOUR_READ = 6;
/**
* The maximum number of groups that should be encoded onto a single line (so we don't exceed 76
* characters per line).
*/
private static final int MAX_GROUPS_PER_LINE = 76 / 4;
/**
* Encodes the input byte array into a Base64-encoded <code>String</code>. The output
* <code>String</code> has a CR LF (0x0d 0x0a) after every 76 bytes, but not at the end.
* <p>
* <b>WARNING</b>: If the input byte array is modified while encoding is in progress, the output
* is undefined.
*
* @param binaryValue the byte array to be encoded
*
* @return the Base64-encoded <code>String</code>
*/
public static String encode(byte[] binaryValue) {
int binaryValueLen = binaryValue.length;
// Estimated output length (about 1.4x input, due to CRLF)
int maxChars = (binaryValueLen * 7) / 5;
// Buffer for encoded output
StringBuffer sb = new StringBuffer(maxChars);
int groupsToEOL = MAX_GROUPS_PER_LINE;
// Convert groups of 3 input bytes, with pad if < 3 in final
for (int binaryValueNdx = 0; binaryValueNdx < binaryValueLen; binaryValueNdx += 3) {
// Encode 1st 6-bit group
int group1 = (binaryValue[binaryValueNdx] >> 2) & 0x3F;
sb.append(BASE64EncodingString.charAt(group1));
// Encode 2nd 6-bit group
int group2 = (binaryValue[binaryValueNdx] << 4) & 0x030;
if ((binaryValueNdx + 1) < binaryValueLen) {
group2 = group2 | ((binaryValue[binaryValueNdx + 1] >> 4) & 0xF);
}
sb.append(BASE64EncodingString.charAt(group2));
// Encode 3rd 6-bit group
int group3;
if ((binaryValueNdx + 1) < binaryValueLen) {
group3 = (binaryValue[binaryValueNdx + 1] << 2) & 0x03C;
if ((binaryValueNdx + 2) < binaryValueLen) {
group3 = group3 | ((binaryValue[binaryValueNdx + 2] >> 6) & 0x3);
}
} else {
group3 = PAD_INDEX;
}
sb.append(BASE64EncodingString.charAt(group3));
// Encode 4th 6-bit group
int group4;
if ((binaryValueNdx + 2) < binaryValueLen) {
group4 = binaryValue[binaryValueNdx + 2] & 0x3F;
} else {
group4 = PAD_INDEX;
}
sb.append(BASE64EncodingString.charAt(group4));
// After every MAX_GROUPS_PER_LINE groups, insert CR LF.
// Unless this is the final line, in which case we skip that.
groupsToEOL = groupsToEOL - 1;
if (groupsToEOL == 0) {
groupsToEOL = MAX_GROUPS_PER_LINE;
if ((binaryValueNdx + 3) <= binaryValueLen) {
sb.append(CR);
sb.append(LF);
}
}
}
return sb.toString();
}
/**
* Initializes Base64DecodeArray, if this hasn't already been done.
*/
private static void initDecodeArray() {
if (Base64DecodeArray != null)
return;
int[] ourArray = new int[MAX_BASE64_CHAR + 1];
for (int i = 0; i <= MAX_BASE64_CHAR; i++)
ourArray[i] = BASE64EncodingString.indexOf(i);
Base64DecodeArray = ourArray;
}
/**
* Decodes a Base64-encoded <code>String</code>. The result is returned in a byte array that
* should match the original binary value (before encoding). Whitespace characters in the input
* <code>String</code> are ignored.
* <p>
* If the <code>ignoreBadChars</code> parameter is <code>true</code>, characters that are not
* allowed in a BASE64-encoded string are ignored. Otherwise, they cause an
* <code>IOException</code> to be raised.
*
* @param encoded a <code>String</code> containing a Base64-encoded value
* @param ignoreBadChars If <code>true</code>, bad characters are ignored. Otherwise, they cause
* an <code>IOException</code> to be raised.
*
* @return a byte array containing the decoded value
*
* @throws IOException if the input <code>String</code> is not a valid Base64-encoded value
*/
public static byte[] decode(String encoded, boolean ignoreBadChars) throws IOException {
int encodedLen = encoded.length();
int maxBytes = (encodedLen / 4) * 3; /* Maximum possible output bytes */
ByteArrayOutputStream ba = /* Buffer for decoded output */
new ByteArrayOutputStream(maxBytes);
byte[] quantum = new byte[3]; /* one output quantum */
// ensure Base64DecodeArray is initialized
initDecodeArray();
/*
* Every 4 encoded characters in input are converted to 3 bytes of output. This is called
* one "quantum". Each encoded character is mapped to one 6-bit unit of the output.
* Whitespace characters in the input are passed over; they are not included in the output.
*/
int state = NO_CHARS_DECODED;
for (int encodedNdx = 0; encodedNdx < encodedLen; encodedNdx++) {
// Turn encoded char into decoded value
int encodedChar = encoded.charAt(encodedNdx);
int decodedChar;
if (encodedChar > MAX_BASE64_CHAR)
decodedChar = -1;
else
decodedChar = Base64DecodeArray[encodedChar];
// Handle white space and invalid characters
if (decodedChar == -1) {
if (ignoreBadChars)
continue;
throw new IOException("Invalid character");
}
if (decodedChar > PAD_INDEX) { /* whitespace */
continue;
}
// Handle valid characters
switch (state) {
case NO_CHARS_DECODED:
if (decodedChar == PAD_INDEX) {
throw new IOException("Pad character in invalid position");
}
quantum[0] = (byte) ((decodedChar << 2) & 0xFC);
state = ONE_CHAR_DECODED;
break;
case ONE_CHAR_DECODED:
if (decodedChar == PAD_INDEX) {
throw new IOException("Pad character in invalid position");
}
quantum[0] = (byte) (quantum[0] | ((decodedChar >> 4) & 0x3));
quantum[1] = (byte) ((decodedChar << 4) & 0xF0);
state = TWO_CHARS_DECODED;
break;
case TWO_CHARS_DECODED:
if (decodedChar == PAD_INDEX) {
ba.write(quantum, 0, 1);
state = PAD_THREE_READ;
} else {
quantum[1] = (byte) (quantum[1] | ((decodedChar >> 2) & 0x0F));
quantum[2] = (byte) ((decodedChar << 6) & 0xC0);
state = THREE_CHARS_DECODED;
}
break;
case THREE_CHARS_DECODED:
if (decodedChar == PAD_INDEX) {
ba.write(quantum, 0, 2);
state = PAD_FOUR_READ;
} else {
quantum[2] = (byte) (quantum[2] | decodedChar);
ba.write(quantum, 0, 3);
state = NO_CHARS_DECODED;
}
break;
case PAD_THREE_READ:
if (decodedChar != PAD_INDEX) {
throw new IOException("Missing pad character");
}
state = PAD_FOUR_READ;
break;
case PAD_FOUR_READ:
throw new IOException("Invalid input follows pad character");
}
}
// BalanaTest valid terminal states
if (state != NO_CHARS_DECODED && state != PAD_FOUR_READ)
throw new IOException("Invalid sequence of input characters");
return ba.toByteArray();
}
}
| 14,585 | 43.2 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/IPv6AddressAttribute.java | /*
* @(#)IPv6AddressAttribute.java
*
* Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Subclass of <code>IPAddressAttribute</code> that handles the specifics of IPv6. In general, you
* shouldn't need to interact with this class except to create an instance directly.
*
* @since 2.0
* @author Seth Proctor
*/
public class IPv6AddressAttribute extends IPAddressAttribute {
/**
* Creates the new <code>IPv6AddressAttribute</code> with just the required address component.
*
* @param address a non-null <code>InetAddress</code>
*/
public IPv6AddressAttribute(InetAddress address) {
this(address, null, new PortRange());
}
/**
* Creates the new <code>IPv6AddressAttribute</code> with the optional address mask.
*
* @param address a non-null <code>InetAddress</code>
* @param mask an <code>InetAddress</code> or null if there is no mask
*/
public IPv6AddressAttribute(InetAddress address, InetAddress mask) {
this(address, mask, new PortRange());
}
/**
* Creates the new <code>IPv6AddressAttribute</code> with the optional port range.
*
* @param address a non-null <code>InetAddress</code>
* @param portRange a non-null <code>PortRange</code>
*/
public IPv6AddressAttribute(InetAddress address, PortRange range) {
this(address, null, range);
}
/**
* Creates the new <code>IPv6AddressAttribute</code> with all the optional components.
*
* @param address a non-null <code>InetAddress</code>
* @param mask an <code>InetAddress</code> or null if there is no mask
* @param portRange a non-null <code>PortRange</code>
*/
public IPv6AddressAttribute(InetAddress address, InetAddress mask, PortRange range) {
super(address, mask, range);
}
/**
* Returns a new <code>IPv6AddressAttribute</code> that represents the name indicated by the
* <code>String</code> provided. This is a protected method because you should never call it
* directly. Instead, you should call <code>getInstance</code> on
* <code>IPAddressAttribute</code> which provides versions that take both a <code>String</code>
* and a <code>Node</code> and will determine the protocol version correctly.
*
* @param value a string representing the address
*
* @return a new <code>IPAddressAttribute</code>
*
* @throws UnknownHostException if the address components is invalid
* @throws ParsingException if any of the address components is invalid
*/
protected static IPAddressAttribute getV6Instance(String value) throws UnknownHostException {
InetAddress address = null;
InetAddress mask = null;
PortRange range = null;
int len = value.length();
// get the required address component
int endIndex = value.indexOf(']');
address = InetAddress.getByName(value.substring(1, endIndex));
// see if there's anything left in the string
if (endIndex != (len - 1)) {
// if there's a mask, it's also an IPv6 address
if (value.charAt(endIndex + 1) == '/') {
int startIndex = endIndex + 3;
endIndex = value.indexOf(']', startIndex);
mask = InetAddress.getByName(value.substring(startIndex, endIndex));
}
// finally, see if there's a port range, if we're not finished
if ((endIndex != (len - 1)) && (value.charAt(endIndex + 1) == ':'))
range = PortRange.getInstance(value.substring(endIndex + 2, len));
}
// if the range is null, then create it as unbound
range = new PortRange();
return new IPv6AddressAttribute(address, mask, range);
}
/**
*
*/
public String encode() {
String str = "[" + getAddress().getHostAddress() + "]";
if (getMask() != null)
str += "/[" + getMask().getHostAddress() + "]";
if (!getRange().isUnbound())
str += ":" + getRange().encode();
return str;
}
}
| 5,944 | 38.633333 | 99 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/AbstractDesignator.java | package org.wso2.balana.attr;
import org.wso2.balana.cond.Evaluatable;
import java.net.URI;
/**
*
*/
public abstract class AbstractDesignator implements Evaluatable {
public abstract URI getId();
}
| 209 | 13 | 65 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/DayTimeDurationAttribute.java | /*
* @(#)DayTimeDurationAttribute.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import org.wso2.balana.ParsingException;
import java.math.BigInteger;
import java.net.URI;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.regex.Matcher;
import org.w3c.dom.Node;
/**
* Representation of an xf:dayTimeDuration value. This class supports parsing xd:dayTimeDuration
* values. All objects of this class are immutable and thread-safe. The <code>Date</code> objects
* returned are not, but these objects are cloned before being returned.
*
* @since 1.0
* @author Steve Hanna
*/
public class DayTimeDurationAttribute extends AttributeValue {
/**
* Official name of this type
*/
public static final String identifier = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#"
+ "dayTimeDuration";
/**
* URI version of name for this type
* <p>
* This field is initialized by a static initializer so that we can catch any exceptions thrown
* by URI(String) and transform them into a RuntimeException, since this should never happen but
* should be reported properly if it ever does.
*/
private static URI identifierURI;
/**
* RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if
* none.
*/
private static RuntimeException earlyException;
/**
* Static initializer that initializes the identifierURI class field so that we can catch any
* exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions
* should never happen but should be reported properly if they ever do.
*/
static {
try {
identifierURI = new URI(identifier);
} catch (Exception e) {
earlyException = new IllegalArgumentException();
earlyException.initCause(e);
}
};
/**
* Regular expression for dayTimeDuration (a la java.util.regex)
*/
private static final String patternString = "(\\-)?P((\\d+)?D)?(T((\\d+)?H)?((\\d+)?M)?((\\d+)?(.(\\d+)?)?S)?)?";
/**
* The index of the capturing group for the negative sign.
*/
private static final int GROUP_SIGN = 1;
/**
* The index of the capturing group for the number of days.
*/
private static final int GROUP_DAYS = 3;
/**
* The index of the capturing group for the number of hours.
*/
private static final int GROUP_HOURS = 6;
/**
* The index of the capturing group for the number of minutes.
*/
private static final int GROUP_MINUTES = 8;
/**
* The index of the capturing group for the number of seconds.
*/
private static final int GROUP_SECONDS = 10;
/**
* The index of the capturing group for the number of nanoseconds.
*/
private static final int GROUP_NANOSECONDS = 12;
/**
* Static BigInteger values. We only use these if one of the components is bigger than
* Integer.MAX_LONG and we want to detect overflow, so we don't initialize these until they're
* needed.
*/
private static BigInteger big24 = BigInteger.valueOf(24);
private static BigInteger big60 = BigInteger.valueOf(60);
private static BigInteger big1000 = BigInteger.valueOf(1000);
private static BigInteger bigMaxLong = BigInteger.valueOf(Long.MAX_VALUE);
/**
* A shared Pattern object, only initialized if needed
*/
private static Pattern pattern;
/**
* Negative flag. true if duration is negative, false otherwise
*/
private boolean negative;
/**
* Number of days
*/
private long days;
/**
* Number of hours
*/
private long hours;
/**
* Number of minutes
*/
private long minutes;
/**
* Number of seconds
*/
private long seconds;
/**
* Number of nanoseconds
*/
private int nanoseconds;
/**
* Total number of round seconds (in milliseconds)
*/
private long totalMillis;
/**
* Cached encoded value (null if not cached yet).
*/
private String encodedValue = null;
/**
* Creates a new <code>DayTimeDurationAttribute</code> that represents the duration supplied.
*
* @param negative true if the duration is negative, false otherwise
* @param days the number of days in the duration
* @param hours the number of hours in the duration
* @param minutes the number of minutes in the duration
* @param seconds the number of seconds in the duration
* @param nanoseconds the number of nanoseconds in the duration
* @throws IllegalArgumentException if the total number of milliseconds exceeds Long.MAX_LONG
*/
public DayTimeDurationAttribute(boolean negative, long days, long hours, long minutes,
long seconds, int nanoseconds) throws IllegalArgumentException {
super(identifierURI);
// Shouldn't happen, but just in case...
if (earlyException != null)
throw earlyException;
this.negative = negative;
this.days = days;
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
this.nanoseconds = nanoseconds;
// Convert all the components except nanoseconds to milliseconds
// If any of the components is big (too big to be an int),
// use the BigInteger class to do the math so we can detect
// overflow.
if ((days > Integer.MAX_VALUE) || (hours > Integer.MAX_VALUE)
|| (minutes > Integer.MAX_VALUE) || (seconds > Integer.MAX_VALUE)) {
BigInteger bigDays = BigInteger.valueOf(days);
BigInteger bigHours = BigInteger.valueOf(hours);
BigInteger bigMinutes = BigInteger.valueOf(minutes);
BigInteger bigSeconds = BigInteger.valueOf(seconds);
BigInteger bigTotal = bigDays.multiply(big24).add(bigHours).multiply(big60)
.add(bigMinutes).multiply(big60).add(bigSeconds).multiply(big1000);
// If the result is bigger than Long.MAX_VALUE, we have an
// overflow. Indicate an error (should be a processing error,
// since it can be argued that we should handle gigantic
// values for this).
if (bigTotal.compareTo(bigMaxLong) == 1)
throw new IllegalArgumentException("total number of " + "milliseconds "
+ "exceeds Long.MAX_VALUE");
// If no overflow, convert to a long.
totalMillis = bigTotal.longValue();
} else {
// The numbers are small, so do it the fast way.
totalMillis = ((((((days * 24) + hours) * 60) + minutes) * 60) + seconds) * 1000;
}
}
/**
* Returns a new <code>DayTimeDurationAttribute</code> that represents the xf:dayTimeDuration at
* a particular DOM node.
*
* @param root the <code>Node</code> that contains the desired value
* @return a new <code>DayTimeDurationAttribute</code> representing the appropriate value (null
* if there is a parsing error)
*/
public static DayTimeDurationAttribute getInstance(Node root) throws ParsingException,
NumberFormatException {
return getInstance(root.getFirstChild().getNodeValue());
}
/**
* Returns the long value for the capturing group groupNumber. This method takes a Matcher that
* has been used to match a Pattern against a String, fetches the value for the specified
* capturing group, converts that value to an long, and returns the value. If that group did not
* match, 0 is returned. If the matched value is not a valid long, NumberFormatException is
* thrown.
*
* @param matcher the Matcher from which to fetch the group
* @param groupNumber the group number to fetch
* @return the long value for that groupNumber
* @throws NumberFormatException if the string value for that groupNumber is not a valid long
*/
private static long parseGroup(Matcher matcher, int groupNumber) throws NumberFormatException {
long groupLong = 0;
if (matcher.start(groupNumber) != -1) {
String groupString = matcher.group(groupNumber);
groupLong = Long.parseLong(groupString);
}
return groupLong;
}
/**
* Returns a new <code>DayTimeDurationAttribute</code> that represents the xf:dayTimeDuration
* value indicated by the string provided.
*
* @param value a string representing the desired value
* @return a new <code>DayTimeDurationAttribute</code> representing the desired value (null if
* there is a parsing error)
*/
public static DayTimeDurationAttribute getInstance(String value) throws ParsingException,
NumberFormatException {
boolean negative = false;
long days = 0;
long hours = 0;
long minutes = 0;
long seconds = 0;
int nanoseconds = 0;
// Compile the pattern, if not already done.
// No thread-safety problem here. The worst that can
// happen is that we initialize pattern several times.
if (pattern == null) {
try {
pattern = Pattern.compile(patternString);
} catch (PatternSyntaxException e) {
// This should never happen
throw new ParsingException("unexpected pattern match error");
}
}
// See if the value matches the pattern.
Matcher matcher = pattern.matcher(value);
boolean matches = matcher.matches();
// If not, syntax error!
if (!matches) {
throw new ParsingException("Syntax error in dayTimeDuration");
}
// If the negative group matched, the value is negative.
if (matcher.start(GROUP_SIGN) != -1)
negative = true;
try {
// If the days group matched, parse that value.
days = parseGroup(matcher, GROUP_DAYS);
// If the hours group matched, parse that value.
hours = parseGroup(matcher, GROUP_HOURS);
// If the minutes group matched, parse that value.
minutes = parseGroup(matcher, GROUP_MINUTES);
// If the seconds group matched, parse that value.
seconds = parseGroup(matcher, GROUP_SECONDS);
// Special handling for fractional seconds, since
// they can have any resolution.
if (matcher.start(GROUP_NANOSECONDS) != -1) {
String nanosecondString = matcher.group(GROUP_NANOSECONDS);
// If there are less than 9 digits in the fractional seconds,
// pad with zeros on the right so it's nanoseconds.
if (nanosecondString.length() < 9) {
StringBuffer buffer = new StringBuffer(nanosecondString);
while (buffer.length() < 9) {
buffer.append("0");
}
nanosecondString = buffer.toString();
}
// If there are more than 9 digits in the fractional seconds,
// drop the least significant digits.
if (nanosecondString.length() > 9) {
nanosecondString = nanosecondString.substring(0, 9);
}
nanoseconds = Integer.parseInt(nanosecondString);
}
} catch (NumberFormatException e) {
// If we run into a number that's too big to be a long
// that's an error. Really, it's a processing error,
// since one can argue that we should handle that.
throw e;
}
// Here's a requirement that's not checked for in the pattern.
// The designator 'T' must be absent if all the time
// items are absent. So the string can't end in 'T'.
// Note that we don't have to worry about a zero length
// string, since the pattern won't allow that.
if (value.charAt(value.length() - 1) == 'T')
throw new ParsingException("'T' must be absent if all" + "time items are absent");
// If parsing went OK, create a new DayTimeDurationAttribute object and
// return it.
return new DayTimeDurationAttribute(negative, days, hours, minutes, seconds, nanoseconds);
}
/**
* Returns true if the duration is negative.
*
* @return true if the duration is negative, false otherwise
*/
public boolean isNegative() {
return negative;
}
/**
* Gets the number of days.
*
* @return the number of days
*/
public long getDays() {
return days;
}
/**
* Gets the number of hours.
*
* @return the number of hours
*/
public long getHours() {
return hours;
}
/**
* Gets the number of minutes.
*
* @return the number of minutes
*/
public long getMinutes() {
return minutes;
}
/**
* Gets the number of seconds.
*
* @return the number of seconds
*/
public long getSeconds() {
return seconds;
}
/**
* Gets the number of nanoseconds.
*
* @return the number of nanoseconds
*/
public int getNanoseconds() {
return nanoseconds;
}
/**
* Gets the total number of round seconds (in milliseconds).
*
* @return the total number of seconds (in milliseconds)
*/
public long getTotalSeconds() {
return totalMillis;
}
/**
* Returns true if the input is an instance of this class and if its value equals the value
* contained in this class.
*
* @param o the object to compare
*
* @return true if this object and the input represent the same value
*/
public boolean equals(Object o) {
if (!(o instanceof DayTimeDurationAttribute))
return false;
DayTimeDurationAttribute other = (DayTimeDurationAttribute) o;
return ((totalMillis == other.totalMillis) && (nanoseconds == other.nanoseconds) && (negative == other.negative));
}
/**
* Returns the hashcode value used to index and compare this object with others of the same
* type. Typically this is the hashcode of the backing data object.
*
* @return the object's hashcode value
*/
public int hashCode() {
// The totalMillis, nanoseconds, and negative fields are all considered
// by the equals method, so it's best if the hashCode is derived
// from all of those fields.
int hashCode = (int) totalMillis ^ (int) (totalMillis >> 32);
hashCode = 31 * hashCode + nanoseconds;
if (negative)
hashCode = -hashCode;
return hashCode;
}
/**
* Converts to a String representation.
*
* @return the String representation
*/
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("DayTimeDurationAttribute: [\n");
sb.append(" Negative: " + negative);
sb.append(" Days: " + days);
sb.append(" Hours: " + hours);
sb.append(" Minutes: " + minutes);
sb.append(" Seconds: " + seconds);
sb.append(" Nanoseconds: " + nanoseconds);
sb.append(" TotalSeconds: " + totalMillis);
sb.append("]");
return sb.toString();
}
/**
* Encodes the value in a form suitable for including in XML data like a request or an
* obligation. This must return a value that could in turn be used by the factory to create a
* new instance with the same value.
*
* @return a <code>String</code> form of the value
*/
public String encode() {
if (encodedValue != null)
return encodedValue;
// Length is quite variable
StringBuffer buf = new StringBuffer(10);
if (negative)
buf.append('-');
buf.append('P');
if (days != 0) {
buf.append(Long.toString(days));
buf.append('D');
}
if ((hours != 0) || (minutes != 0) || (seconds != 0) || (nanoseconds != 0)) {
// Only include the T if there are some time fields
buf.append('T');
} else {
// Make sure that there's always at least one field specified
if (days == 0)
buf.append("0D");
}
if (hours != 0) {
buf.append(Long.toString(hours));
buf.append('H');
}
if (minutes != 0) {
buf.append(Long.toString(minutes));
buf.append('M');
}
if ((seconds != 0) || (nanoseconds != 0)) {
buf.append(Long.toString(seconds));
if (nanoseconds != 0) {
buf.append('.');
buf.append(DateAttribute.zeroPadInt(nanoseconds, 9));
}
buf.append('S');
}
encodedValue = buf.toString();
return encodedValue;
}
}
| 16,779 | 29.902394 | 116 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/IntegerAttribute.java | /*
* @(#)IntegerAttribute.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import java.net.URI;
import org.w3c.dom.Node;
/**
* Representation of an xs:integer value. This class supports parsing xs:integer values. All objects
* of this class are immutable and all methods of the class are thread-safe.
*
* @since 1.0
* @author Marco Barreno
* @author Steve Hanna
*/
public class IntegerAttribute extends AttributeValue {
/**
* Official name of this type
*/
public static final String identifier = "http://www.w3.org/2001/XMLSchema#integer";
/**
* URI version of name for this type
* <p>
* This field is initialized by a static initializer so that we can catch any exceptions thrown
* by URI(String) and transform them into a RuntimeException, since this should never happen but
* should be reported properly if it ever does.
*/
private static URI identifierURI;
/**
* RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if
* none.
*/
private static RuntimeException earlyException;
/**
* Static initializer that initializes the identifierURI class field so that we can catch any
* exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions
* should never happen but should be reported properly if they ever do.
*/
static {
try {
identifierURI = new URI(identifier);
} catch (Exception e) {
earlyException = new IllegalArgumentException();
earlyException.initCause(e);
}
};
/**
* The actual long value that this object represents.
*/
private long value;
/**
* Creates a new <code>IntegerAttribute</code> that represents the long value supplied.
*
* @param value the <code>long</code> value to be represented
*/
public IntegerAttribute(long value) {
super(identifierURI);
// Shouldn't happen, but just in case...
if (earlyException != null)
throw earlyException;
this.value = value;
}
/**
* Returns a new <code>IntegerAttribute</code> that represents the xs:integer at a particular
* DOM node.
*
* @param root the <code>Node</code> that contains the desired value
* @return a new <code>IntegerAttribute</code> representing the appropriate value (null if there
* is a parsing error)
* @throws NumberFormatException if the string form isn't a number
*/
public static IntegerAttribute getInstance(Node root) throws NumberFormatException {
return getInstance(root.getFirstChild().getNodeValue());
}
/**
* Returns a new <code>IntegerAttribute</code> that represents the xs:integer value indicated by
* the string provided.
*
* @param value a string representing the desired value
* @return a new <code>IntegerAttribute</code> representing the appropriate value (null if there
* is a parsing error)
* @throws NumberFormatException if the string isn't a number
*/
public static IntegerAttribute getInstance(String value) throws NumberFormatException {
// Leading '+' is allowed per XML schema and not
// by Long.parseLong. Strip it, if present.
if ((value.length() >= 1) && (value.charAt(0) == '+'))
value = value.substring(1);
return new IntegerAttribute(Long.parseLong(value));
}
/**
* Returns the <code>long</code> value represented by this object.
*
* @return the <code>long</code> value
*/
public long getValue() {
return value;
}
/**
* Returns true if the input is an instance of this class and if its value equals the value
* contained in this class.
*
* @param o the object to compare
*
* @return true if this object and the input represent the same value
*/
public boolean equals(Object o) {
if (!(o instanceof IntegerAttribute))
return false;
IntegerAttribute other = (IntegerAttribute) o;
return (value == other.value);
}
/**
* Returns the hashcode value used to index and compare this object with others of the same
* type. Typically this is the hashcode of the backing data object.
*
* @return the object's hashcode value
*/
public int hashCode() {
return (int) value;
}
/**
*
*/
public String encode() {
return String.valueOf(value);
}
}
| 6,363 | 34.553073 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/Base64BinaryAttribute.java | /*
* @(#)Base64BinaryAttribute.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import org.wso2.balana.ParsingException;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import org.w3c.dom.Node;
/**
* Representation of an xsi:base64Binary value. This class supports parsing xsi:base64Binary values.
* All objects of this class are immutable and all methods of the class are thread-safe.
*
* @since 1.0
* @author Steve Hanna
*/
public class Base64BinaryAttribute extends AttributeValue {
/**
* Official name of this type
*/
public static final String identifier = "http://www.w3.org/2001/XMLSchema#base64Binary";
/**
* URI version of name for this type
* <p>
* This field is initialized by a static initializer so that we can catch any exceptions thrown
* by URI(String) and transform them into a RuntimeException, since this should never happen but
* should be reported properly if it ever does.
*/
private static URI identifierURI;
/**
* RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if
* none.
*/
private static RuntimeException earlyException;
/**
* Static initializer that initializes the identifierURI class field so that we can catch any
* exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions
* should never happen but should be reported properly if they ever do.
*/
static {
try {
identifierURI = new URI(identifier);
} catch (Exception e) {
earlyException = new IllegalArgumentException();
earlyException.initCause(e);
}
};
/**
* The actual binary value that this object represents.
*/
private byte[] value;
/**
* The value returned by toString(). Cached, but only generated if needed.
*/
private String strValue;
/**
* Creates a new <code>Base64BinaryAttribute</code> that represents the byte [] value supplied.
*
* @param value the <code>byte []</code> value to be represented
*/
public Base64BinaryAttribute(byte[] value) {
super(identifierURI);
// Shouldn't happen, but just in case...
if (earlyException != null)
throw earlyException;
// This will throw a NullPointerException if value == null.
// That's what we want in that case.
this.value = (byte[]) value.clone();
}
/**
* Returns a new <code>Base64BinaryAttribute</code> that represents the xsi:base64Binary at a
* particular DOM node.
*
* @param root the <code>Node</code> that contains the desired value
* @return a new <code>Base64BinaryAttribute</code> representing the appropriate value
* @exception ParsingException if a parsing error occurs
*/
public static Base64BinaryAttribute getInstance(Node root) throws ParsingException {
return getInstance(root.getFirstChild().getNodeValue());
}
/**
* Returns a new <code>Base64BinaryAttribute</code> that represents the xsi:base64Binary value
* indicated by the string provided.
*
* @param value a string representing the desired value
* @return a new <code>Base64BinaryAttribute</code> representing the desired value
* @exception ParsingException if a parsing error occurs
*/
public static Base64BinaryAttribute getInstance(String value) throws ParsingException {
byte[] bytes = null;
try {
bytes = Base64.decode(value, false);
} catch (IOException e) {
throw new ParsingException("Couldn't parse purported " + "Base64 string: " + value, e);
}
return new Base64BinaryAttribute(bytes);
}
/**
* Returns the <code>byte []</code> value represented by this object. Note that this value is
* cloned before returning to prevent unauthorized modifications.
*
* @return the <code>byte []</code> value
*/
public byte[] getValue() {
return (byte[]) value.clone();
}
/**
* Returns true if the input is an instance of this class and if its value equals the value
* contained in this class.
*
* @param o the object to compare
*
* @return true if this object and the input represent the same value
*/
public boolean equals(Object o) {
if (!(o instanceof Base64BinaryAttribute))
return false;
Base64BinaryAttribute other = (Base64BinaryAttribute) o;
return Arrays.equals(value, other.value);
}
/**
* Returns the hashcode value used to index and compare this object with others of the same
* type. Typically this is the hashcode of the backing data object.
*
* @return the object's hashcode value
*/
public int hashCode() {
int code = (int) (value[0]);
for (int i = 1; i < value.length; i++) {
code *= 31;
code += (int) (value[i]);
}
return code;
}
/**
* Make the String representation of this object.
*
* @return the String representation
*/
private String makeStringRep() {
return Base64.encode(value);
}
/**
* Returns a String representation.
*
* @return the String representation
*/
public String toString() {
if (strValue == null)
strValue = makeStringRep();
return "Base64BinaryAttribute: [\n" + strValue + "]\n";
}
/**
*
*/
public String encode() {
if (strValue == null)
strValue = makeStringRep();
return strValue;
}
}
| 7,501 | 32.342222 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/HexBinaryAttribute.java | /*
* @(#)HexBinaryAttribute.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import org.wso2.balana.ParsingException;
import java.net.URI;
import java.util.Arrays;
import org.w3c.dom.Node;
/**
* Representation of an xsi:hexBinary value. This class supports parsing xsi:hexBinary values. All
* objects of this class are immutable and all methods of the class are thread-safe.
*
* @since 1.0
* @author Steve Hanna
*/
public class HexBinaryAttribute extends AttributeValue {
/**
* Official name of this type
*/
public static final String identifier = "http://www.w3.org/2001/XMLSchema#hexBinary";
/**
* URI version of name for this type
* <p>
* This field is initialized by a static initializer so that we can catch any exceptions thrown
* by URI(String) and transform them into a RuntimeException, since this should never happen but
* should be reported properly if it ever does.
*/
private static URI identifierURI;
/**
* RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if
* none.
*/
private static RuntimeException earlyException;
/**
* Static initializer that initializes the identifierURI class field so that we can catch any
* exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions
* should never happen but should be reported properly if they ever do.
*/
static {
try {
identifierURI = new URI(identifier);
} catch (Exception e) {
earlyException = new IllegalArgumentException();
earlyException.initCause(e);
}
};
/**
* The actual binary value that this object represents.
*/
private byte[] value;
/**
* The value returned by toString(). Cached, but only generated if needed.
*/
private String strValue;
/**
* Creates a new <code>HexBinaryAttribute</code> that represents the byte [] value supplied.
*
* @param value the <code>byte []</code> value to be represented
*/
public HexBinaryAttribute(byte[] value) {
super(identifierURI);
// Shouldn't happen, but just in case...
if (earlyException != null)
throw earlyException;
// This will throw a NullPointerException if value == null.
// That's what we want in that case.
this.value = (byte[]) value.clone();
}
/**
* Returns a new <code>HexBinaryAttribute</code> that represents the xsi:hexBinary at a
* particular DOM node.
*
* @param root the <code>Node</code> that contains the desired value
* @return a new <code>HexBinaryAttribute</code> representing the appropriate value
* @exception ParsingException if a parsing error occurs
*/
public static HexBinaryAttribute getInstance(Node root) throws ParsingException {
return getInstance(root.getFirstChild().getNodeValue());
}
/**
* Returns a new <code>HexBinaryAttribute</code> that represents the xsi:hexBinary value
* indicated by the string provided.
*
* @param value a string representing the desired value
* @return a new <code>HexBinaryAttribute</code> representing the desired value
* @exception ParsingException if a parsing error occurs
*/
public static HexBinaryAttribute getInstance(String value) throws ParsingException {
byte[] bytes = hexToBin(value);
if (bytes == null)
throw new ParsingException("Couldn't parse purported " + "hex string: " + value);
return new HexBinaryAttribute(bytes);
}
/**
* Returns the <code>byte []</code> value represented by this object. Note that this value is
* cloned before returning to prevent unauthorized modifications.
*
* @return the <code>byte []</code> value
*/
public byte[] getValue() {
return (byte[]) value.clone();
}
/**
* Returns the hashcode value used to index and compare this object with others of the same
* type. Typically this is the hashcode of the backing data object.
*
* @return the object's hashcode value
*/
public int hashCode() {
int code = (int) (value[0]);
for (int i = 1; i < value.length; i++) {
code *= 31;
code += (int) (value[i]);
}
return code;
}
/**
* Returns true if the input is an instance of this class and if its value equals the value
* contained in this class.
*
* @param o the object to compare
*
* @return true if this object and the input represent the same value
*/
public boolean equals(Object o) {
if (!(o instanceof HexBinaryAttribute))
return false;
HexBinaryAttribute other = (HexBinaryAttribute) o;
return Arrays.equals(value, other.value);
}
/**
* Return the int value of a hex character. Return -1 if the character is not a valid hex
* character.
*/
private static int hexToBinNibble(char c) {
int result = -1;
if ((c >= '0') && (c <= '9'))
result = (c - '0');
else {
if ((c >= 'a') && (c <= 'f'))
result = (c - 'a') + 10;
else {
if ((c >= 'A') && (c <= 'F'))
result = (c - 'A') + 10;
// else pick up the -1 value set above
}
}
return result;
}
/**
* Parse a hex string, returning a new byte array containing the value. Return null in case of a
* parsing error.
*
* @param hex the hex string
* @return a new byte array containing the value (or null)
*/
private static byte[] hexToBin(String hex) {
int len = hex.length();
// Must have an even number of hex digits
if (len % 2 != 0)
return null;
int byteCount = len / 2;
byte[] bytes = new byte[byteCount];
int charIndex = 0;
for (int byteIndex = 0; byteIndex < byteCount; byteIndex++) {
int hiNibble = hexToBinNibble(hex.charAt(charIndex++));
int loNibble = hexToBinNibble(hex.charAt(charIndex++));
if ((hiNibble < 0) || (loNibble < 0))
return null;
bytes[byteIndex] = (byte) (hiNibble * 16 + loNibble);
}
return bytes;
}
/**
* Return the hex character for a particular nibble (half a byte).
*
* @param nibble a value 0-15
* @return hex character for that nibble (using A-F for 10-15)
*/
private static char binToHexNibble(int nibble) {
char result = (char) 0;
if (nibble < 10)
result = (char) (nibble + '0');
else
result = (char) ((nibble - 10) + 'A');
return result;
}
/**
* Return a straight hexadecimal conversion of a byte array. This is a String containing only
* hex digits.
*
* @param bytes the byte array
* @return the hex version
*/
private static String binToHex(byte[] bytes) {
int byteLength = bytes.length;
char[] chars = new char[byteLength * 2];
int charIndex = 0;
for (int byteIndex = 0; byteIndex < byteLength; byteIndex++) {
byte b = bytes[byteIndex];
chars[charIndex++] = binToHexNibble((b >> 4) & 0xf);
chars[charIndex++] = binToHexNibble(b & 0xf);
}
return new String(chars);
}
/**
* Returns a String representation.
*
* @return the String representation
*/
public String toString() {
if (strValue == null)
strValue = binToHex(value);
return "HexBinaryAttribute: [\n" + strValue + "]\n";
}
/**
*
*/
public String encode() {
if (strValue == null)
strValue = binToHex(value);
return strValue;
}
}
| 9,751 | 31.945946 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/YearMonthDurationAttribute.java | /*
* @(#)YearMonthDurationAttribute.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import org.wso2.balana.ParsingException;
import java.math.BigInteger;
import java.net.URI;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.regex.Matcher;
import org.w3c.dom.Node;
/**
* Representation of an xf:yearMonthDuration value. This class supports parsing xd:yearMonthDuration
* values. All objects of this class are immutable and thread-safe. The <code>Date</code> objects
* returned are not, but these objects are cloned before being returned.
*
* @since 1.0
* @author Steve Hanna
*/
public class YearMonthDurationAttribute extends AttributeValue {
/**
* Official name of this type
*/
public static final String identifier = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#"
+ "yearMonthDuration";
/**
* URI version of name for this type
* <p>
* This field is initialized by a static initializer so that we can catch any exceptions thrown
* by URI(String) and transform them into a RuntimeException, since this should never happen but
* should be reported properly if it ever does.
*/
private static URI identifierURI;
/**
* RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if
* none.
*/
private static RuntimeException earlyException;
/**
* Static initializer that initializes the identifierURI class field so that we can catch any
* exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions
* should never happen but should be reported properly if they ever do.
*/
static {
try {
identifierURI = new URI(identifier);
} catch (Exception e) {
earlyException = new IllegalArgumentException();
earlyException.initCause(e);
}
};
/**
* Regular expression for yearMonthDuration (a la java.util.regex)
*/
private static final String patternString = "(\\-)?P((\\d+)?Y)?((\\d+)?M)?";
/**
* The index of the capturing group for the negative sign.
*/
private static final int GROUP_SIGN = 1;
/**
* The index of the capturing group for the number of years.
*/
private static final int GROUP_YEARS = 3;
/**
* The index of the capturing group for the number of months.
*/
private static final int GROUP_MONTHS = 5;
/**
* Static BigInteger values. We only use these if one of the components is bigger than
* Integer.MAX_LONG and we want to detect overflow, so we don't initialize these until they're
* needed.
*/
private static BigInteger big12 = BigInteger.valueOf(12);
private static BigInteger bigMaxLong = BigInteger.valueOf(Long.MAX_VALUE);
/**
* A shared Pattern object, only initialized if needed
*/
private static Pattern pattern;
/**
* Negative flag. true if duration is negative, false otherwise
*/
private boolean negative;
/**
* Number of years
*/
private long years;
/**
* Number of months
*/
private long months;
/**
* Total number of months (used for equals)
*/
private long totalMonths;
/**
* Cached encoded value (null if not cached yet).
*/
private String encodedValue = null;
/**
* Creates a new <code>YearMonthDurationAttribute</code> that represents the duration supplied.
*
* @param negative true if the duration is negative, false otherwise
* @param years the number of years in the duration (must be positive)
* @param months the number of months in the duration (must be positive)
* @throws IllegalArgumentException if the total number of months exceeds Long.MAX_LONG or the
* number of months or years is negative
*/
public YearMonthDurationAttribute(boolean negative, long years, long months)
throws IllegalArgumentException {
super(identifierURI);
// Shouldn't happen, but just in case...
if (earlyException != null)
throw earlyException;
this.negative = negative;
this.years = years;
this.months = months;
// Convert all the components except nanoseconds to milliseconds
// If any of the components is big (too big to be an int),
// use the BigInteger class to do the math so we can detect
// overflow.
if ((years > Integer.MAX_VALUE) || (months > Integer.MAX_VALUE)) {
BigInteger bigMonths = BigInteger.valueOf(months);
BigInteger bigYears = BigInteger.valueOf(years);
BigInteger bigTotal = bigYears.multiply(big12).add(bigMonths);
// If the result is bigger than Long.MAX_VALUE, we have an
// overflow. Indicate an error (should be a processing error,
// since it can be argued that we should handle gigantic
// values for this).
if (bigTotal.compareTo(bigMaxLong) == 1)
throw new IllegalArgumentException("total number of " + "months "
+ "exceeds Long.MAX_VALUE");
// If no overflow, convert to a long.
totalMonths = bigTotal.longValue();
if (negative)
totalMonths = -totalMonths;
} else {
// The numbers are small, so do it the fast way.
totalMonths = ((years * 12) + months) * (negative ? -1 : 1);
}
}
/**
* Returns a new <code>YearMonthDurationAttribute</code> that represents the
* xf:yearMonthDuration at a particular DOM node.
*
* @param root the <code>Node</code> that contains the desired value
* @return a new <code>YearMonthDurationAttribute</code> representing the appropriate value
* @throws ParsingException if any problems occurred while parsing
*/
public static YearMonthDurationAttribute getInstance(Node root) throws ParsingException {
return getInstance(root.getFirstChild().getNodeValue());
}
/**
* Returns the long value for the capturing group groupNumber. This method takes a Matcher that
* has been used to match a Pattern against a String, fetches the value for the specified
* capturing group, converts that value to an long, and returns the value. If that group did not
* match, 0 is returned. If the matched value is not a valid long, NumberFormatException is
* thrown.
*
* @param matcher the Matcher from which to fetch the group
* @param groupNumber the group number to fetch
* @return the long value for that groupNumber
* @throws NumberFormatException if the string value for that groupNumber is not a valid long
*/
private static long parseGroup(Matcher matcher, int groupNumber) throws NumberFormatException {
long groupLong = 0;
if (matcher.start(groupNumber) != -1) {
String groupString = matcher.group(groupNumber);
groupLong = Long.parseLong(groupString);
}
return groupLong;
}
/**
* Returns a new <code>YearMonthDurationAttribute</code> that represents the
* xf:yearMonthDuration value indicated by the string provided.
*
* @param value a string representing the desired value
*
* @return a new <code>YearMonthDurationAttribute</code> representing the desired value
*
* @throws ParsingException if any problems occurred while parsing
*/
public static YearMonthDurationAttribute getInstance(String value) throws ParsingException {
boolean negative = false;
long years = 0;
long months = 0;
// Compile the pattern, if not already done.
if (pattern == null) {
try {
pattern = Pattern.compile(patternString);
} catch (PatternSyntaxException e) {
// This should never happen
throw new ParsingException("unexpected pattern syntax error");
}
}
// See if the value matches the pattern.
Matcher matcher = pattern.matcher(value);
boolean matches = matcher.matches();
// If not, syntax error!
if (!matches) {
throw new ParsingException("Syntax error in yearMonthDuration");
}
// If the negative group matched, the value is negative.
if (matcher.start(GROUP_SIGN) != -1)
negative = true;
try {
// If the years group matched, parse that value.
years = parseGroup(matcher, GROUP_YEARS);
// If the months group matched, parse that value.
months = parseGroup(matcher, GROUP_MONTHS);
} catch (NumberFormatException e) {
// If we run into a number that's too big to be a long
// that's an error. Really, it's a processing error,
// since one can argue that we should handle that.
throw new ParsingException("Unable to handle number size");
}
// If parsing went OK, create a new YearMonthDurationAttribute
// object and return it.
return new YearMonthDurationAttribute(negative, years, months);
}
/**
* Returns true if the duration is negative.
*
* @return true if the duration is negative, false otherwise
*/
public boolean isNegative() {
return negative;
}
/**
* Gets the number of years.
*
* @return the number of years
*/
public long getYears() {
return years;
}
/**
* Gets the number of months.
*
* @return the number of months
*/
public long getMonths() {
return months;
}
/**
* Returns true if the input is an instance of this class and if its value equals the value
* contained in this class.
*
* @param o the object to compare
*
* @return true if this object and the input represent the same value
*/
public boolean equals(Object o) {
if (!(o instanceof YearMonthDurationAttribute))
return false;
YearMonthDurationAttribute other = (YearMonthDurationAttribute) o;
return (totalMonths == other.totalMonths);
}
/**
* Returns the hashcode value used to index and compare this object with others of the same
* type. Typically this is the hashcode of the backing data object.
*
* @return the object's hashcode value
*/
public int hashCode() {
return (int) totalMonths ^ (int) (totalMonths >> 32);
}
/**
* Converts to a String representation.
*
* @return the String representation
*/
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("YearMonthDurationAttribute: [\n");
sb.append(" Negative: " + negative);
sb.append(" Years: " + years);
sb.append(" Months: " + months);
sb.append("]");
return sb.toString();
}
/**
* Encodes the value in a form suitable for including in XML data like a request or an
* obligation. This must return a value that could in turn be used by the factory to create a
* new instance with the same value.
*
* @return a <code>String</code> form of the value
*/
public String encode() {
if (encodedValue != null)
return encodedValue;
// Length is variable
StringBuffer buf = new StringBuffer(10);
if (negative)
buf.append('-');
buf.append('P');
if ((years != 0) || (months == 0)) {
buf.append(Long.toString(years));
buf.append('Y');
}
if (months != 0) {
buf.append(Long.toString(months));
buf.append('M');
}
encodedValue = buf.toString();
return encodedValue;
}
}
| 12,412 | 30.585242 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/AttributeSelectorFactory.java | /*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.attr;
import org.w3c.dom.Node;
import org.wso2.balana.ParsingException;
import org.wso2.balana.PolicyMetaData;
import org.wso2.balana.XACMLConstants;
/**
*
*/
public class AttributeSelectorFactory {
private static volatile AttributeSelectorFactory factoryInstance;
public AbstractAttributeSelector getAbstractSelector(Node root, PolicyMetaData metaData)
throws ParsingException {
if(metaData.getXACMLVersion() == XACMLConstants.XACML_VERSION_3_0){
return org.wso2.balana.attr.xacml3.AttributeSelector.getInstance(root, metaData);
} else {
return org.wso2.balana.attr.AttributeSelector.getInstance(root, metaData);
}
}
/**
* Returns an instance of this factory. This method enforces a singleton model, meaning that
* this always returns the same instance, creating the factory if it hasn't been requested
* before.
*
* @return the factory instance
*/
public static AttributeSelectorFactory getFactory() {
if (factoryInstance == null) {
synchronized (AttributeDesignatorFactory.class) {
if (factoryInstance == null) {
factoryInstance = new AttributeSelectorFactory();
}
}
}
return factoryInstance;
}
}
| 2,065 | 31.793651 | 97 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/AttributeFactory.java | /*
* @(#)AttributeFactory.java
*
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import org.wso2.balana.ParsingException;
import org.wso2.balana.UnknownIdentifierException;
import java.net.URI;
import java.util.HashMap;
import java.util.Set;
import org.w3c.dom.Node;
import org.wso2.balana.XACMLConstants;
/**
* This is an abstract factory class for creating XACML attribute values. There may be any number of
* factories available in the system, though there is always one default factory used by the core
* code.
*
* @since 1.0
* @author Seth Proctor
* @author Marco Barreno
*/
public abstract class AttributeFactory {
// the proxy used to get the default factory
private static AttributeFactoryProxy defaultFactoryProxy;
// the map of registered factories
private static HashMap registeredFactories;
/**
* static intialiazer that sets up the default factory proxy and registers the standard
* namespaces
*/
static {
AttributeFactoryProxy proxy = new AttributeFactoryProxy() {
public AttributeFactory getFactory() {
return StandardAttributeFactory.getFactory();
}
};
registeredFactories = new HashMap();
registeredFactories.put(XACMLConstants.XACML_1_0_IDENTIFIER, proxy);
registeredFactories.put(XACMLConstants.XACML_2_0_IDENTIFIER, proxy);
registeredFactories.put(XACMLConstants.XACML_3_0_IDENTIFIER, proxy);
defaultFactoryProxy = proxy;
};
/**
* Default constructor. Used only by subclasses.
*/
protected AttributeFactory() {
}
/**
* Returns the default factory. Depending on the default factory's implementation, this may
* return a singleton instance or new instances with each invokation.
*
* @return the default <code>AttributeFactory</code>
*/
public static final AttributeFactory getInstance() {
return defaultFactoryProxy.getFactory();
}
/**
* Returns a factory based on the given identifier. You may register as many factories as you
* like, and then retrieve them through this interface, but a factory may only be registered
* once using a given identifier. By default, the standard XACML 1.0 and 2.0 identifiers are
* regsietered to provide the standard factory.
*
* @param identifier the identifier for a factory
*
* @return an <code>AttributeFactory</code>
*
* @throws UnknownIdentifierException if the given identifier isn't registered
*/
public static final AttributeFactory getInstance(String identifier)
throws UnknownIdentifierException {
AttributeFactoryProxy proxy = (AttributeFactoryProxy) (registeredFactories.get(identifier));
if (proxy == null)
throw new UnknownIdentifierException("Uknown AttributeFactory " + "identifier: "
+ identifier);
return proxy.getFactory();
}
/**
* Sets the default factory. This does not register the factory proxy as an identifiable
* factory.
*
* @param proxy the <code>AttributeFactoryProxy</code> to set as the new default factory proxy
*/
public static final void setDefaultFactory(AttributeFactoryProxy proxy) {
defaultFactoryProxy = proxy;
}
/**
* Registers the given factory proxy with the given identifier. If the identifier is already
* used, then this throws an exception. If the identifier is not already used, then it will
* always be bound to the given proxy.
*
* @param identifier the identifier for the proxy
* @param proxy the <code>AttributeFactoryProxy</code> to register with the given identifier
*
* @throws IllegalArgumentException if the identifier is already used
*/
public static final void registerFactory(String identifier, AttributeFactoryProxy proxy)
throws IllegalArgumentException {
synchronized (registeredFactories) {
if (registeredFactories.containsKey(identifier))
throw new IllegalArgumentException("Identifier is already " + "registered as "
+ "AttributeFactory: " + identifier);
registeredFactories.put(identifier, proxy);
}
}
/**
* Adds a proxy to the factory, which in turn will allow new attribute types to be created using
* the factory. Typically the proxy is provided as an anonymous class that simply calls the
* getInstance methods (or something similar) of some <code>AttributeValue</code> class.
*
* @param id the name of the attribute type
* @param proxy the proxy used to create new attributes of the given type
*
* @throws IllegalArgumentException if the given id is already in use
*/
public abstract void addDatatype(String id, AttributeProxy proxy);
/**
* Returns the datatype identifiers supported by this factory.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public abstract Set getSupportedDatatypes();
/**
* Creates a value based on the given DOM root node. The type of the attribute is assumed to be
* present in the node as an XAML attribute named <code>DataType</code>, as is the case with the
* AttributeValueType in the policy schema. The value is assumed to be the first child of this
* node.
*
* @param root the DOM root of an attribute value
*
* @return a new <code>AttributeValue</code>
*
* @throws UnknownIdentifierException if the type in the node isn't known to the factory
* @throws ParsingException if the node is invalid or can't be parsed by the appropriate proxy
*/
public abstract AttributeValue createValue(Node root) throws UnknownIdentifierException,
ParsingException;
/**
* Creates a value based on the given DOM root node and data type.
*
* @param root the DOM root of an attribute value
* @param dataType the type of the attribute
*
* @return a new <code>AttributeValue</code>
*
* @throws UnknownIdentifierException if the data type isn't known to the factory
* @throws ParsingException if the node is invalid or can't be parsed by the appropriate proxy
*/
public abstract AttributeValue createValue(Node root, URI dataType)
throws UnknownIdentifierException, ParsingException;
/**
* Creates a value based on the given DOM root node and data type.
*
* @param root the DOM root of an attribute value
* @param type the type of the attribute
*
* @return a new <code>AttributeValue</code>
*
* @throws UnknownIdentifierException if the type isn't known to the factory
* @throws ParsingException if the node is invalid or can't be parsed by the appropriate proxy
*/
public abstract AttributeValue createValue(Node root, String type)
throws UnknownIdentifierException, ParsingException;
/**
* Creates a value based on the given data type and text-encoded value. Used primarily by code
* that does an XPath query to get an attribute value, and then needs to turn the resulting
* value into an Attribute class.
*
* @param dataType the type of the attribute
* @param value the text-encoded representation of an attribute's value
* @return a new <code>AttributeValue</code>
*
* @throws UnknownIdentifierException if the data type isn't known to the factory
* @throws ParsingException if the text is invalid or can't be parsed by the appropriate proxy
*/
public AttributeValue createValue(URI dataType, String value)
throws UnknownIdentifierException, ParsingException {
return createValue(dataType, value, null);
}
/**
* Creates a value based on the given data type and text-encoded value. Used primarily by code
* that does an XPath query to get an attribute value, and then needs to turn the resulting
* value into an Attribute class.
*
* @param dataType the type of the attribute
* @param value the text-encoded representation of an attribute's value
* @param params additional parameters that need to creates a value
* @return a new <code>AttributeValue</code>
*
* @throws UnknownIdentifierException if the data type isn't known to the factory
* @throws ParsingException if the text is invalid or can't be parsed by the appropriate proxy
*/
public abstract AttributeValue createValue(URI dataType, String value, String[] params)
throws UnknownIdentifierException, ParsingException;
}
| 10,469 | 40.220472 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/PortRange.java | /*
* @(#)PortRange.java
*
* Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
/**
* This class represents a port range as specified in the XACML 2.0 description of
* <code>dnsName</code> and <code>ipAddress</code>. The range may have upper and lower bounds, be
* specified by a single port number, or may be unbound.
*
* @since 2.0
* @author Seth Proctor
*/
public class PortRange {
/**
* Constant used to specify that the range is unbound on one side.
*/
public static final int UNBOUND = -1;
// the port bound values
private int lowerBound;
private int upperBound;
/**
* Default constructor used to represent an unbound range. This is typically used when an
* address has no port information.
*/
public PortRange() {
this(UNBOUND, UNBOUND);
}
/**
* Creates a <code>PortRange</code> that represents a single port value instead of a range of
* values.
*
* @param singlePort the single port number
*/
public PortRange(int singlePort) {
this(singlePort, singlePort);
}
/**
* Creates a <code>PortRange</code> with upper and lower bounds. Either of the parameters may
* have the value <code>UNBOUND</code> meaning that there is no bound at the respective end.
*
* @param lowerBound the lower-bound port number or <code>UNBOUND</code>
* @param upperBound the upper-bound port number or <code>UNBOUND</code>
*/
public PortRange(int lowerBound, int upperBound) {
this.lowerBound = lowerBound;
this.upperBound = upperBound;
}
/**
* Creates an instance of <code>PortRange</code> based on the given value.
*
* @param value a <code>String</code> representing the range
*
* @return a new <code>PortRange</code>
*
* @throws NumberFormatException if a port value isn't an integer
*/
public static PortRange getInstance(String value) {
int lowerBound = UNBOUND;
int upperBound = UNBOUND;
// first off, make sure there's actually content here
if ((value.length() == 0) || (value.equals("-")))
return new PortRange();
// there's content, so figure where the '-' is, if at all
int dashPos = value.indexOf('-');
if (dashPos == -1) {
// there's no dash, so it's just a single number
lowerBound = upperBound = Integer.parseInt(value);
} else if (dashPos == 0) {
// it starts with a dash, so it's just upper-range bound
upperBound = Integer.parseInt(value.substring(1));
} else {
// it's a number followed by a dash, so get the lower-bound...
lowerBound = Integer.parseInt(value.substring(0, dashPos));
int len = value.length();
// ... and see if there is a second port number
if (dashPos != (len - 1)) {
// the dash wasn't at the end, so there's an upper-bound
upperBound = Integer.parseInt(value.substring(dashPos + 1, len));
}
}
return new PortRange(lowerBound, upperBound);
}
/**
* Returns the lower-bound port value. If the range is not lower-bound, then this returns
* <code>UNBOUND</code>. If the range is actually a single port number, then this returns the
* same value as <code>getUpperBound</code>.
*
* @return the upper-bound
*/
public int getLowerBound() {
return lowerBound;
}
/**
* Returns the upper-bound port value. If the range is not upper-bound, then this returns
* <code>UNBOUND</code>. If the range is actually a single port number, then this returns the
* same value as <code>getLowerBound</code>.
*
* @return the upper-bound
*/
public int getUpperBound() {
return upperBound;
}
/**
* Returns whether the range is bounded by a lower port number.
*
* @return true if lower-bounded, false otherwise
*/
public boolean isLowerBounded() {
return (lowerBound != -1);
}
/**
* Returns whether the range is bounded by an upper port number.
*
* @return true if upper-bounded, false otherwise
*/
public boolean isUpperBounded() {
return (upperBound != -1);
}
/**
* Returns whether the range is actually a single port number.
*
* @return true if the range is a single port number, false otherwise
*/
public boolean isSinglePort() {
return ((lowerBound == upperBound) && (lowerBound != UNBOUND));
}
/**
* Returns whether the range is unbound, which means that it specifies no port number or range.
* This is typically used with addresses that include no port information.
*
* @return true if the range is unbound, false otherwise
*/
public boolean isUnbound() {
return ((lowerBound == UNBOUND) && (upperBound == UNBOUND));
}
/**
* Returns true if the input is an instance of this class and if its value equals the value
* contained in this class.
*
* @param o the object to compare
*
* @return true if this object and the input represent the same value
*/
public boolean equals(Object o) {
if (!(o instanceof PortRange))
return false;
PortRange other = (PortRange) o;
if (lowerBound != other.lowerBound)
return false;
if (upperBound != other.upperBound)
return false;
return true;
}
@Override
public int hashCode() {
int result = lowerBound;
result = 31 * result + upperBound;
return result;
}
/**
*
*/
public String encode() {
if (isUnbound())
return "";
if (isSinglePort())
return String.valueOf(lowerBound);
if (!isLowerBounded())
return "-" + String.valueOf(upperBound);
if (!isUpperBounded())
return String.valueOf(lowerBound) + "-";
return String.valueOf(lowerBound) + "-" + String.valueOf(upperBound);
}
}
| 7,940 | 32.225941 | 99 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/AttributeDesignatorFactory.java | /*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.balana.attr;
import org.w3c.dom.Node;
import org.wso2.balana.ParsingException;
import org.wso2.balana.PolicyMetaData;
import org.wso2.balana.XACMLConstants;
import org.wso2.balana.attr.xacml3.AttributeDesignator;
/**
*
*/
public class AttributeDesignatorFactory {
private static volatile AttributeDesignatorFactory factoryInstance;
public AbstractDesignator getAbstractDesignator(Node root, PolicyMetaData metaData)
throws ParsingException {
if(metaData.getXACMLVersion() == XACMLConstants.XACML_VERSION_3_0){
return AttributeDesignator.getInstance(root);
} else {
return org.wso2.balana.attr.AttributeDesignator.getInstance(root);
}
}
/**
* Returns an instance of this factory. This method enforces a singleton model, meaning that
* this always returns the same instance, creating the factory if it hasn't been requested
* before.
*
* @return the factory instance
*/
public static AttributeDesignatorFactory getFactory() {
if (factoryInstance == null) {
synchronized (AttributeDesignatorFactory.class) {
if (factoryInstance == null) {
factoryInstance = new AttributeDesignatorFactory();
}
}
}
return factoryInstance;
}
}
| 2,080 | 31.515625 | 97 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/DNSNameAttribute.java | /*
* @(#)DNSNameAttribute.java
*
* Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import org.wso2.balana.ParsingException;
import java.net.URI;
import org.w3c.dom.Node;
/**
* Represents the DNSName datatype introduced in XACML 2.0. All objects of this class are immutable
* and all methods of the class are thread-safe.
*
* @since 2.0
* @author Seth Proctor
*/
public class DNSNameAttribute extends AttributeValue {
/**
* Official name of this type
*/
public static final String identifier = "urn:oasis:names:tc:xacml:2.0:data-type:dnsName";
/**
* URI version of name for this type
* <p>
* This field is initialized by a static initializer so that we can catch any exceptions thrown
* by URI(String) and transform them into a RuntimeException, since this should never happen but
* should be reported properly if it ever does.
*/
private static URI identifierURI;
/**
* RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if
* none.
*/
private static RuntimeException earlyException;
/**
* Static initializer that initializes the identifierURI class field so that we can catch any
* exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions
* should never happen but should be reported properly if they ever do.
*/
static {
try {
identifierURI = new URI(identifier);
} catch (Exception e) {
earlyException = new IllegalArgumentException();
earlyException.initCause(e);
}
};
// the required hostname
private String hostname;
// the optional port range
private PortRange range;
// true if the hostname starts with a '*'
private boolean isSubdomain = false;
/**
* Creates the new <code>DNSNameAttribute</code> with only the required hostname component.
*
* @param hostname the host name component of the address
*
* @throws ParsingException if the hostname is invalid
*/
public DNSNameAttribute(String hostname) throws ParsingException {
this(hostname, new PortRange());
}
/**
* Creates the new <code>DNSNameAttribute</code> with the optional port range component.
*
* @param hostname the host name component of the address
* @param range the port range
*
* @throws ParsingException if the hostname is invalid
*/
public DNSNameAttribute(String hostname, PortRange range) throws ParsingException {
super(identifierURI);
// shouldn't happen, but just in case...
if (earlyException != null)
throw earlyException;
// verify that the hostname is valid before we store it
if (!isValidHostName(hostname))
System.out.println("FIXME: throw error about bad hostname");
// see if it started with a '*' character
if (hostname.charAt(0) == '*')
this.isSubdomain = true;
this.hostname = hostname;
this.range = range;
}
/**
* Private helper that tests whether the given string is valid.
*/
private boolean isValidHostName(String hostname) {
/*
* hostname = *( domainlabel "." ) toplabel [ "." ] domainlabel = alphanum | alphanum *(
* alphanum | "-" ) alphanum toplabel = alpha | alpha *( alphanum | "-" ) alphanum
*/
String domainlabel = "\\w[[\\w|\\-]*\\w]?";
String toplabel = "[a-zA-Z][[\\w|\\-]*\\w]?";
String pattern = "[\\*\\.]?[" + domainlabel + "\\.]*" + toplabel + "\\.?";
return hostname.matches(pattern);
}
/**
* Returns a new <code>DNSNameAttribute</code> that represents the name at a particular DOM
* node.
*
* @param root the <code>Node</code> that contains the desired value
*
* @return a new <code>DNSNameAttribute</code> representing the appropriate value (null if there
* is a parsing error)
*
* @throws ParsingException if the hostname is invalid
*/
public static DNSNameAttribute getInstance(Node root) throws ParsingException {
return getInstance(root.getFirstChild().getNodeValue());
}
/**
* Returns a new <code>DNSNameAttribute</code> that represents the name indicated by the
* <code>String</code> provided.
*
* @param value a string representing the name
*
* @return a new <code>DNSNameAttribute</code>
*
* @throws ParsingException if the hostname is invalid
*/
public static DNSNameAttribute getInstance(String value) throws ParsingException {
int portSep = value.indexOf(':');
if (portSep == -1) {
// there is no port range, so just use the name
return new DNSNameAttribute(value);
} else {
// split the name and the port range
String hostname = value.substring(0, portSep);
PortRange range = PortRange.getInstance(value.substring(portSep + 1, value.length()));
return new DNSNameAttribute(hostname, range);
}
}
/**
* Returns the host name represented by this object.
*
* @return the host name
*/
public String getHostName() {
return hostname;
}
/**
* Returns the port range represented by this object which will be unbound if no range was
* specified.
*
* @return the port range
*/
public PortRange getPortRange() {
return range;
}
/**
* Returns true if the leading character in the hostname is a '*', and therefore represents a
* matching subdomain, or false otherwise.
*
* @return true if the name represents a subdomain, false otherwise
*/
public boolean isSubdomain() {
return isSubdomain;
}
/**
* Returns true if the input is an instance of this class and if its value equals the value
* contained in this class.
*
* @param o the object to compare
*
* @return true if this object and the input represent the same value
*/
public boolean equals(Object o) {
if (!(o instanceof DNSNameAttribute))
return false;
DNSNameAttribute other = (DNSNameAttribute) o;
if (!hostname.toUpperCase().equals(other.hostname.toUpperCase()))
return false;
if (!range.equals(other.range))
return false;
return true;
}
/**
* Returns the hashcode value used to index and compare this object with others of the same
* type.
*
* @return the object's hashcode value
*/
public int hashCode() {
// FIXME: what should the hashcode be?
return 0;
}
/**
* Converts to a String representation.
*
* @return the String representation
*/
public String toString() {
return "DNSNameAttribute: \"" + encode() + "\"";
}
/**
*
*/
public String encode() {
if (range.isUnbound())
return hostname;
return hostname + ":" + range.encode();
}
}
| 8,939 | 31.627737 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/DateAttribute.java | /*
* @(#)DateAttribute.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import java.net.URI;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.w3c.dom.Node;
/**
* Representation of an xs:date value. This class supports parsing xs:date values. All objects of
* this class are immutable and thread-safe. The <code>Date</code> objects returned are not, but
* these objects are cloned before being returned.
*
* @since 1.0
* @author Marco Barreno
* @author Seth Proctor
* @author Steve Hanna
*/
public class DateAttribute extends AttributeValue {
/**
* Official name of this type
*/
public static final String identifier = "http://www.w3.org/2001/XMLSchema#date";
/**
* URI version of name for this type
* <p>
* This field is initialized by a static initializer so that we can catch any exceptions thrown
* by URI(String) and transform them into a RuntimeException, since this should never happen but
* should be reported properly if it ever does.
* <p>
* This object is used for synchronization whenever we need protection across this whole class.
*/
private static URI identifierURI;
/**
* RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if
* none.
*/
private static RuntimeException earlyException;
/**
* Static initializer that initializes the identifierURI class field so that we can catch any
* exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions
* should never happen but should be reported properly if they ever do.
*/
static {
try {
identifierURI = new URI(identifier);
} catch (Exception e) {
earlyException = new IllegalArgumentException();
earlyException.initCause(e);
}
};
/**
* Parser for dates with no time zones
* <p>
* This field is only initialized if needed (by initParsers()).
* <p>
* NOTE: This object should only be accessed from code that has synchronized on it, since
* SimpleDateFormat objects are not thread-safe. If this is causing performance problems, we
* could easily make this a method variable in methods that use it instead of a class field. But
* that would mean we'd need to spend a lot more time creating these objects.
*/
private static volatile DateFormat simpleParser;
/**
* Parser for dates with RFC 822 time zones (like +0300)
* <p>
* This field is only initialized if needed (by initParsers()).
* <p>
* NOTE: This object should only be accessed from code that has a lock on it, since
* SimpleDateFormat objects are not thread-safe.
*/
private static DateFormat zoneParser;
/**
* Calendar for GMT
* <p>
* NOTE: This object should only be accessed from code that has a lock on it, since Calendar
* objects are not generally thread-safe.
*/
private static volatile Calendar gmtCalendar;
/**
* Number of nanoseconds per millisecond (shared by other classes in this package)
*/
static final int NANOS_PER_MILLI = 1000000;
/**
* Number of milliseconds per second (shared by other classes in this package)
*/
static final int MILLIS_PER_SECOND = 1000;
/**
* Number of seconds in a minute (shared by other classes in this package)
*/
static final int SECONDS_PER_MINUTE = 60;
/**
* Number of minutes in an hour (shared by other classes in this package)
*/
static final int MINUTES_PER_HOUR = 60;
/**
* Number of hours in a day (shared by other classes in this package)
*/
static final int HOURS_PER_DAY = 24;
/**
* Number of nanoseconds per second (shared by other classes in this package)
*/
static final int NANOS_PER_SECOND = NANOS_PER_MILLI * MILLIS_PER_SECOND;
/**
* Number of milliseconds in a minute (shared by other classes in this package)
*/
static final int MILLIS_PER_MINUTE = MILLIS_PER_SECOND * SECONDS_PER_MINUTE;
/**
* Number of milliseconds in an hour (shared by other classes in this package)
*/
static final int MILLIS_PER_HOUR = MILLIS_PER_MINUTE * MINUTES_PER_HOUR;
/**
* Number of milliseconds in a day (shared by other classes in this package)
*/
static final long MILLIS_PER_DAY = MILLIS_PER_HOUR * HOURS_PER_DAY;
/**
* Time zone value that indicates that the time zone was not specified.
*/
public static final int TZ_UNSPECIFIED = -1000000;
/**
* The instant (in GMT) at which the specified date began (midnight) in the specified time zone.
* If no time zone was specified, the local time zone is used.
*/
private Date value;
/**
* The time zone specified for this object (or TZ_UNSPECIFIED if unspecified). The offset to
* GMT, in minutes.
*/
private int timeZone;
/**
* The time zone actually used for this object (if it was originally unspecified, the default
* time zone used). The offset to GMT, in minutes.
*/
private int defaultedTimeZone;
/**
* Cached encoded value (null if not cached yet).
*/
private String encodedValue = null;
/**
* Creates a new <code>TimeAttribute</code> that represents the current date in the default time
* zone.
*/
public DateAttribute() {
this(new Date());
}
/**
* Creates a new <code>TimeAttribute</code> that represents the given date with default timezone
* values.
*
* @param date a <code>Date</code> object representing the instant at which the specified date
* began (midnight) in the specified time zone (the actual time value will be forced
* to midnight)
*/
public DateAttribute(Date date) {
super(identifierURI);
// Get the current time and GMT offset
int currOffset = DateTimeAttribute.getDefaultTZOffset(date);
long millis = date.getTime();
// Now find out the last time it was midnight local time
// (actually the last time it was midnight with the current
// GMT offset, but that's good enough).
// Skip back by time zone offset.
millis += currOffset * MILLIS_PER_MINUTE;
// Reset to last GMT midnight
millis -= millis % MILLIS_PER_DAY;
// Skip forward by time zone offset.
millis -= currOffset * MILLIS_PER_MINUTE;
date.setTime(millis);
init(date, currOffset, currOffset);
}
/**
* Creates a new <code>DateAttribute</code> that represents the date supplied.
*
* @param date a <code>Date</code> object representing the instant at which the specified date
* began (midnight) in the specified time zone
* @param timeZone the time zone specified for this object (or TZ_UNSPECIFIED if unspecified).
* The offset to GMT, in minutes.
* @param defaultedTimeZone the time zone actually used for this object (if it was originally
* unspecified, the default time zone used). The offset to GMT, in minutes.
*/
public DateAttribute(Date date, int timeZone, int defaultedTimeZone) {
super(identifierURI);
init(date, timeZone, defaultedTimeZone);
}
/**
* Initialization code shared by constructors.
*
* @param date a <code>Date</code> object representing the instant at which the specified date
* began (midnight) in the specified time zone.
* @param timeZone the time zone specified for this object (or TZ_UNSPECIFIED if unspecified).
* The offset to GMT, in minutes.
* @param defaultedTimeZone the time zone actually used for this object (if it was originally
* unspecified, the default time zone used). The offset to GMT, in minutes.
*/
private void init(Date date, int timeZone, int defaultedTimeZone) {
// Shouldn't happen, but just in case...
if (earlyException != null)
throw earlyException;
this.value = (Date) date.clone();
this.timeZone = timeZone;
this.defaultedTimeZone = defaultedTimeZone;
}
/**
* Returns a new <code>DateAttribute</code> that represents the xs:date at a particular DOM
* node.
*
* @param root the <code>Node</code> that contains the desired value
* @return a new <code>DateAttribute</code> representing the appropriate value (null if there is
* a parsing error)
*/
public static DateAttribute getInstance(Node root) throws ParseException {
return getInstance(root.getFirstChild().getNodeValue());
}
/**
* Returns a new <code>DateAttribute</code> that represents the xs:date value indicated by the
* string provided.
*
* @param value a string representing the desired value
* @return a new <code>DateAttribute</code> representing the desired value (null if there is a
* parsing error)
*/
public static DateAttribute getInstance(String value) throws ParseException {
Date dateValue = null;
int timeZone;
int defaultedTimeZone;
if (simpleParser == null)
initParsers();
// If string ends with Z, it's in GMT. Chop off the Z and
// add +0000 to make the time zone explicit, then parse it
// with the timezone parser.
if (value.endsWith("Z")) {
value = value.substring(0, value.length() - 1) + "+0000";
dateValue = strictParse(zoneParser, value);
timeZone = 0;
defaultedTimeZone = 0;
} else {
// If string ends with :XX, it must have a time zone
// or be invalid. Strip off the possible time zone and
// make sure what's left is a valid simple date. If so,
// reformat the time zone by stripping out the colon
// and parse the whole thing with the timezone parser.
int len = value.length();
if ((len > 6) && (value.charAt(len - 3) == ':')) {
Date gmtValue = strictParse(zoneParser, value.substring(0, len - 6) + "+0000");
value = value.substring(0, len - 3) + value.substring(len - 2, len);
dateValue = strictParse(zoneParser, value);
timeZone = (int) (gmtValue.getTime() - dateValue.getTime());
timeZone = timeZone / 60000;
defaultedTimeZone = timeZone;
} else {
// No funny business. This must be a simple date.
dateValue = strictParse(simpleParser, value);
timeZone = TZ_UNSPECIFIED;
Date gmtValue = strictParse(zoneParser, value + "+0000");
defaultedTimeZone = (int) (gmtValue.getTime() - dateValue.getTime());
defaultedTimeZone = defaultedTimeZone / 60000;
}
}
// If parsing went OK, create a new DateAttribute object and
// return it.
DateAttribute attr = new DateAttribute(dateValue, timeZone, defaultedTimeZone);
return attr;
}
/**
* Parse a String using a DateFormat parser, requiring that the entire String be consumed by the
* parser. On success, return a Date. On failure, throw a ParseException.
* <p>
* Synchronize on the parser object when using it, since we assume they're the shared static
* objects in this class.
*/
private static Date strictParse(DateFormat parser, String str) throws ParseException {
ParsePosition pos = new ParsePosition(0);
Date ret;
synchronized (parser) {
ret = parser.parse(str, pos);
}
if (pos.getIndex() != str.length())
throw new ParseException("", 0);
return ret;
}
/**
* Initialize the parser objects.
*/
private static void initParsers() {
// If simpleParser is already set, we're done.
if (simpleParser != null)
return;
// Make sure that identifierURI is not null
if (earlyException != null)
throw earlyException;
// Synchronize on identifierURI while initializing parsers
// so we don't end up using a half-way initialized parser
synchronized (identifierURI) {
// This simple parser has no time zone
simpleParser = new SimpleDateFormat("yyyy-MM-dd");
simpleParser.setLenient(false);
// This parser has a four digit offset to GMT with sign
zoneParser = new SimpleDateFormat("yyyy-MM-ddZ");
zoneParser.setLenient(false);
}
}
/**
* Gets the date represented by this object. The return value is a <code>Date</code> object
* representing the instant at which the specified date began (midnight) in the time zone.
* <p>
* <b>NOTE:</b> The <code>Date</code> object is cloned before it is returned to avoid
* unauthorized changes.
*
* @return a <code>Date</code> object representing the instant at which the date began
*/
public Date getValue() {
return (Date) value.clone();
}
/**
* Gets the specified time zone of this object (or TZ_UNSPECIFIED if unspecified).
*
* @return the offset to GMT in minutes (positive or negative)
*/
public int getTimeZone() {
return timeZone;
}
/**
* Gets the time zone actually used for this object (if it was originally unspecified, the
* default time zone used).
*
* @return the offset to GMT in minutes (positive or negative)
*/
public int getDefaultedTimeZone() {
return defaultedTimeZone;
}
/**
* Returns true if the input is an instance of this class and if its value equals the value
* contained in this class.
* <p>
* Two <code>DateAttribute</code>s are equal if and only if the instant on which the date began
* is equal. This means that they must have the same time zone.
*
* @param o the object to compare
*
* @return true if this object and the input represent the same value
*/
public boolean equals(Object o) {
if (!(o instanceof DateAttribute))
return false;
DateAttribute other = (DateAttribute) o;
return value.equals(other.value);
}
/**
* Returns the hashcode value used to index and compare this object with others of the same
* type.
*
* @return the object's hashcode value
*/
public int hashCode() {
// Only the value field is considered by the equals method, so only
// that field should be considered by this method.
return value.hashCode();
}
/**
* Converts to a String representation.
*
* @return the String representation
*/
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("DateAttribute: [\n");
sb.append(" Date: " + value + " local time");
sb.append(" TimeZone: " + timeZone);
sb.append(" Defaulted TimeZone: " + defaultedTimeZone);
sb.append("]");
return sb.toString();
}
/**
* Encodes the value in a form suitable for including in XML data like a request or an
* obligation. This must return a value that could in turn be used by the factory to create a
* new instance with the same value.
*
* @return a <code>String</code> form of the value
*/
public String encode() {
if (encodedValue != null)
return encodedValue;
if (timeZone == TZ_UNSPECIFIED) {
// If no time zone was specified, format Date value in
// local time with no time zone string.
initParsers();
synchronized (simpleParser) {
encodedValue = simpleParser.format(value);
}
} else {
// If a time zone was specified, don't use SimpleParser
// because it can only format dates in the local (default)
// time zone. And the offset between that time zone and the
// time zone we need to display can vary in complicated ways.
// Instead, do it ourselves using our formatDateWithTZ method.
encodedValue = formatDateWithTZ();
}
return encodedValue;
}
/**
* Encodes the value of this object as an xsi:date. Only for use when the time zone is
* specified.
*
* @return a <code>String</code> form of the value
*/
private String formatDateWithTZ() {
if (gmtCalendar == null) {
TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");
// Locale doesn't make much difference here. We don't use
// any of the strings in the Locale and we don't do anything
// that depends on week count conventions. We use the US
// locale because it's always around and it ensures that we
// will always get a Gregorian calendar, which is necessary
// for compliance with ISO 8501.
gmtCalendar = Calendar.getInstance(gmtTimeZone, Locale.US);
}
// "YYYY-MM-DD+hh:mm".length() = 16
// Length may be longer if years < -999 or > 9999
StringBuffer buf = new StringBuffer(16);
synchronized (gmtCalendar) {
// Start with the GMT instant when the date started in the
// specified time zone (would be 7:00 PM the preceding day
// if the specified time zone was +0500).
gmtCalendar.setTime(value);
// Bump by the timeZone (so we get the right date/time that
// that we want to format)
gmtCalendar.add(Calendar.MINUTE, timeZone);
// Now, assemble the string
int year = gmtCalendar.get(Calendar.YEAR);
buf.append(zeroPadInt(year, 4));
buf.append('-');
// JANUARY is 0
int month = gmtCalendar.get(Calendar.MONTH) + 1;
buf.append(zeroPadInt(month, 2));
buf.append('-');
int dom = gmtCalendar.get(Calendar.DAY_OF_MONTH);
buf.append(zeroPadInt(dom, 2));
}
int tzNoSign = timeZone;
if (timeZone < 0) {
tzNoSign = -tzNoSign;
buf.append('-');
} else
buf.append('+');
int tzHours = tzNoSign / 60;
buf.append(zeroPadInt(tzHours, 2));
buf.append(':');
int tzMinutes = tzNoSign % 60;
buf.append(zeroPadInt(tzMinutes, 2));
return buf.toString();
}
/**
* Takes a String representation of an integer (an optional sign followed by digits) and pads it
* with zeros on the left until it has at least the specified number of digits. Note that this
* function will work for an integer of any size: int, long, etc.
*
* @param unpadded the unpadded <code>String</code> (must have length of at least one)
* @param minDigits the minimum number of digits desired
* @return the padded <code>String</code>
*/
static String zeroPadIntString(String unpadded, int minDigits) {
int len = unpadded.length();
// Get the sign character (or 0 if none)
char sign = unpadded.charAt(0);
if ((sign != '-') && (sign != '+'))
sign = 0;
// The number of characters required is the number of digits,
// plus one for the sign if present.
int minChars = minDigits;
if (sign != 0)
minChars++;
// If we already have that many characters, we're done.
if (len >= minChars)
return unpadded;
// Otherwise, create the buffer
StringBuffer buf = new StringBuffer();
// Copy in the sign first, if present
if (sign != 0) {
buf.append(sign);
}
// Add the zeros
int zerosNeeded = minChars - len;
while (zerosNeeded-- != 0)
buf.append('0');
// Copy the rest of the unpadded string
if (sign != 0) {
// Skip sign
buf.append(unpadded.substring(1, len));
} else {
buf.append(unpadded);
}
return buf.toString();
}
/**
* Converts an integer to a base 10 string and pads it with zeros on the left until it has at
* least the specified number of digits. Note that the length of the resulting string will be
* greater than minDigits if the number is negative since the string will start with a minus
* sign.
*
* @param intValue the integer to convert
* @param minDigits the minimum number of digits desired
* @return the padded <code>String</code>
*/
static String zeroPadInt(int intValue, int minDigits) {
return zeroPadIntString(Integer.toString(intValue), minDigits);
}
}
| 22,999 | 36.037037 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/BaseAttributeFactory.java | /*
* @(#)BaseAttributeFactory.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import org.wso2.balana.ParsingException;
import org.wso2.balana.UnknownIdentifierException;
import java.net.URI;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.w3c.dom.Node;
/**
* This is a basic implementation of <code>AttributeFactory</code>. It implements the insertion and
* retrieval methods, but doesn't actually setup the factory with any datatypes.
* <p>
* Note that while this class is thread-safe on all creation methods, it is not safe to add support
* for a new datatype while creating an instance of a value. This follows from the assumption that
* most people will initialize these factories up-front, and then start processing without ever
* modifying the factories. If you need these mutual operations to be thread-safe, then you should
* write a wrapper class that implements the right synchronization.
*
* @since 1.2
* @author Seth Proctor
*/
public class BaseAttributeFactory extends AttributeFactory {
// the map of proxies
private HashMap attributeMap;
/**
* Default constructor.
*/
public BaseAttributeFactory() {
attributeMap = new HashMap();
}
/**
* Constructor that configures this factory with an initial set of supported datatypes.
*
* @param attributes a <code>Map</code> of <code>String</code>s to </code>AttributeProxy</code>s
*
* @throws IllegalArgumentException if any elements of the Map are not
* </code>AttributeProxy</code>s
*/
public BaseAttributeFactory(Map attributes) {
attributeMap = new HashMap();
Iterator it = attributes.keySet().iterator();
while (it.hasNext()) {
try {
String id = (it.next()).toString();
AttributeProxy proxy = (AttributeProxy) (attributes.get(id));
attributeMap.put(id, proxy);
} catch (ClassCastException cce) {
throw new IllegalArgumentException("an element of the map "
+ "was not an instance of " + "AttributeProxy");
}
}
}
/**
* Adds a proxy to the factory, which in turn will allow new attribute types to be created using
* the factory. Typically the proxy is provided as an anonymous class that simply calls the
* getInstance methods (or something similar) of some <code>AttributeValue</code> class.
*
* @param id the name of the attribute type
* @param proxy the proxy used to create new attributes of the given type
*/
public void addDatatype(String id, AttributeProxy proxy) {
// make sure this doesn't already exist
if (attributeMap.containsKey(id))
throw new IllegalArgumentException("datatype already exists");
attributeMap.put(id, proxy);
}
/**
* Returns the datatype identifiers supported by this factory.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public Set getSupportedDatatypes() {
return Collections.unmodifiableSet(attributeMap.keySet());
}
/**
* Creates a value based on the given DOM root node. The type of the attribute is assumed to be
* present in the node as an XACML attribute named <code>DataType</code>, as is the case with
* the AttributeValueType in the policy schema. The value is assumed to be the first child of
* this node.
*
* @param root the DOM root of an attribute value
*
* @return a new <code>AttributeValue</code>
*
* @throws UnknownIdentifierException if the type in the node isn't known to the factory
* @throws ParsingException if the node is invalid or can't be parsed by the appropriate proxy
*/
public AttributeValue createValue(Node root) throws UnknownIdentifierException,
ParsingException {
Node node = root.getAttributes().getNamedItem("DataType");
return createValue(root, node.getNodeValue());
}
/**
* Creates a value based on the given DOM root node and data type.
*
* @param root the DOM root of an attribute value
* @param dataType the type of the attribute
*
* @return a new <code>AttributeValue</code>
*
* @throws UnknownIdentifierException if the data type isn't known to the factory
* @throws ParsingException if the node is invalid or can't be parsed by the appropriate proxy
*/
public AttributeValue createValue(Node root, URI dataType) throws UnknownIdentifierException,
ParsingException {
return createValue(root, dataType.toString());
}
/**
* Creates a value based on the given DOM root node and data type.
*
* @param root the DOM root of an attribute value
* @param type the type of the attribute
*
* @return a new <code>AttributeValue</code>
*
* @throws UnknownIdentifierException if the type isn't known to the factory
* @throws ParsingException if the node is invalid or can't be parsed by the appropriate proxy
*/
public AttributeValue createValue(Node root, String type) throws UnknownIdentifierException,
ParsingException {
AttributeValue attributeValue;
AttributeProxy proxy = (AttributeProxy) (attributeMap.get(type));
if (proxy != null) {
try {
attributeValue = proxy.getInstance(root);
} catch (Exception e) {
throw new ParsingException("couldn't create " + type
+ " attribute based on DOM node");
}
} else {
throw new UnknownIdentifierException("Attributes of type " + type
+ " aren't supported.");
}
if (attributeValue == null) {
throw new ParsingException("Could not create " + type + " attribute based on DOM node");
}
return attributeValue;
}
/**
* Creates a value based on the given data type and text-encoded value. Used primarily by code
* that does an XPath query to get an attribute value, and then needs to turn the resulting
* value into an Attribute class.
*
* @param dataType the type of the attribute
* @param value the text-encoded representation of an attribute's value
* @param params additional parameters that need to creates a value
* @return a new <code>AttributeValue</code>
*
* @throws UnknownIdentifierException if the data type isn't known to the factory
* @throws ParsingException if the text is invalid or can't be parsed by the appropriate proxy
*/
public AttributeValue createValue(URI dataType, String value, String[] params)
throws UnknownIdentifierException, ParsingException {
String type = dataType.toString();
AttributeProxy proxy = (AttributeProxy) (attributeMap.get(type));
if (proxy != null) {
try {
return proxy.getInstance(value, params);
} catch (Exception e) {
throw new ParsingException("couldn't create " + type + " attribute from input: "
+ value);
}
} else {
throw new UnknownIdentifierException("Attributes of type " + type
+ " aren't supported.");
}
}
}
| 9,235 | 39.508772 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/IPv4AddressAttribute.java | /*
* @(#)IPv4AddressAttribute.java
*
* Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Subclass of <code>IPAddressAttribute</code> that handles the specifics of IPv4. In general, you
* shouldn't need to interact with this class except to create an instance directly.
*
* @since 2.0
* @author Seth Proctor
*/
public class IPv4AddressAttribute extends IPAddressAttribute {
/**
* Creates the new <code>IPv4AddressAttribute</code> with just the required address component.
*
* @param address a non-null <code>InetAddress</code>
*/
public IPv4AddressAttribute(InetAddress address) {
this(address, null, new PortRange());
}
/**
* Creates the new <code>IPv4AddressAttribute</code> with the optional address mask.
*
* @param address a non-null <code>InetAddress</code>
* @param mask an <code>InetAddress</code> or null if there is no mask
*/
public IPv4AddressAttribute(InetAddress address, InetAddress mask) {
this(address, mask, new PortRange());
}
/**
* Creates the new <code>IPv4AddressAttribute</code> with the optional port range.
*
* @param address a non-null <code>InetAddress</code>
* @param portRange a non-null <code>PortRange</code>
*/
public IPv4AddressAttribute(InetAddress address, PortRange range) {
this(address, null, range);
}
/**
* Creates the new <code>IPv4AddressAttribute</code> with all the optional components.
*
* @param address a non-null <code>InetAddress</code>
* @param mask an <code>InetAddress</code> or null if there is no mask
* @param portRange a non-null <code>PortRange</code>
*/
public IPv4AddressAttribute(InetAddress address, InetAddress mask, PortRange range) {
super(address, mask, range);
}
/**
* Returns a new <code>IPv4AddressAttribute</code> that represents the name indicated by the
* <code>String</code> provided. This is a protected method because you should never call it
* directly. Instead, you should call <code>getInstance</code> on
* <code>IPAddressAttribute</code> which provides versions that take both a <code>String</code>
* and a <code>Node</code> and will determine the protocol version correctly.
*
* @param value a string representing the address
*
* @return a new <code>IPAddressAttribute</code>
*
* @throws UnknownHostException if the address components is invalid
* @throws ParsingException if any of the address components is invalid
*/
protected static IPAddressAttribute getV4Instance(String value) throws UnknownHostException {
InetAddress address = null;
InetAddress mask = null;
PortRange range = null;
// start out by seeing where the delimiters are
int maskPos = value.indexOf("/");
int rangePos = value.indexOf(":");
// now check to see which components we have
if (maskPos == rangePos) {
// the sting is just an address
address = InetAddress.getByName(value);
} else if (maskPos != -1) {
// there is also a mask (and maybe a range)
address = InetAddress.getByName(value.substring(0, maskPos));
if (rangePos != -1) {
// there's a range too, so get it and the mask
mask = InetAddress.getByName(value.substring(maskPos + 1, rangePos));
range = PortRange.getInstance(value.substring(rangePos + 1, value.length()));
} else {
// there's no range, so just get the mask
mask = InetAddress.getByName(value.substring(maskPos + 1, value.length()));
}
} else {
// there is a range, but no mask
address = InetAddress.getByName(value.substring(0, rangePos));
range = PortRange.getInstance(value.substring(rangePos + 1, value.length()));
}
// if the range is null, then create it as unbound
range = new PortRange();
return new IPv4AddressAttribute(address, mask, range);
}
/**
*
*/
public String encode() {
String str = getAddress().getHostAddress();
if (getMask() != null)
str += getMask().getHostAddress();
if (!getRange().isUnbound())
str += ":" + getRange().encode();
return str;
}
}
| 6,257 | 39.115385 | 99 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/StringAttribute.java | /*
* @(#)StringAttribute.java
*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import java.net.URI;
import org.w3c.dom.Node;
/**
* Representation of an xs:string value. This class supports parsing xs:string values. All objects
* of this class are immutable and all methods of the class are thread-safe.
* <p>
* Note that there was some confusion in the XACML specification about whether this datatype should
* be able to handle XML elements (ie, whether <AttributeValue
* DataType="...string"><foo/> </AttributeValue> is valid). This has been clarified
* to provide the correct requirement that a string may not contain mixed content (ie, the example
* provided here is invalid). If you need to specify something like this with the string datatype,
* then you must escape the <code><</code> and <code>></code> characters.
*
* @since 1.0
* @author Marco Barreno
* @author Seth Proctor
* @author Steve Hanna
*/
public class StringAttribute extends AttributeValue {
/**
* Official name of this type
*/
public static final String identifier = "http://www.w3.org/2001/XMLSchema#string";
/**
* URI version of name for this type
* <p>
* This field is initialized by a static initializer so that we can catch any exceptions thrown
* by URI(String) and transform them into a RuntimeException, since this should never happen but
* should be reported properly if it ever does.
*/
private static URI identifierURI;
/**
* RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if
* none.
*/
private static RuntimeException earlyException;
/**
* Static initializer that initializes the identifierURI class field so that we can catch any
* exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions
* should never happen but should be reported properly if they ever do.
*/
static {
try {
identifierURI = new URI(identifier);
} catch (Exception e) {
earlyException = new IllegalArgumentException();
earlyException.initCause(e);
}
};
/**
* The actual String value that this object represents.
*/
private String value;
/**
* Creates a new <code>StringAttribute</code> that represents the String value supplied.
*
* @param value the <code>String</code> value to be represented
*/
public StringAttribute(String value) {
super(identifierURI);
// Shouldn't happen, but just in case...
if (earlyException != null)
throw earlyException;
if (value == null)
this.value = "";
else
this.value = value;
}
/**
* Returns a new <code>StringAttribute</code> that represents the xs:string at a particular DOM
* node.
*
* @param root the <code>Node</code> that contains the desired value
* @return a new <code>StringAttribute</code> representing the appropriate value (null if there
* is a parsing error)
*/
public static StringAttribute getInstance(Node root) {
Node node = root.getFirstChild();
// Strings are allowed to have an empty AttributeValue element and are
// just treated as empty strings...we have to handle this case
if (node == null)
return new StringAttribute("");
// get the type of the node
short type = node.getNodeType();
// now see if we have (effectively) a simple string value
if ((type == Node.TEXT_NODE) || (type == Node.CDATA_SECTION_NODE)
|| (type == Node.COMMENT_NODE)) {
return getInstance(node.getNodeValue());
}
// there is some confusion in the specifications about what should
// happen at this point, but the strict reading of the XMLSchema
// specification suggests that this should be an error
return null;
}
/**
* Returns a new <code>StringAttribute</code> that represents the xs:string value indicated by
* the <code>String</code> provided.
*
* @param value a string representing the desired value
* @return a new <code>StringAttribute</code> representing the appropriate value
*/
public static StringAttribute getInstance(String value) {
return new StringAttribute(value);
}
/**
* Returns the <code>String</code> value represented by this object.
*
* @return the <code>String</code> value
*/
public String getValue() {
return value;
}
/**
* Returns true if the input is an instance of this class and if its value equals the value
* contained in this class.
*
* @param o the object to compare
*
* @return true if this object and the input represent the same value
*/
public boolean equals(Object o) {
if (!(o instanceof StringAttribute))
return false;
StringAttribute other = (StringAttribute) o;
return value.equals(other.value);
}
/**
* Returns the hashcode value used to index and compare this object with others of the same
* type. Typically this is the hashcode of the backing data object.
*
* @return the object's hashcode value
*/
public int hashCode() {
return value.hashCode();
}
/**
* Converts to a String representation.
*
* @return the String representation
*/
public String toString() {
return "StringAttribute: \"" + value + "\"";
}
/**
*
*/
public String encode() {
return value;
}
}
| 7,502 | 34.559242 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/AttributeFactoryProxy.java | /*
* @(#)AttributeFactoryProxy.java
*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
/**
* A simple proxy interface used to install new <code>AttributeFactory</code>s.
*
* @since 1.2
* @author Seth Proctor
*/
public interface AttributeFactoryProxy {
/**
* Returns an instance of the <code>AttributeFactory</code> for which this is a proxy.
*
* @return an <code>AttributeFactory</code> instance
*/
public AttributeFactory getFactory();
}
| 2,244 | 40.574074 | 90 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/TimeAttribute.java | /*
* @(#)TimeAttribute.java
*
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import org.wso2.balana.ParsingException;
import org.wso2.balana.ProcessingException;
import java.net.URI;
import java.text.ParseException;
import java.util.Date;
import org.w3c.dom.Node;
/**
* Representation of an xs:time value. This class supports parsing xs:time values. All objects of
* this class are immutable and thread-safe. The <code>Date</code> objects returned are not, but
* these objects are cloned before being returned.
*
* @since 1.0
* @author Steve Hanna
* @author Seth Proctor
*/
public class TimeAttribute extends AttributeValue {
/**
* Official name of this type
*/
public static final String identifier = "http://www.w3.org/2001/XMLSchema#time";
/**
* URI version of name for this type
* <p>
* This field is initialized by a static initializer so that we can catch any exceptions thrown
* by URI(String) and transform them into a RuntimeException, since this should never happen but
* should be reported properly if it ever does.
* <p>
* This object is used for synchronization whenever we need protection across this whole class.
*/
private static URI identifierURI;
/**
* RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if
* none.
*/
private static RuntimeException earlyException;
/**
* Static initializer that initializes the identifierURI class field so that we can catch any
* exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions
* should never happen but should be reported properly if they ever do.
*/
static {
try {
identifierURI = new URI(identifier);
} catch (Exception e) {
earlyException = new IllegalArgumentException();
earlyException.initCause(e);
}
};
/**
* Time zone value that indicates that the time zone was not specified.
*/
public static final int TZ_UNSPECIFIED = -1000000;
/**
* The time that this object represents in second resolution, in milliseconds GMT, with zero
* being midnight. If no time zone was specified, the local time zone is used to convert to
* milliseconds relative to GMT.
*/
private long timeGMT;
/**
* The number of nanoseconds beyond the time given by the timeGMT field. The XML Query document
* says that fractional seconds must be supported down to at least 100 nanosecond resolution.
* The Date class only supports milliseconds, so we include here support for nanosecond
* resolution.
*/
private int nanoseconds;
// NOTE: now that we're not using a Date object, the above two variables
// could be condensed, and the interface could be changed so we don't
// need to worry about tracking the time values separately
/**
* The time zone specified for this object (or TZ_UNSPECIFIED if unspecified). The offset to
* GMT, in minutes.
*/
private int timeZone;
/**
* The time zone actually used for this object (if it was originally unspecified, the default
* time zone used). The offset to GMT, in minutes.
*/
private int defaultedTimeZone;
/**
* Cached encoded value (null if not cached yet).
*/
private String encodedValue = null;
/**
* Creates a new <code>TimeAttribute</code> that represents the current time in the current time
* zone.
*/
public TimeAttribute() {
this(new Date());
}
/**
* Creates a new <code>TimeAttribute</code> that represents the given time but uses the default
* timezone and offset values.
*
* @param time a <code>Date</code> object representing the specified time down to second
* resolution. This date should have a date of 01/01/1970. If it does not, such a
* date will be forced. If this object has non-zero milliseconds, they are combined
* with the nanoseconds parameter.
*/
public TimeAttribute(Date time) {
super(identifierURI);
int currOffset = DateTimeAttribute.getDefaultTZOffset(time);
init(time, 0, currOffset, currOffset);
}
/**
* Creates a new <code>TimeAttribute</code> that represents the time supplied.
*
* @param time a <code>Date</code> object representing the specified time down to second
* resolution. This date should have a date of 01/01/1970. If it does not, such a
* date will be forced. If this object has non-zero milliseconds, they are combined
* with the nanoseconds parameter.
* @param nanoseconds the number of nanoseconds beyond the Date specified in the date parameter
* @param timeZone the time zone specified for this object (or TZ_UNSPECIFIED if unspecified).
* The offset to GMT, in minutes.
* @param defaultedTimeZone the time zone actually used for this object, which must be
* specified. The offset to GMT, in minutes.
*/
public TimeAttribute(Date time, int nanoseconds, int timeZone, int defaultedTimeZone) {
super(identifierURI);
// if the timezone is unspecified, it's illegal for the defaulted
// timezone to also be unspecified
if ((timeZone == TZ_UNSPECIFIED) && (defaultedTimeZone == TZ_UNSPECIFIED))
throw new ProcessingException("default timezone must be specified"
+ "when a timezone is provided");
init(time, nanoseconds, timeZone, defaultedTimeZone);
}
/**
* Initialization code shared by constructors.
*
* @param date a <code>Date</code> object representing the specified time down to second
* resolution. This date should have a date of 01/01/1970. If it does not, such a
* date will be forced. If this object has non-zero milliseconds, they are combined
* with the nanoseconds parameter.
* @param nanoseconds the number of nanoseconds beyond the Date specified in the date parameter
* @param timeZone the time zone specified for this object (or TZ_UNSPECIFIED if unspecified).
* The offset to GMT, in minutes.
* @param defaultedTimeZone the time zone actually used for this object (if it was originally
* unspecified, the default time zone used). The offset to GMT, in minutes.
*/
private void init(Date date, int nanoseconds, int timeZone, int defaultedTimeZone) {
// Shouldn't happen, but just in case...
if (earlyException != null)
throw earlyException;
// get a temporary copy of the date
Date tmpDate = (Date) (date.clone());
// Combine the nanoseconds so they are between 0 and 999,999,999
this.nanoseconds = DateTimeAttribute.combineNanos(tmpDate, nanoseconds);
// now that the date has been (potentially) updated, store the time
this.timeGMT = tmpDate.getTime();
// keep track of the timezone values
this.timeZone = timeZone;
this.defaultedTimeZone = defaultedTimeZone;
// Check that the date is normalized to 1/1/70
if ((timeGMT >= DateAttribute.MILLIS_PER_DAY) || (timeGMT < 0)) {
timeGMT = timeGMT % DateAttribute.MILLIS_PER_DAY;
// if we had a negative value then we need to shift by a day
if (timeGMT < 0)
timeGMT += DateAttribute.MILLIS_PER_DAY;
}
}
/**
* Returns a new <code>TimeAttribute</code> that represents the xs:time at a particular DOM
* node.
*
* @param root the <code>Node</code> that contains the desired value
* @return a new <code>TimeAttribute</code> representing the appropriate value (null if there is
* a parsing error)
*/
public static TimeAttribute getInstance(Node root) throws ParsingException,
NumberFormatException, ParseException {
return getInstance(root.getFirstChild().getNodeValue());
}
/**
* Returns a new <code>TimeAttribute</code> that represents the xs:time value indicated by the
* string provided.
*
* @param value a string representing the desired value
* @return a new <code>TimeAttribute</code> representing the desired value (null if there is a
* parsing error)
* @throws ParsingException if any problems occurred while parsing
*/
public static TimeAttribute getInstance(String value) throws ParsingException,
NumberFormatException, ParseException {
// Prepend date string for Jan 1 1970 and use the
// DateTimeAttribute parsing code.
value = "1970-01-01T" + value;
DateTimeAttribute dateTime = DateTimeAttribute.getInstance(value);
// if there was no explicit TZ provided, then we want to make sure
// the that the defaulting is done correctly, especially since 1/1/70
// is always out of daylight savings time
Date dateValue = dateTime.getValue();
int defaultedTimeZone = dateTime.getDefaultedTimeZone();
if (dateTime.getTimeZone() == TZ_UNSPECIFIED) {
int newDefTimeZone = DateTimeAttribute.getDefaultTZOffset(new Date());
dateValue = new Date(dateValue.getTime() - (newDefTimeZone - defaultedTimeZone)
* DateAttribute.MILLIS_PER_MINUTE);
defaultedTimeZone = newDefTimeZone;
}
return new TimeAttribute(dateValue, dateTime.getNanoseconds(), dateTime.getTimeZone(),
defaultedTimeZone);
}
/**
* Gets the time represented by this object. The return value is a <code>Date</code> object
* representing the specified time down to second resolution with a date of January 1, 1970.
* Subsecond values are handled by the {@link #getNanoseconds getNanoseconds} method.
*
* @return a <code>Date</code> object representing the time represented by this object
*/
public Date getValue() {
return new Date(timeGMT);
}
/**
* Gets the number of milliseconds since midnight GMT that this attribute value represents. This
* is the same time returned by <code>getValue</code>, and likewise the milliseconds are
* provided with second resolution.
*
* @return milliseconds since midnight GMT
*/
public long getMilliseconds() {
return timeGMT;
}
/**
* Gets the nanoseconds of this object.
*
* @return the number of nanoseconds
*/
public int getNanoseconds() {
return nanoseconds;
}
/**
* Gets the time zone of this object (or TZ_UNSPECIFIED if unspecified).
*
* @return the offset to GMT in minutes (positive or negative)
*/
public int getTimeZone() {
return timeZone;
}
/**
* Gets the time zone actually used for this object (if it was originally unspecified, the
* default time zone used).
*
* @return the offset to GMT in minutes (positive or negative)
*/
public int getDefaultedTimeZone() {
return defaultedTimeZone;
}
/**
* Returns true if the input is an instance of this class and if its value equals the value
* contained in this class.
*
* @param o the object to compare
*
* @return true if this object and the input represent the same value
*/
public boolean equals(Object o) {
if (!(o instanceof TimeAttribute))
return false;
TimeAttribute other = (TimeAttribute) o;
return (timeGMT == other.timeGMT && (nanoseconds == other.nanoseconds));
}
/**
* Returns the hashcode value used to index and compare this object with others of the same
* type. Typically this is the hashcode of the backing data object.
*
* @return the object's hashcode value
*/
public int hashCode() {
// the standard Date hashcode is used here...
int hashCode = (int) (timeGMT ^ (timeGMT >>> 32));
// ...but both the timeGMT and the nanoseconds fields are considered
// by the equals method, so it's best if the hashCode is derived
// from both of those fields.
hashCode = (31 * hashCode) + nanoseconds;
return hashCode;
}
/**
* Converts to a String representation.
*
* @return the String representation
*/
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("TimeAttribute: [\n");
// calculate the GMT value of this time
long secsGMT = timeGMT / 1000;
long minsGMT = secsGMT / 60;
secsGMT = secsGMT % 60;
long hoursGMT = minsGMT / 60;
minsGMT = minsGMT % 60;
// put the right number of zeros in place
String hoursStr = (hoursGMT < 10) ? "0" + hoursGMT : "" + hoursGMT;
String minsStr = (minsGMT < 10) ? "0" + minsGMT : "" + minsGMT;
String secsStr = (secsGMT < 10) ? "0" + secsGMT : "" + secsGMT;
sb.append(" Time GMT: " + hoursStr + ":" + minsStr + ":" + secsStr);
sb.append(" Nanoseconds: " + nanoseconds);
sb.append(" TimeZone: " + timeZone);
sb.append(" Defaulted TimeZone: " + defaultedTimeZone);
sb.append("]");
return sb.toString();
}
/**
* Encodes the value in a form suitable for including in XML data like a request or an
* obligation. This returns a time value that could in turn be used by the factory to create a
* new instance with the same value.
*
* @return a <code>String</code> form of the value
*/
public String encode() {
if (encodedValue != null)
return encodedValue;
// "hh:mm:ss.sssssssss+hh:mm".length() = 27
StringBuffer buf = new StringBuffer(27);
// get the correct time for the timezone being used
int millis = (int) timeGMT;
if (timeZone == TZ_UNSPECIFIED)
millis += (defaultedTimeZone * DateAttribute.MILLIS_PER_MINUTE);
else
millis += (timeZone * DateAttribute.MILLIS_PER_MINUTE);
if (millis < 0) {
millis += DateAttribute.MILLIS_PER_DAY;
} else if (millis >= DateAttribute.MILLIS_PER_DAY) {
millis -= DateAttribute.MILLIS_PER_DAY;
}
// now generate the time string
int hour = millis / DateAttribute.MILLIS_PER_HOUR;
millis = millis % DateAttribute.MILLIS_PER_HOUR;
buf.append(DateAttribute.zeroPadInt(hour, 2));
buf.append(':');
int minute = millis / DateAttribute.MILLIS_PER_MINUTE;
millis = millis % DateAttribute.MILLIS_PER_MINUTE;
buf.append(DateAttribute.zeroPadInt(minute, 2));
buf.append(':');
int second = millis / DateAttribute.MILLIS_PER_SECOND;
buf.append(DateAttribute.zeroPadInt(second, 2));
// add any nanoseconds
if (nanoseconds != 0) {
buf.append('.');
buf.append(DateAttribute.zeroPadInt(nanoseconds, 9));
}
// if there is a specified timezone, then include that in the encoding
if (timeZone != TZ_UNSPECIFIED) {
int tzNoSign = timeZone;
if (timeZone < 0) {
tzNoSign = -tzNoSign;
buf.append('-');
} else
buf.append('+');
int tzHours = tzNoSign / 60;
buf.append(DateAttribute.zeroPadInt(tzHours, 2));
buf.append(':');
int tzMinutes = tzNoSign % 60;
buf.append(DateAttribute.zeroPadInt(tzMinutes, 2));
}
// remember the encoding for later
encodedValue = buf.toString();
return encodedValue;
}
}
| 17,638 | 37.597374 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/AttributeDesignator.java | /*
* @(#)AttributeDesignator.java
*
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.balana.*;
import org.wso2.balana.cond.EvaluationResult;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.ctx.MissingAttributeDetail;
import org.wso2.balana.ctx.Status;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.wso2.balana.ctx.StatusDetail;
/**
* Represents all four kinds of Designators in XACML.
*
* @author Seth Proctor
* @since 1.0
*/
public class AttributeDesignator extends AbstractDesignator {
/**
* Tells designator to search in the subject section of the request
*/
public static final int SUBJECT_TARGET = 0;
/**
* Tells designator to search in the resource section of the request
*/
public static final int RESOURCE_TARGET = 1;
/**
* Tells designator to search in the action section of the request
*/
public static final int ACTION_TARGET = 2;
/**
* Tells designator to search in the environment section of the request
*/
public static final int ENVIRONMENT_TARGET = 3;
/**
* The standard URI for the default subject category value
*/
public static final String SUBJECT_CATEGORY_DEFAULT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject";
// helper array of strings
static final private String[] targetTypes = {"Subject", "Resource", "Action", "Environment"};
// the type of designator we are
private int target;
// required attributes
private URI type;
private URI id;
// optional attribute
private String issuer;
// must resolution find something
private boolean mustBePresent;
// here we are defined a category
// This is used only for Subject in XACML2.
// but adding it for all designators
private URI category;
// the logger we'll use for all messages
private static final Log logger = LogFactory.getLog(AttributeDesignator.class);
/**
* Creates a new <code>AttributeDesignator</code> without the optional issuer.
*
* @param target the type of designator as specified by the 4 member *_TARGET fields
* @param type the data type resolved by this designator
* @param id the attribute id looked for by this designator
* @param mustBePresent whether resolution must find a value
*/
public AttributeDesignator(int target, URI type, URI id, boolean mustBePresent) {
this(target, type, id, mustBePresent, null, null);
}
/**
* Creates a new <code>AttributeDesignator</code> with the optional issuer.
*
* @param target the type of designator as specified by the 4 member *_TARGET fields
* @param type the data type resolved by this designator
* @param id the attribute id looked for by this designator
* @param mustBePresent whether resolution must find a value
* @param issuer the issuer of the values to search for or null if no issuer is specified
* @throws IllegalArgumentException if the input target isn't a valid value
*/
public AttributeDesignator(int target, URI type, URI id, boolean mustBePresent, String issuer)
throws IllegalArgumentException {
this(target, type, id, mustBePresent, null, null);
}
/**
* Creates a new <code>AttributeDesignator</code> with the optional issuer.
*
* @param target the type of designator as specified by the 4 member *_TARGET fields
* @param type the data type resolved by this designator
* @param id the attribute id looked for by this designator
* @param mustBePresent whether resolution must find a value
* @param issuer the issuer of the values to search for or null if no issuer is specified
* @throws IllegalArgumentException if the input target isn't a valid value
*/
public AttributeDesignator(int target, URI type, URI id, boolean mustBePresent, String issuer,
URI category) throws IllegalArgumentException {
// check if input target is a valid value
if ((target != SUBJECT_TARGET) && (target != RESOURCE_TARGET) && (target != ACTION_TARGET)
&& (target != ENVIRONMENT_TARGET))
throw new IllegalArgumentException("Input target is not a valid" + "value");
this.target = target;
this.type = type;
this.id = id;
this.mustBePresent = mustBePresent;
this.issuer = issuer;
this.category = category;
}
/**
* Creates a new <code>AttributeDesignator</code> based on the DOM root of the XML data.
*
* @param root the DOM root of the AttributeDesignatorType XML type
* @return the designator
* @throws ParsingException if the AttributeDesignatorType was invalid
*/
public static AttributeDesignator getInstance(Node root) throws ParsingException {
URI type = null;
URI id = null;
String issuer = null;
boolean mustBePresent = false;
URI category = null;
int target;
String tagName = DOMHelper.getLocalName(root);
if (tagName.equals("SubjectAttributeDesignator")) {
target = SUBJECT_TARGET;
} else if (tagName.equals("ResourceAttributeDesignator")) {
target = RESOURCE_TARGET;
} else if (tagName.equals("ActionAttributeDesignator")) {
target = ACTION_TARGET;
} else if (tagName.equals("EnvironmentAttributeDesignator")) {
target = ENVIRONMENT_TARGET;
} else {
throw new ParsingException("AttributeDesignator cannot be constructed using " + "type: "
+ DOMHelper.getLocalName(root));
}
NamedNodeMap attrs = root.getAttributes();
try {
// there's always an Id
id = new URI(attrs.getNamedItem("AttributeId").getNodeValue());
} catch (Exception e) {
throw new ParsingException("Required AttributeId missing in " + "AttributeDesignator",
e);
}
try {
// there's always a data type
type = new URI(attrs.getNamedItem("DataType").getNodeValue());
} catch (Exception e) {
throw new ParsingException("Required DataType missing in " + "AttributeDesignator", e);
}
try {
// there might be an issuer
Node node = attrs.getNamedItem("Issuer");
if (node != null)
issuer = node.getNodeValue();
// if it's for the Subject section, there's another attr
if (target == SUBJECT_TARGET) {
Node scnode = attrs.getNamedItem("SubjectCategory");
if (scnode != null){
category = new URI(scnode.getNodeValue());
} else {
category = new URI(SUBJECT_CATEGORY_DEFAULT);
}
} else if (target == RESOURCE_TARGET){
category = new URI(XACMLConstants.RESOURCE_CATEGORY);
} else if (target == ACTION_TARGET){
category = new URI(XACMLConstants.ACTION_CATEGORY);
} else if (target == ENVIRONMENT_TARGET) {
category = new URI(XACMLConstants.ENT_CATEGORY);
}
// there might be a mustBePresent flag
node = attrs.getNamedItem("MustBePresent");
if (node != null)
if (node.getNodeValue().equals("true"))
mustBePresent = true;
} catch (Exception e) {
// this shouldn't ever happen, but in theory something could go
// wrong in the code in this try block
throw new ParsingException(
"Error parsing AttributeDesignator " + "optional attributes", e);
}
return new AttributeDesignator(target, type, id, mustBePresent, issuer, category);
}
/**
* Returns the type of this designator as specified by the *_TARGET fields.
*
* @return the designator type
*/
public int getDesignatorType() {
return target;
}
/**
* Returns the type of attribute that is resolved by this designator. While an AD will always
* return a bag, this method will always return the type that is stored in the bag.
*
* @return the attribute type
*/
public URI getType() {
return type;
}
/**
* Returns the AttributeId of the values resolved by this designator.
*
* @return identifier for the values to resolve
*/
public URI getId() {
return id;
}
/**
* Returns the subject category for this designator. If this is not a SubjectAttributeDesignator
* then this will always return null.
*
* @return the subject category or null if this isn't a SubjectAttributeDesignator
*/
public URI getCategory() {
return category;
}
/**
* Returns the issuer of the values resolved by this designator if specified.
*
* @return the attribute issuer or null if unspecified
*/
public String getIssuer() {
return issuer;
}
/**
* Returns whether or not a value is required to be resolved by this designator.
*
* @return true if a value is required, false otherwise
*/
public boolean mustBePresent() {
return mustBePresent;
}
/**
* Always returns true, since a designator always returns a bag of attribute values.
*
* @return true
*/
public boolean returnsBag() {
return true;
}
/**
* Always returns true, since a designator always returns a bag of attribute values.
*
* @return true
* @deprecated As of 2.0, you should use the <code>returnsBag</code> method from the
* super-interface <code>Expression</code>.
*/
public boolean evaluatesToBag() {
return true;
}
/**
* Always returns an empty list since designators never have children.
*
* @return an empty <code>List</code>
*/
public List getChildren() {
return Collections.EMPTY_LIST;
}
/**
* Evaluates the pre-assigned meta-data against the given context, trying to find some matching
* values.
*
* @param evaluationCtx the representation of the request
* @return a result containing a bag either empty because no values were found or containing at
* least one value, or status associated with an Indeterminate result
*/
public EvaluationResult evaluate(EvaluationCtx evaluationCtx) {
EvaluationResult result = null;
// look in the right section for some attribute values
switch (target) {
case SUBJECT_TARGET:
result = evaluationCtx.getAttribute(type, id, issuer, category);
break;
case RESOURCE_TARGET:
result = evaluationCtx.getAttribute(type, id, issuer, category);
break;
case ACTION_TARGET:
result = evaluationCtx.getAttribute(type, id, issuer, category);
break;
case ENVIRONMENT_TARGET:
result = evaluationCtx.getAttribute(type, id, issuer, category);
break;
}
// if the lookup was indeterminate, then we return immediately
if(result != null){
if (result.indeterminate())
return result;
BagAttribute bag = (BagAttribute) (result.getAttributeValue());
if (bag.isEmpty()) {
// if it's empty, this may be an error
if (mustBePresent) {
if (logger.isDebugEnabled()) {
logger.debug("AttributeDesignator failed to resolve a "
+ "value for a required attribute: " + id.toString());
}
ArrayList<String> code = new ArrayList<String>();
code.add(Status.STATUS_MISSING_ATTRIBUTE);
ArrayList<MissingAttributeDetail> missingAttributes = new ArrayList<MissingAttributeDetail>();
MissingAttributeDetail missingAttribute = new MissingAttributeDetail(id, type,
category, issuer, null, XACMLConstants.XACML_VERSION_3_0);
missingAttributes.add(missingAttribute);
StatusDetail detail = new StatusDetail(missingAttributes);
String message = "Couldn't find " + targetTypes[target]
+ "AttributeDesignator attribute";
// Note that there is a bug in the XACML spec. You can't //TODO
// specify an identifier without specifying acceptable
// values. Until this is fixed, this code will only
// return the status code, and not any hints about what
// was missing
/*
* List attrs = new ArrayList(); attrs.add(new Attribute(id, ((issuer == null) ?
* null : issuer.toString()), null, null)); StatusDetail detail = new
* StatusDetail(attrs);
*/
return new EvaluationResult(new Status(code, message, detail));
}
}
} else {
ArrayList<String> code = new ArrayList<String>();
code.add(Status.STATUS_MISSING_ATTRIBUTE);
ArrayList<MissingAttributeDetail> missingAttributes = new ArrayList<MissingAttributeDetail>();
MissingAttributeDetail missingAttribute = new MissingAttributeDetail(id, type,
category, issuer, null, XACMLConstants.XACML_VERSION_3_0);
missingAttributes.add(missingAttribute);
StatusDetail detail = new StatusDetail(missingAttributes);
String message = "Couldn't find " + targetTypes[target]
+ "AttributeDesignator attribute";
return new EvaluationResult(new Status(code, message, detail)); //TODO
}
// if we got here the bag wasn't empty, or mustBePresent was false,
// so we just return the result
return result;
}
/**
* Encodes this <code>AttributeDesignator</code> into its XML form and writes this out to the provided
* <code>StringBuilder<code>
*
* @param builder string stream into which the XML-encoded data is written
*/
public void encode(StringBuilder builder) {
builder.append("<").append(targetTypes[target]).append("AttributeDesignator");
if ((target == SUBJECT_TARGET) && (category != null)){
builder.append(" SubjectCategory=\"").append(category.toString()).append("\"");
}
builder.append(" AttributeId=\"").append(id.toString()).append("\"");
builder.append(" DataType=\"").append(type.toString()).append("\"");
if (issuer != null)
builder.append(" Issuer=\"").append(issuer).append("\"");
if (mustBePresent){
builder.append(" MustBePresent=\"true\"");
}
builder.append("/>\n");
}
}
| 17,374 | 37.10307 | 121 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/DoubleAttribute.java | /*
* @(#)DoubleAttribute.java
*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import java.net.URI;
import org.w3c.dom.Node;
/**
* Representation of an xsi:double value. This class supports parsing xsi:double values. All objects
* of this class are immutable and all methods of the class are thread-safe.
*
* @since 1.0
* @author Marco Barreno
* @author Seth Proctor
* @author Steve Hanna
*/
public class DoubleAttribute extends AttributeValue {
/**
* Official name of this type
*/
public static final String identifier = "http://www.w3.org/2001/XMLSchema#double";
/**
* URI version of name for this type
* <p>
* This field is initialized by a static initializer so that we can catch any exceptions thrown
* by URI(String) and transform them into a RuntimeException, since this should never happen but
* should be reported properly if it ever does.
*/
private static URI identifierURI;
/**
* RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if
* none.
*/
private static RuntimeException earlyException;
/**
* Static initializer that initializes the identifierURI class field so that we can catch any
* exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions
* should never happen but should be reported properly if they ever do.
*/
static {
try {
identifierURI = new URI(identifier);
} catch (Exception e) {
earlyException = new IllegalArgumentException();
earlyException.initCause(e);
}
};
/**
* The actual double value that this object represents.
*/
private double value;
/**
* Creates a new <code>DoubleAttribute</code> that represents the double value supplied.
*
* @param value the <code>double</code> value to be represented
*/
public DoubleAttribute(double value) {
super(identifierURI);
// Shouldn't happen, but just in case...
if (earlyException != null)
throw earlyException;
this.value = value;
}
/**
* Returns a new <code>DoubleAttribute</code> that represents the xsi:double at a particular DOM
* node.
*
* @param root the <code>Node</code> that contains the desired value
* @return a new <code>DoubleAttribute</code> representing the appropriate value (null if there
* is a parsing error)
* @throws NumberFormatException if the string form is not a double
*/
public static DoubleAttribute getInstance(Node root) throws NumberFormatException {
return getInstance(root.getFirstChild().getNodeValue());
}
/**
* Returns a new <code>DoubleAttribute</code> that represents the xsi:double value indicated by
* the string provided.
*
* @param value a string representing the desired value
* @return a new <code>DoubleAttribute</code> representing the desired value (null if there is a
* parsing error)
* @throws NumberFormatException if the value is not a double
*/
public static DoubleAttribute getInstance(String value) {
// Convert "INF" to "Infinity"
if (value.endsWith("INF")) {
int infIndex = value.lastIndexOf("INF");
value = value.substring(0, infIndex) + "Infinity";
}
return new DoubleAttribute(Double.parseDouble(value));
}
/**
* Returns the <code>double</code> value represented by this object.
*
* @return the <code>double</code> value
*/
public double getValue() {
return value;
}
/**
* Returns true if the input is an instance of this class and if its value equals the value
* contained in this class.
*
* @param o the object to compare
*
* @return true if this object and the input represent the same value
*/
public boolean equals(Object o) {
if (!(o instanceof DoubleAttribute))
return false;
DoubleAttribute other = (DoubleAttribute) o;
// Handle the NaN case, where Java says NaNs are never
// equal and XML Query says they always are
if (Double.isNaN(value)) {
// this is a NaN, so see if the other is as well
if (Double.isNaN(other.value)) {
// they're both NaNs, so they're equal
return true;
} else {
// they're not both NaNs, so they're not equal
return false;
}
} else {
// not NaNs, so we can do a normal comparison
return (value == other.value);
}
}
/**
* Returns the hashcode value used to index and compare this object with others of the same
* type. Typically this is the hashcode of the backing data object.
*
* @return the object's hashcode value
*/
public int hashCode() {
long v = Double.doubleToLongBits(value);
return (int) (v ^ (v >>> 32));
}
/**
*
*/
public String encode() {
return String.valueOf(value);
}
}
| 6,968 | 34.375635 | 100 | java |
balana | balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/AttributeValue.java | /*
* @(#)AttributeValue.java
*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package org.wso2.balana.attr;
import org.wso2.balana.ctx.EvaluationCtx;
import org.wso2.balana.Indenter;
import org.wso2.balana.cond.Evaluatable;
import org.wso2.balana.cond.EvaluationResult;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.util.Collections;
import java.util.List;
/**
* The base type for all datatypes used in a policy or request/response, this abstract class
* represents a value for a given attribute type. All the required types defined in the XACML
* specification are provided as instances of <code>AttributeValue<code>s. If you want to
* provide a new type, extend this class and implement the
* <code>equals(Object)</code> and <code>hashCode</code> methods from <code>Object</code>, which are
* used for equality checking.
*
* @since 1.0
* @author Seth Proctor
*/
public abstract class AttributeValue implements Evaluatable {
// the type of this attribute
private URI type;
/**
* Constructor that takes the specific attribute type.
*
* @param type the attribute's type
*/
protected AttributeValue(URI type) {
this.type = type;
}
/**
* Returns the type of this attribute value. By default this always returns the type passed to
* the constructor.
*
* @return the attribute's type
*/
public URI getType() {
return type;
}
/**
* Returns whether or not this value is actually a bag of values. This is a required interface
* from <code>Expression</code>, but the more meaningful <code>isBag</code> method is used by
* <code>AttributeValue</code>s, so this method is declared as final and calls the
* <code>isBag</code> method for this value.
*
* @return true if this is a bag of values, false otherwise
*/
public final boolean returnsBag() {
return isBag();
}
/**
* Returns whether or not this value is actually a bag of values. This is a required interface
* from <code>Evaluatable</code>, but the more meaningful <code>isBag</code> method is used by
* <code>AttributeValue</code>s, so this method is declared as final and calls the
* <code>isBag</code> method for this value.
*
*
* @deprecated As of 2.0, you should use the <code>returnsBag</code> method from the
* super-interface <code>Expression</code>.
*
* @return true if this is a bag of values, false otherwise
*/
public final boolean evaluatesToBag() {
return isBag();
}
/**
* Always returns an empty list since values never have children.
*
* @return an empty <code>List</code>
*/
public List getChildren() {
return Collections.EMPTY_LIST;
}
/**
* Returns whether or not this value is actually a bag of values. By default this returns
* <code>false</code>. Typically, only the <code>BagAttribute</code> should ever override this
* to return <code>true</code>.
*
* @return true if this is a bag of values, false otherwise
*/
public boolean isBag() {
return false;
}
/**
* Implements the required interface from <code>Evaluatable</code>. Since there is nothing to
* evaluate in an attribute value, the default result is just this instance. Override this
* method if you want special behavior, like a dynamic value.
*
* @param context the representation of the request
*
* @return a successful evaluation containing this value
*/
public EvaluationResult evaluate(EvaluationCtx context) {
return new EvaluationResult(this);
}
/**
* Encodes the value in a form suitable for including in XML data like a request or an
* obligation. This must return a value that could in turn be used by the factory to create a
* new instance with the same value.
*
* @return a <code>String</code> form of the value
*/
public abstract String encode();
/**
* Encodes this <code>AttributeValue</code> into its XML representation and writes this encoding
* to the given <code>StringBuilder</code> This will always produce the version
* used in a policy rather than that used in a request, so this is equivalent to calling
* <code>encodeWithTags(true)</code> and then stuffing that into a stream.
*
* @param builder string stream into which the XML-encoded data is written
*/
public void encode(StringBuilder builder) {
builder.append(encodeWithTags(true));
}
/**
* Encodes the value and includes the AttributeValue XML tags so that the resulting string can
* be included in a valid XACML policy or Request/Response. The <code>boolean</code> parameter
* lets you include the DataType attribute, which is required in a policy but not allowed in a
* Request or Response.
*
* @param includeType include the DataType XML attribute if <code>true</code>, exclude if
* <code>false</code>
*
* @return a <code>String</code> encoding including the XML tags
*/
public String encodeWithTags(boolean includeType) {
if (includeType && type != null) {
return "<AttributeValue DataType=\"" + type.toString() + "\">" + encode()
+ "</AttributeValue>";
} else {
return "<AttributeValue>" + encode() + "</AttributeValue>";
}
}
}
| 7,297 | 37.209424 | 100 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.