📄 slcodec.java
字号:
}
buffer.append(')');
}
private void encodeAndAppend(AbsPrimitive val) throws CodecException {
Object v = val.getObject();
if (v instanceof Date)
buffer.append(ISO8601.toString((Date)v));
else if (v instanceof Number) {
buffer.append(v.toString());
if (preserveJavaTypes) {
if (v instanceof Long) {
buffer.append('L');
}
else if (v instanceof Float) {
buffer.append('F');
}
}
}
else if (v instanceof byte[]) {
// Note: Currently uses Java default charset, may need to use another one
byte[] b = (byte[]) v;
buffer.append('#');
buffer.append(b.length);
buffer.append('"');
// FIXME: Should we use base64 encoding?
buffer.append(new String(b));
}
else if (v instanceof Boolean)
buffer.append(v.toString());
else {
String vs = v.toString();
if ( (CaseInsensitiveString.equalsIgnoreCase("true",vs)) ||
(CaseInsensitiveString.equalsIgnoreCase("false",vs)) ) {
// quote true and false to avoid confusion with booleans
buffer.append('"');
buffer.append(vs);
buffer.append('"');
} else
encodeAndAppend(vs);
}
}
private void encodeAndAppend(AbsObject val) throws CodecException {
if (val instanceof AbsPrimitive) encodeAndAppend( (AbsPrimitive)val);
else if (val instanceof AbsPredicate) encodeAndAppend( (AbsPredicate)val);
else if (val instanceof AbsIRE) encodeAndAppend( (AbsIRE)val);
else if (val instanceof AbsVariable) encodeAndAppend( (AbsVariable)val);
// if (val instanceof AbsAgentAction) return toString( (AbsAgentAction)val);
else if (val instanceof AbsAggregate) encodeAndAppend( (AbsAggregate)val);
else if (val instanceof AbsConcept) encodeAndAppend( (AbsConcept)val);
else throw new CodecException("SLCodec cannot encode this object "+val);
}
/**
* Decodes the content to an abstract description.
* @param content the content as a String.
* @return the content as an abstract description.
* @throws CodecException
*/
public AbsContentElement decode(String content) throws CodecException {
return decode(null, content);
}
/**
* Decodes the content to an abstract description.
* @param ontology the ontology.
* @param content the content as a String.
* @return the content as an abstract description.
* @throws CodecException
*/
public synchronized AbsContentElement decode(Ontology ontology, String content) throws CodecException {
try {
AbsContentElementList tuple = null;
if (preserveJavaTypes) {
extendedParser.reinit(ontology, content);
tuple = extendedParser.Content();
}
else {
parser.reinit(ontology, content);
tuple = parser.Content();
}
if (tuple.size() > 1)
return tuple;
else // if there is a single ContentExpression than return just it, not the tuple
return tuple.get(0);
} catch(Throwable e) { // both ParseException and TokenMgrError
throw new CodecException("Parse exception", e);
}
}
/**
* Decodes the content to an abstract description, where the content is known to be a Term.
* @param ontology the ontology.
* @param cterm the term as a String.
* @return the content as an abstract description.
* @throws CodecException
* @since JADE 3.4
*/
public synchronized AbsTerm decodeTerm(Ontology ontology, String term) throws CodecException {
try {
if (preserveJavaTypes) {
extendedParser.reinit(ontology, term);
return extendedParser.Term();
}
else {
parser.reinit(ontology, term);
return parser.Term();
}
} catch(Throwable e) { // both ParseException and TokenMgrError
throw new CodecException("Parse exception", e);
}
}
/**
* Encodes the content into a String, where the content is known to be a Term.
* @param ontology the ontology.
* @param term the termt as an abstract descriptor
* @return the content as a String
* @throws CodecException
* @since JADE 3.4
*/
public synchronized String encodeTerm(Ontology ontology, AbsTerm term) throws CodecException {
try {
domainOnto = ontology;
buffer = new StringBuffer();
encodeAndAppend(term);
return buffer.toString();
} finally {
buffer = null; //frees the memory
}
}
/**
* Decodes the content to an abstract description, where the content is known to be a Well-formed Formula
* @param ontology the ontology.
* @param formula the content as a String.
* @return the content as an abstract description.
* @throws CodecException
* @since JADE 3.4
*/
public synchronized AbsPredicate decodeFormula(Ontology ontology, String formula) throws CodecException {
try {
if (preserveJavaTypes) {
extendedParser.reinit(ontology, formula);
return extendedParser.Wff();
}
else {
parser.reinit(ontology, formula);
return parser.Wff();
}
} catch(Throwable e) { // both ParseException and TokenMgrError
throw new CodecException("Parse exception", e);
}
}
/**
* Encodes the content into a String, where the content is known to be a Well-formed Formula
* @param ontology the ontology.
* @param formula the formula as an abstract descriptor
* @return the content as a String
* @throws CodecException
* @since JADE 3.4
*/
public synchronized String encodeFormula(Ontology ontology, AbsPredicate formula) throws CodecException {
try {
domainOnto = ontology;
buffer = new StringBuffer();
encodeAndAppend(formula);
return buffer.toString();
} finally {
buffer = null; //frees the memory
}
}
public static void main(String[] args) {
SLCodec codec = null;
char contentType = 'C';
try {
codec = new SLCodec(Integer.parseInt(args[0]));
contentType = (args.length > 1 ? args[1].charAt(0) : 'C');
} catch (Exception e) {
System.out.println("usage: SLCodec SLLevel [ContentType]\n where SLLevel can be 0 for SL0, 1 for SL1, 2 for SL2, 3 or more for full SL \n and where ContentType is a char representing the type of content to be parsed: C for a contentexpression (default), T for a term, F for a formula");
System.exit(0);
}
while (true) {
try {
System.out.println("insert an SL " + (contentType == 'F' ? "Well-Formed Formula" : (contentType == 'T' ? "Term" : "Content Expression")) + " to parse (all the expression on a single line!): ");
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
String str = buff.readLine();
System.out.println("\n\n");
if (contentType == 'F') {
AbsPredicate result = codec.decodeFormula(null, str);
System.out.println("DUMP OF THE DECODE OUTPUT (just for debugging):");
System.out.println(result);
System.out.println("\n\n");
System.out.println("AFTER ENCODE:");
System.out.println(codec.encodeFormula(null, result));
System.out.println("\n\n");
} else if (contentType == 'T') {
AbsTerm result = codec.decodeTerm(null, str);
System.out.println("DUMP OF THE DECODE OUTPUT (just for debugging):");
System.out.println(result);
System.out.println("\n\n");
System.out.println("AFTER ENCODE:");
System.out.println(codec.encodeTerm(null, result));
System.out.println("\n\n");
} else {
AbsContentElement result = codec.decode(str);
System.out.println("DUMP OF THE DECODE OUTPUT (just for debugging):");
System.out.println(result);
System.out.println("\n\n");
System.out.println("AFTER ENCODE:");
System.out.println(codec.encode(result));
System.out.println("\n\n");
}
} catch(Exception pe) {
pe.printStackTrace();
//System.exit(0);
}
}
}
/**
* @return the ontology containing the schemas of the operator
* defined in this language
*/
public Ontology getInnerOntology() {
return slOnto;
}
private String[] getSlotNames(AbsObject abs) throws CodecException {
String[] slotNames = null;
String type = abs.getTypeName();
if (domainOnto != null) {
// If an ontology is specified, get the slot names from it
// (and not directly from the abstract descriptor val) to preserve
// the order
try {
ObjectSchema s = domainOnto.getSchema(type);
if (s == null) {
throw new CodecException("No schema found for symbol "+type);
}
slotNames = s.getNames();
}
catch (OntologyException oe) {
throw new CodecException("Error getting schema for symbol "+type, oe);
}
}
else {
slotNames = abs.getNames();
}
return slotNames;
}
private boolean getEncodingByOrder(AbsObject abs) throws CodecException {
if (domainOnto != null) {
String type = abs.getTypeName();
try {
ObjectSchema s = domainOnto.getSchema(type);
return s.getEncodingByOrder();
}
catch (Exception e) {
// Just ignore it
}
}
return false;
}
/**
* Encode the slots of an abstract descriptor by order, i.e.
* without writing the slot names. Also take into account that, in
* order to ensure a correct parsing, empty slots can only occur at
* the end.
* Append this encoded string to buffer.
*/
private void encodeSlotsByOrder(AbsObject val, String[] slotNames) throws CodecException {
boolean lastSlotEmpty = false;
for (int i=0; i<slotNames.length; i++) {
AbsTerm t = (AbsTerm)val.getAbsObject(slotNames[i]);
if (t != null) {
if (lastSlotEmpty) {
throw new CodecException("Non-empty slot "+slotNames[i]+" follows empty slot "+slotNames[i-1]);
}
buffer.append(' ');
encodeAndAppend(t);
}
else {
lastSlotEmpty = true;
}
}
}
/**
* Encode the slots of an abstract descriptor by name, i.e.
* writing for each non-empty slot the slot name followed by the
* slot value.
* Append this encoded string to buffer.
*/
private void encodeSlotsByName(AbsObject val, String[] slotNames) throws CodecException {
for (int i=0; i<slotNames.length; i++) {
AbsTerm t = (AbsTerm)val.getAbsObject(slotNames[i]);
if (t != null) {
// if this isn't un unnamed slot, then encode it otherwise just encode its value
if (!slotNames[i].startsWith(this.UNNAMEDPREFIX)) {
buffer.append(" :");
encodeAndAppend(slotNames[i]);
}
buffer.append(' ');
encodeAndAppend(t);
}
}
}
/**
* Restore parser after deserialization. <br>
* The readResolve method is called when ObjectInputStream has read an object from the stream
* and is preparing to return it to the caller. <br>
* The readResolve method is not invoked on the object until the object is fully constructed.
*/
protected Object readResolve() throws java.io.ObjectStreamException {
initParser();
return this;
}
//#MIDP_EXCLUDE_END
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -